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
JavaScript
mit
d09c48f2659dd3f9a24f459380e403249bff0c45
0
mirror-media/plate
var keystone = require('arch-keystone'); var transform = require('model-transform'); var Types = keystone.Field.Types; var Watch = new keystone.List('Watch', { track: true, sortable: true, }); var price = 'NTD30000以下, NTD30000~NTD70000, NTD70000~NTD150000, NTD150000~NTD300000, NTD300000~NTD500000, NTD500000~NTD1500000, NTD3000000以上'; Watch.add({ brand: { label: '品牌', type: Types.Relationship, ref: 'WatchBrand' }, name: { label: '品名', type: String }, type: { label: '型號', type: String }, style: { label: '錶款名稱', type: String }, series: { label: '系列', type: String }, watchImage: { label: '圖片', type: Types.ImageRelationship, ref: 'Image' }, price: { label: '價格', type: String }, ga: { label: '發表年份', type: Number}, limit: { label: '限量支數', type: Number, index: true}, sex: { label: '性別', type: Types.Select, options: '男錶款, 女錶款, 中性錶款', default: '中性錶款'}, luminous: { label: '夜光', type: Boolean, index: true}, movement: { label: '機芯', type: Types.Select, options: '自動上鏈, 手動上鏈, 石英, 光動能, 人動電能, GPS, 電波, 智能錶' }, power: { label: '動力', type: String }, size: { label: '錶殼尺寸', type: String }, color: { label: '面盤顏色', type: String }, youtube: { label: 'Youtube 影片', type: Types.Url }, watchfunction: { label: '功能', type: Types.Relationship, ref: 'WatchFunction', many: true }, material: { label: '材質', type: Types.Select, options: '不鏽鋼, 半金, 銅, 黃金, 玫瑰金, 白金, 鉑金, 鉑金, 鈦金屬, 特殊合金, 複合材質' }, waterproof: { label: '防水', type: Types.Select, options: '無, 30米, 50米, 100米, 200米, 300米, 600米, 1000米, 2000米, 2000米, 4000米' }, popular: { label: '熱門錶款', type: Boolean, index: true }, treasury: { label: '庫藏區', type: Boolean, index: true }, content: { label: '內文', type: Types.Html, wysiwyg: true, height: 400 }, relateds: { label: '相關文章', type: Types.Relationship, ref: 'Post', many: true }, relatedwatch: { label: '相似錶款', type: Types.Relationship, ref: 'Watch', many: true }, stores: { label: '錶店', type: Types.Relationship, ref: 'WatchStore', many: true }, createTime: { type: Types.Datetime, default: Date.now, utc: true }, }); transform.toJSON(Watch); Watch.defaultColumns = 'name, brand|20%, series|20%, type|20%, movement|20%'; Watch.register();
models/Watch.js
var keystone = require('arch-keystone'); var transform = require('model-transform'); var Types = keystone.Field.Types; var Watch = new keystone.List('Watch', { track: true, sortable: true, }); var price = 'NTD30000以下, NTD30000~NTD70000, NTD70000~NTD150000, NTD150000~NTD300000, NTD300000~NTD500000, NTD500000~NTD1500000, NTD3000000以上'; Watch.add({ brand: { label: '品牌', type: Types.Relationship, ref: 'WatchBrand' }, name: { label: '品名', type: String }, type: { label: '型號', type: String }, style: { label: '錶款名稱', type: String }, series: { label: '系列', type: String }, watchImage: { label: '圖片', type: Types.ImageRelationship, ref: 'Image' }, price: { label: '價格', type: String }, ga: { label: '發表年份', type: Number}, limit: { label: '限量支數', type: Number, index: true}, sex: { label: '性別', type: Types.Select, options: '男錶款, 女錶款, 中性錶款', default: '中性錶款'}, luminous: { label: '夜光', type: Types.Select, options: '有, 無', default: '有'}, movement: { label: '機芯', type: Types.Select, options: '自動上鏈, 手動上鏈, 石英, 光動能, 人動電能, GPS, 電波, 智能錶' }, power: { label: '動力', type: String }, watchfunction: { label: '功能', type: Types.Relationship, ref: 'WatchFunction', many: true }, material: { label: '材質', type: Types.Select, options: '不鏽鋼, 半金, 銅, 黃金, 玫瑰金, 白金, 鉑金, 鉑金, 鈦金屬, 特殊合金, 複合材質' }, waterproof: { label: '防水', type: Types.Select, options: '無, 30米, 50米, 100米, 200米, 300米, 600米, 1000米, 2000米, 2000米, 4000米' }, popular: { label: '熱門錶款', type: Boolean, index: true }, treasury: { label: '庫藏區', type: Boolean, index: true }, content: { label: '內文', type: Types.Html, wysiwyg: true, height: 400 }, relateds: { label: '相關文章', type: Types.Relationship, ref: 'Post', many: true }, stores: { label: '錶店', type: Types.Relationship, ref: 'WatchStore', many: true }, createTime: { type: Types.Datetime, default: Date.now, utc: true }, }); transform.toJSON(Watch); Watch.defaultColumns = 'name, brand|20%, series|20%, type|20%, movement|20%'; Watch.register();
add some fields in Watch.js
models/Watch.js
add some fields in Watch.js
<ide><path>odels/Watch.js <ide> ga: { label: '發表年份', type: Number}, <ide> limit: { label: '限量支數', type: Number, index: true}, <ide> sex: { label: '性別', type: Types.Select, options: '男錶款, 女錶款, 中性錶款', default: '中性錶款'}, <del> luminous: { label: '夜光', type: Types.Select, options: '有, 無', default: '有'}, <add> luminous: { label: '夜光', type: Boolean, index: true}, <ide> movement: { label: '機芯', type: Types.Select, options: '自動上鏈, 手動上鏈, 石英, 光動能, 人動電能, GPS, 電波, 智能錶' }, <ide> power: { label: '動力', type: String }, <add> size: { label: '錶殼尺寸', type: String }, <add> color: { label: '面盤顏色', type: String }, <add> youtube: { label: 'Youtube 影片', type: Types.Url }, <ide> watchfunction: { label: '功能', type: Types.Relationship, ref: 'WatchFunction', many: true }, <ide> material: { label: '材質', type: Types.Select, options: '不鏽鋼, 半金, 銅, 黃金, 玫瑰金, 白金, 鉑金, 鉑金, 鈦金屬, 特殊合金, 複合材質' }, <ide> waterproof: { label: '防水', type: Types.Select, options: '無, 30米, 50米, 100米, 200米, 300米, 600米, 1000米, 2000米, 2000米, 4000米' }, <ide> treasury: { label: '庫藏區', type: Boolean, index: true }, <ide> content: { label: '內文', type: Types.Html, wysiwyg: true, height: 400 }, <ide> relateds: { label: '相關文章', type: Types.Relationship, ref: 'Post', many: true }, <add> relatedwatch: { label: '相似錶款', type: Types.Relationship, ref: 'Watch', many: true }, <ide> stores: { label: '錶店', type: Types.Relationship, ref: 'WatchStore', many: true }, <ide> createTime: { type: Types.Datetime, default: Date.now, utc: true }, <ide> });
JavaScript
mit
e4c3d138520087f985fc011a403a93d43b343868
0
oddhill/generator-odd
var helpers = require('yeoman-generator').test; var fse = require('fs-extra'); var path = require('path'); var assert = require('yeoman-generator').assert; describe('generator-odd', function () { describe('When generating Oddbaby', function () { before(function (done) { this.timeout(10000); // Run the generator helpers.run(path.join(__dirname, '../generators/baby')) .inDir(path.join(__dirname, './tmp')) .on('end', function () { done(); }); }); it('Should clone Oddbaby', function () { assert.fileContent(__dirname + '/tmp/package.json', '"name": "oddbaby"'); }); it('Remove the git repository', function () { assert.noFile(__dirname + '/tmp/.git'); }); it('Should rename oddbaby.info', function () { assert.file(path.join(__dirname, './tmp/tmp.info')); }); it('Should replace the word "oddbaby" in various files', function () { var files = ['template.php', 'preprocess.inc', 'theme.inc', 'js/main.js']; for (file in files) { assert.noFileContent(path.join(__dirname, './tmp/' + files[file]), 'oddbaby'); } }); after(function (done) { fse.remove(path.join(__dirname, './tmp'), function () { done(); }); }); }); describe('When generating Odddrupal', function () { before(function (done) { this.timeout(0); // Run the generator helpers.run(path.join(__dirname, '../generators/drupal')) .inDir(path.join(__dirname, './tmp')) .on('end', function () { done(); }); }); it('Clone Odddrupal', function () { assert.file(path.join(__dirname, '/tmp/index.php')); }); it('Should remove remote reference', function () { return false; }); it('Rename 7.x to master', function () { return false; }); it('Should create .htaccess file', function () { return false; }); it('Should create settings.local.php file', function () { return false; }); it('Should change permission on files dir', function (done) { // Make sure files folder is 777 fse.stat(path.join(__dirname, '/tmp/sites/all/files'), function (err, stats) { assert.textEqual('40777', parseInt(stats.mode.toString(8), 10).toString()); done(); }); }); after(function (done) { // Make sure tmp folder is removed. fse.remove(path.join(__dirname, './tmp'), function (err) { done(); }); }); }); });
test/test.js
var helpers = require('yeoman-generator').test; var fse = require('fs-extra'); var path = require('path'); var assert = require('yeoman-generator').assert; describe('generator-odd', function () { describe('When generating Oddbaby', function () { before(function (done) { this.timeout(10000); // Run the generator helpers.run(path.join(__dirname, '../generators/baby')) .inDir(path.join(__dirname, './tmp')) .on('end', function () { done(); }); }); it('Should clone Oddbaby', function () { assert.fileContent(__dirname + '/tmp/package.json', '"name": "oddbaby"'); }); it('Remove the git repository', function () { assert.noFile(__dirname + '/tmp/.git'); }); it('Should rename oddbaby.info', function () { assert.file(path.join(__dirname, './tmp/tmp.info')); }); it('Should replace the word "oddbaby" in various files', function () { var files = ['template.php', 'preprocess.inc', 'theme.inc', 'js/main.js']; for (file in files) { assert.noFileContent(path.join(__dirname, './tmp/' + files[file]), 'oddbaby'); } }); after(function (done) { fse.remove(path.join(__dirname, './tmp'), function () { done(); }); }); }); describe('When generating Odddrupal', function () { before(function (done) { this.timeout(0); // Run the generator helpers.run(path.join(__dirname, '../generators/drupal')) .inDir(path.join(__dirname, './tmp')) .on('end', function () { done(); }); }); it('Clone Odddrupal', function () { assert.file(path.join(__dirname, '/tmp/index.php')); }); it('Should remove remote reference', function () { return false; }); it('Rename 7.x to master', function () { return false; }); it('Should create .htaccess file', function () { return false; }); it('Should create settings.local.php file', function () { return false; }); it('Should change permission on files dir', function (done) { // Make sure files folder is 777 fse.stat(path.join(__dirname, '/tmp/sites/all/files'), function (err, stats) { assert.textEqual('40777', parseInt(stats.mode.toString(8), 10).toString()); done(); }); }); }); }); });
Make sure to remove tmp folder when tests are done
test/test.js
Make sure to remove tmp folder when tests are done
<ide><path>est/test.js <ide> done(); <ide> }); <ide> }); <add> <add> after(function (done) { <add> // Make sure tmp folder is removed. <add> fse.remove(path.join(__dirname, './tmp'), function (err) { <add> done(); <add> }); <ide> }); <ide> <ide> });
JavaScript
apache-2.0
73f5b6e23e836e393698b4e4956659628c18c565
0
dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui
import classNames from 'classnames'; import {Confirm, Dropdown} from 'reactjs-components'; import mixin from 'reactjs-mixin'; import prettycron from 'prettycron'; /* eslint-disable no-unused-vars */ import React from 'react'; /* eslint-enable no-unused-vars */ import {RouteHandler} from 'react-router'; import {StoreMixin} from 'mesosphere-shared-reactjs'; import Breadcrumbs from '../../components/Breadcrumbs'; import TimeAgo from '../../components/TimeAgo'; import Icon from '../../components/Icon'; import JobConfiguration from './JobConfiguration'; import JobFormModal from '../../components/modals/JobFormModal'; import JobRunHistoryTable from './JobRunHistoryTable'; import MetronomeStore from '../../stores/MetronomeStore'; import PageHeader from '../../components/PageHeader'; import RequestErrorMsg from '../../components/RequestErrorMsg'; import StringUtil from '../../utils/StringUtil'; import TabsMixin from '../../mixins/TabsMixin'; import TaskStates from '../../constants/TaskStates'; const METHODS_TO_BIND = [ 'closeDialog', 'handleEditButtonClick', 'handleMoreDropdownSelection', 'handleRunNowButtonClick', 'onMetronomeStoreJobDeleteError', 'onMetronomeStoreJobDeleteSuccess', 'onMetronomeStoreJobDetailError', 'onMetronomeStoreJobDetailChange' ]; const JobActionItem = { EDIT: 'edit', DESTROY: 'destroy', SCHEDULE_DISABLE: 'schedule_disable', SCHEDULE_ENABLE: 'schedule_enable', MORE: 'more' }; class JobDetailPage extends mixin(StoreMixin, TabsMixin) { constructor() { super(...arguments); this.store_listeners = [{ name: 'metronome', events: [ 'jobDeleteSuccess', 'jobDeleteError', 'jobDetailChange', 'jobDetailError', 'jobRunError', 'jobRunSuccess', 'jobScheduleUpdateError', 'jobScheduleUpdateSuccess' ] }]; this.tabs_tabs = { runHistory: 'Run History', configuration: 'Configuration' }; this.state = { currentTab: Object.keys(this.tabs_tabs).shift(), disabledDialog: null, jobActionDialog: null, errorMsg: null, errorCount: 0, isJobFormModalOpen: false, isLoading: true }; METHODS_TO_BIND.forEach((method) => { this[method] = this[method].bind(this); }); } componentDidMount() { super.componentDidMount(...arguments); MetronomeStore.monitorJobDetail(this.props.params.id); } componentWillUnmount() { super.componentWillUnmount(...arguments); MetronomeStore.stopJobDetailMonitor(this.props.params.id); } onMetronomeStoreJobDeleteError(id, {message:errorMsg}) { if (id !== this.props.params.id || errorMsg == null) { return; } this.setState({ jobActionDialog: JobActionItem.DESTROY, disabledDialog: null, errorMsg }); } onMetronomeStoreJobDeleteSuccess() { this.closeDialog(); this.context.router.transitionTo('jobs-page'); } onMetronomeStoreJobDetailError() { this.setState({errorCount: this.state.errorCount + 1}); } onMetronomeStoreJobDetailChange() { this.setState({errorCount: 0, isLoading: false}); } handleEditButtonClick() { this.setState({jobActionDialog: JobActionItem.EDIT}); } handleRunNowButtonClick() { let job = MetronomeStore.getJob(this.props.params.id); MetronomeStore.runJob(job.getId()); } handleAcceptDestroyDialog(stopCurrentJobRuns = false) { this.setState({disabledDialog: JobActionItem.DESTROY}, () => { MetronomeStore.deleteJob(this.props.params.id, stopCurrentJobRuns); }); } handleMoreDropdownSelection(selection) { if (selection.id === JobActionItem.SCHEDULE_DISABLE) { MetronomeStore.toggleSchedule(this.props.params.id, false); return; } if (selection.id === JobActionItem.SCHEDULE_ENABLE) { MetronomeStore.toggleSchedule(this.props.params.id, true); return; } this.setState({jobActionDialog: selection.id}); } closeDialog() { this.setState({ disabledDialog: null, errorMsg: null, jobActionDialog: null }); } getActionButtons() { let job = MetronomeStore.getJob(this.props.params.id); let dropdownItems = []; let [schedule] = job.getSchedules(); dropdownItems.push({ className: 'hidden', html: 'More', id: JobActionItem.MORE }); if (schedule != null && schedule.enabled) { dropdownItems.push({ html: 'Disable Schedule', id: JobActionItem.SCHEDULE_DISABLE }); } if (schedule != null && !schedule.enabled) { dropdownItems.push({ html: 'Enable Schedule', id: JobActionItem.SCHEDULE_ENABLE }); } dropdownItems.push({ html: <span className="text-danger">Destroy</span>, id: JobActionItem.DESTROY }); return [ <button className="button button-inverse button-stroke" key="edit" onClick={this.handleEditButtonClick}> Edit </button>, <button className="button button-inverse button-stroke" key="run-now" onClick={this.handleRunNowButtonClick}> Run Now </button>, <Dropdown buttonClassName="dropdown-toggle button button-inverse button-stroke" dropdownMenuClassName="dropdown-menu inverse" dropdownMenuListClassName="dropdown-menu-list" dropdownMenuListItemClassName="clickable" initialID="more" items={dropdownItems} key="more" onItemSelection={this.handleMoreDropdownSelection} persistentID="more" transition={true} wrapperClassName="dropdown anchor-right" /> ]; } getDestroyConfirmDialog() { const {id} = this.props.params; const {disabledDialog, jobActionDialog, errorMsg} = this.state; let stopCurrentJobRuns = false; let actionButtonLabel = 'Destroy Job'; let message = `Are you sure you want to destroy ${id}? ` + 'This action is irreversible.'; if (/stopCurrentJobRuns=true/.test(errorMsg)) { actionButtonLabel = 'Stop Current Runs and Destroy Job'; stopCurrentJobRuns = true; message = `Couldn't destroy ${id} as there are currently active job ` + 'runs. Do you want to stop all runs and destroy the job?'; } let content = ( <div className="container-pod flush-top container-pod-short-bottom"> <h2 className="text-danger text-align-center flush-top"> Destroy Job </h2> {message} </div> ); return ( <Confirm children={content} disabled={disabledDialog === JobActionItem.DESTROY} open={jobActionDialog === JobActionItem.DESTROY} onClose={this.closeDialog} leftButtonText="Cancel" leftButtonCallback={this.closeDialog} rightButtonText={actionButtonLabel} rightButtonClassName="button button-danger" rightButtonCallback= {this.handleAcceptDestroyDialog.bind(this, stopCurrentJobRuns)} /> ); } getErrorScreen() { return ( <div className="container container-fluid container-pod text-align-center vertical-center inverse"> <RequestErrorMsg /> </div> ); } getLoadingScreen() { return ( <div className="container container-fluid container-pod text-align-center vertical-center inverse"> <div className="row"> <div className="ball-scale"> <div /> </div> </div> </div> ); } getNavigationTabs() { return ( <ul className="tabs tall list-inline flush-bottom inverse"> {this.tabs_getUnroutedTabs()} </ul> ); } getPrettySchedule(job) { let schedules = job.getSchedules(); if (schedules == null || schedules.length === 0) { return null; } let schedule = schedules[0]; if (schedule.enabled) { return prettycron.toString(schedule.cron); } } getSubTitle(job) { let nodes = []; let scheduleText = this.getPrettySchedule(job); let longestRunningTask = null; let longestRunningActiveRun = job.getActiveRuns() .getLongestRunningActiveRun(); if (longestRunningActiveRun != null) { longestRunningTask = longestRunningActiveRun.getTasks() .getLongestRunningTask(); } if (longestRunningTask == null && scheduleText == null) { return null; } if (scheduleText != null) { nodes.push( <p className="text-overflow" key="schedule-text"> <Icon className="icon-margin-right" key="schedule-icon" color="grey" id="repeat" size="mini" family="small" /> <span>Scheduled {StringUtil.lowercase(scheduleText)}</span> </p> ); } if (longestRunningTask != null) { let dateCompleted = longestRunningTask.getDateCompleted(); let status = TaskStates[longestRunningTask.getStatus()]; let statusClasses = classNames('job-details-header-status', { 'text-success': status.stateTypes.includes('success') && !status.stateTypes.includes('failure'), 'text-danger': status.stateTypes.includes('failure') }); let timePrefix = null; let shouldSuppressRelativeTime = dateCompleted == null; if (shouldSuppressRelativeTime) { timePrefix = 'for '; } nodes.push( <span className={statusClasses} key="status-text"> {status.displayName} </span>, <span key="time-running"> <TimeAgo prefix={timePrefix} suppressSuffix={shouldSuppressRelativeTime} time={longestRunningActiveRun.getDateCreated()} /> </span> ); } return nodes; } renderConfigurationTabView(job) { return <JobConfiguration job={job} />; } renderRunHistoryTabView(job) { return <JobRunHistoryTable job={job} />; } render() { if (this.state.errorCount > 3) { return this.getErrorScreen(); } if (this.state.isLoading) { return this.getLoadingScreen(); } if (this.props.params.taskID) { return <RouteHandler />; } let job = MetronomeStore.getJob(this.props.params.id); return ( <div> <Breadcrumbs /> <PageHeader actionButtons={this.getActionButtons()} icon={<Icon color="white" id="page-code" size="large" />} navigationTabs={this.getNavigationTabs()} subTitle={this.getSubTitle(job)} subTitleClassName={{emphasize: false}} title={job.getDescription()} /> {this.tabs_getTabView(job)} <JobFormModal isEdit={true} job={job} open={this.state.jobActionDialog === JobActionItem.EDIT} onClose={this.closeDialog} /> {this.getDestroyConfirmDialog()} </div> ); } } JobDetailPage.contextTypes = { router: React.PropTypes.func }; module.exports = JobDetailPage;
src/js/pages/jobs/JobDetailPage.js
import classNames from 'classnames'; import {Confirm, Dropdown} from 'reactjs-components'; import mixin from 'reactjs-mixin'; import prettycron from 'prettycron'; /* eslint-disable no-unused-vars */ import React from 'react'; /* eslint-enable no-unused-vars */ import {RouteHandler} from 'react-router'; import {StoreMixin} from 'mesosphere-shared-reactjs'; import Breadcrumbs from '../../components/Breadcrumbs'; import TimeAgo from '../../components/TimeAgo'; import Icon from '../../components/Icon'; import JobConfiguration from './JobConfiguration'; import JobFormModal from '../../components/modals/JobFormModal'; import JobRunHistoryTable from './JobRunHistoryTable'; import MetronomeStore from '../../stores/MetronomeStore'; import PageHeader from '../../components/PageHeader'; import RequestErrorMsg from '../../components/RequestErrorMsg'; import TabsMixin from '../../mixins/TabsMixin'; import TaskStates from '../../constants/TaskStates'; const METHODS_TO_BIND = [ 'closeDialog', 'handleEditButtonClick', 'handleMoreDropdownSelection', 'handleRunNowButtonClick', 'onMetronomeStoreJobDeleteError', 'onMetronomeStoreJobDeleteSuccess', 'onMetronomeStoreJobDetailError', 'onMetronomeStoreJobDetailChange' ]; const JobActionItem = { EDIT: 'edit', DESTROY: 'destroy', SCHEDULE_DISABLE: 'schedule_disable', SCHEDULE_ENABLE: 'schedule_enable', MORE: 'more' }; class JobDetailPage extends mixin(StoreMixin, TabsMixin) { constructor() { super(...arguments); this.store_listeners = [{ name: 'metronome', events: [ 'jobDeleteSuccess', 'jobDeleteError', 'jobDetailChange', 'jobDetailError', 'jobRunError', 'jobRunSuccess', 'jobScheduleUpdateError', 'jobScheduleUpdateSuccess' ] }]; this.tabs_tabs = { runHistory: 'Run History', configuration: 'Configuration' }; this.state = { currentTab: Object.keys(this.tabs_tabs).shift(), disabledDialog: null, jobActionDialog: null, errorMsg: null, errorCount: 0, isJobFormModalOpen: false, isLoading: true }; METHODS_TO_BIND.forEach((method) => { this[method] = this[method].bind(this); }); } componentDidMount() { super.componentDidMount(...arguments); MetronomeStore.monitorJobDetail(this.props.params.id); } componentWillUnmount() { super.componentWillUnmount(...arguments); MetronomeStore.stopJobDetailMonitor(this.props.params.id); } onMetronomeStoreJobDeleteError(id, {message:errorMsg}) { if (id !== this.props.params.id || errorMsg == null) { return; } this.setState({ jobActionDialog: JobActionItem.DESTROY, disabledDialog: null, errorMsg }); } onMetronomeStoreJobDeleteSuccess() { this.closeDialog(); this.context.router.transitionTo('jobs-page'); } onMetronomeStoreJobDetailError() { this.setState({errorCount: this.state.errorCount + 1}); } onMetronomeStoreJobDetailChange() { this.setState({errorCount: 0, isLoading: false}); } handleEditButtonClick() { this.setState({jobActionDialog: JobActionItem.EDIT}); } handleRunNowButtonClick() { let job = MetronomeStore.getJob(this.props.params.id); MetronomeStore.runJob(job.getId()); } handleAcceptDestroyDialog(stopCurrentJobRuns = false) { this.setState({disabledDialog: JobActionItem.DESTROY}, () => { MetronomeStore.deleteJob(this.props.params.id, stopCurrentJobRuns); }); } handleMoreDropdownSelection(selection) { if (selection.id === JobActionItem.SCHEDULE_DISABLE) { MetronomeStore.toggleSchedule(this.props.params.id, false); return; } if (selection.id === JobActionItem.SCHEDULE_ENABLE) { MetronomeStore.toggleSchedule(this.props.params.id, true); return; } this.setState({jobActionDialog: selection.id}); } closeDialog() { this.setState({ disabledDialog: null, errorMsg: null, jobActionDialog: null }); } getActionButtons() { let job = MetronomeStore.getJob(this.props.params.id); let dropdownItems = []; let [schedule] = job.getSchedules(); dropdownItems.push({ className: 'hidden', html: 'More', id: JobActionItem.MORE }); if (schedule != null && schedule.enabled) { dropdownItems.push({ html: 'Disable Schedule', id: JobActionItem.SCHEDULE_DISABLE }); } if (schedule != null && !schedule.enabled) { dropdownItems.push({ html: 'Enable Schedule', id: JobActionItem.SCHEDULE_ENABLE }); } dropdownItems.push({ html: <span className="text-danger">Destroy</span>, id: JobActionItem.DESTROY }); return [ <button className="button button-inverse button-stroke" key="edit" onClick={this.handleEditButtonClick}> Edit </button>, <button className="button button-inverse button-stroke" key="run-now" onClick={this.handleRunNowButtonClick}> Run Now </button>, <Dropdown buttonClassName="dropdown-toggle button button-inverse button-stroke" dropdownMenuClassName="dropdown-menu inverse" dropdownMenuListClassName="dropdown-menu-list" dropdownMenuListItemClassName="clickable" initialID="more" items={dropdownItems} key="more" onItemSelection={this.handleMoreDropdownSelection} persistentID="more" transition={true} wrapperClassName="dropdown anchor-right" /> ]; } getDestroyConfirmDialog() { const {id} = this.props.params; const {disabledDialog, jobActionDialog, errorMsg} = this.state; let stopCurrentJobRuns = false; let actionButtonLabel = 'Destroy Job'; let message = `Are you sure you want to destroy ${id}? ` + 'This action is irreversible.'; if (/stopCurrentJobRuns=true/.test(errorMsg)) { actionButtonLabel = 'Stop Current Runs and Destroy Job'; stopCurrentJobRuns = true; message = `Couldn't destroy ${id} as there are currently active job ` + 'runs. Do you want to stop all runs and destroy the job?'; } let content = ( <div className="container-pod flush-top container-pod-short-bottom"> <h2 className="text-danger text-align-center flush-top"> Destroy Job </h2> {message} </div> ); return ( <Confirm children={content} disabled={disabledDialog === JobActionItem.DESTROY} open={jobActionDialog === JobActionItem.DESTROY} onClose={this.closeDialog} leftButtonText="Cancel" leftButtonCallback={this.closeDialog} rightButtonText={actionButtonLabel} rightButtonClassName="button button-danger" rightButtonCallback= {this.handleAcceptDestroyDialog.bind(this, stopCurrentJobRuns)} /> ); } getErrorScreen() { return ( <div className="container container-fluid container-pod text-align-center vertical-center inverse"> <RequestErrorMsg /> </div> ); } getLoadingScreen() { return ( <div className="container container-fluid container-pod text-align-center vertical-center inverse"> <div className="row"> <div className="ball-scale"> <div /> </div> </div> </div> ); } getNavigationTabs() { return ( <ul className="tabs tall list-inline flush-bottom inverse"> {this.tabs_getUnroutedTabs()} </ul> ); } getPrettySchedule(job) { let schedules = job.getSchedules(); if (schedules == null || schedules.length === 0) { return null; } let schedule = schedules[0]; if (schedule.enabled) { return prettycron.toString(schedule.cron); } } getSubTitle(job) { let nodes = []; let scheduleText = this.getPrettySchedule(job); let longestRunningTask = null; let longestRunningActiveRun = job.getActiveRuns() .getLongestRunningActiveRun(); if (longestRunningActiveRun != null) { longestRunningTask = longestRunningActiveRun.getTasks() .getLongestRunningTask(); } if (longestRunningTask == null && scheduleText == null) { return null; } if (scheduleText != null) { nodes.push( <p className="text-overflow" key="schedule-text"> <Icon className="icon-margin-right" key="schedule-icon" color="grey" id="repeat" size="mini" family="small" /> <span className="job-details-header-status">Scheduled</span> <span>{scheduleText}</span> </p> ); } if (longestRunningTask != null) { let dateCompleted = longestRunningTask.getDateCompleted(); let status = TaskStates[longestRunningTask.getStatus()]; let statusClasses = classNames('job-details-header-status', { 'text-success': status.stateTypes.includes('success') && !status.stateTypes.includes('failure'), 'text-danger': status.stateTypes.includes('failure') }); let timePrefix = null; let shouldSuppressRelativeTime = dateCompleted == null; if (shouldSuppressRelativeTime) { timePrefix = 'for '; } nodes.push( <span className={statusClasses} key="status-text"> {status.displayName} </span>, <span key="time-running"> <TimeAgo prefix={timePrefix} suppressSuffix={shouldSuppressRelativeTime} time={longestRunningActiveRun.getDateCreated()} /> </span> ); } return nodes; } renderConfigurationTabView(job) { return <JobConfiguration job={job} />; } renderRunHistoryTabView(job) { return <JobRunHistoryTable job={job} />; } render() { if (this.state.errorCount > 3) { return this.getErrorScreen(); } if (this.state.isLoading) { return this.getLoadingScreen(); } if (this.props.params.taskID) { return <RouteHandler />; } let job = MetronomeStore.getJob(this.props.params.id); return ( <div> <Breadcrumbs /> <PageHeader actionButtons={this.getActionButtons()} icon={<Icon color="white" id="page-code" size="large" />} navigationTabs={this.getNavigationTabs()} subTitle={this.getSubTitle(job)} subTitleClassName={{emphasize: false}} title={job.getDescription()} /> {this.tabs_getTabView(job)} <JobFormModal isEdit={true} job={job} open={this.state.jobActionDialog === JobActionItem.EDIT} onClose={this.closeDialog} /> {this.getDestroyConfirmDialog()} </div> ); } } JobDetailPage.contextTypes = { router: React.PropTypes.func }; module.exports = JobDetailPage;
Lowercase schedule description
src/js/pages/jobs/JobDetailPage.js
Lowercase schedule description
<ide><path>rc/js/pages/jobs/JobDetailPage.js <ide> import MetronomeStore from '../../stores/MetronomeStore'; <ide> import PageHeader from '../../components/PageHeader'; <ide> import RequestErrorMsg from '../../components/RequestErrorMsg'; <add>import StringUtil from '../../utils/StringUtil'; <ide> import TabsMixin from '../../mixins/TabsMixin'; <ide> import TaskStates from '../../constants/TaskStates'; <ide> <ide> id="repeat" <ide> size="mini" <ide> family="small" /> <del> <span className="job-details-header-status">Scheduled</span> <del> <span>{scheduleText}</span> <add> <span>Scheduled {StringUtil.lowercase(scheduleText)}</span> <ide> </p> <ide> ); <ide> }
Java
lgpl-2.1
error: pathspec 'modules/testsuite/cxf-tests/src/test/java/org/jboss/test/ws/jaxws/samples/wsse/policy/basic/SignEncryptGCMTestCase.java' did not match any file(s) known to git
c0f78f333ca88494b56e373a9c57bf1502d4de2d
1
jbossws/jbossws-cxf
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.test.ws.jaxws.samples.wsse.policy.basic; import java.net.URL; import javax.xml.namespace.QName; import javax.xml.ws.BindingProvider; import javax.xml.ws.Service; import javax.xml.ws.soap.SOAPFaultException; import junit.framework.Test; import org.apache.cxf.ws.security.SecurityConstants; import org.jboss.wsf.test.JBossWSCXFTestSetup; import org.jboss.wsf.test.JBossWSTest; /** * WS-Security Policy sign & encrypt test case * using GCM algorithm suite * * @author [email protected] * @since 27-Feb-2012 */ public final class SignEncryptGCMTestCase extends JBossWSTest { private final String serviceURL = "http://" + getServerHost() + ":8080/jaxws-samples-wsse-policy-sign-encrypt-gcm"; public static Test suite() { return new JBossWSCXFTestSetup(SignEncryptGCMTestCase.class, "jaxws-samples-wsse-policy-sign-encrypt-client.jar jaxws-samples-wsse-policy-sign-encrypt-gcm.war"); } public void test() throws Exception { QName serviceName = new QName("http://www.jboss.org/jbossws/ws-extensions/wssecuritypolicy", "SecurityService"); URL wsdlURL = new URL(serviceURL + "?wsdl"); Service service = Service.create(wsdlURL, serviceName); ServiceIface proxy = (ServiceIface)service.getPort(ServiceIface.class); setupWsse(proxy); try { assertEquals("Secure Hello World!", proxy.sayHello()); } catch (SOAPFaultException e) { throw new Exception("Please check that the Bouncy Castle provider is installed.", e); } } private void setupWsse(ServiceIface proxy) { ((BindingProvider)proxy).getRequestContext().put(SecurityConstants.CALLBACK_HANDLER, new KeystorePasswordCallback()); ((BindingProvider)proxy).getRequestContext().put(SecurityConstants.SIGNATURE_PROPERTIES, Thread.currentThread().getContextClassLoader().getResource("META-INF/alice.properties")); ((BindingProvider)proxy).getRequestContext().put(SecurityConstants.ENCRYPT_PROPERTIES, Thread.currentThread().getContextClassLoader().getResource("META-INF/alice.properties")); ((BindingProvider)proxy).getRequestContext().put(SecurityConstants.SIGNATURE_USERNAME, "alice"); ((BindingProvider)proxy).getRequestContext().put(SecurityConstants.ENCRYPT_USERNAME, "bob"); } }
modules/testsuite/cxf-tests/src/test/java/org/jboss/test/ws/jaxws/samples/wsse/policy/basic/SignEncryptGCMTestCase.java
[JBWS-3439] Actually adding the testcase class (previously forgotten)
modules/testsuite/cxf-tests/src/test/java/org/jboss/test/ws/jaxws/samples/wsse/policy/basic/SignEncryptGCMTestCase.java
[JBWS-3439] Actually adding the testcase class (previously forgotten)
<ide><path>odules/testsuite/cxf-tests/src/test/java/org/jboss/test/ws/jaxws/samples/wsse/policy/basic/SignEncryptGCMTestCase.java <add>/* <add> * JBoss, Home of Professional Open Source. <add> * Copyright 2012, Red Hat Middleware LLC, and individual contributors <add> * as indicated by the @author tags. See the copyright.txt file in the <add> * distribution for a full listing of individual contributors. <add> * <add> * This is free software; you can redistribute it and/or modify it <add> * under the terms of the GNU Lesser General Public License as <add> * published by the Free Software Foundation; either version 2.1 of <add> * the License, or (at your option) any later version. <add> * <add> * This software is distributed in the hope that it will be useful, <add> * but WITHOUT ANY WARRANTY; without even the implied warranty of <add> * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU <add> * Lesser General Public License for more details. <add> * <add> * You should have received a copy of the GNU Lesser General Public <add> * License along with this software; if not, write to the Free <add> * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA <add> * 02110-1301 USA, or see the FSF site: http://www.fsf.org. <add> */ <add>package org.jboss.test.ws.jaxws.samples.wsse.policy.basic; <add> <add>import java.net.URL; <add> <add>import javax.xml.namespace.QName; <add>import javax.xml.ws.BindingProvider; <add>import javax.xml.ws.Service; <add>import javax.xml.ws.soap.SOAPFaultException; <add> <add>import junit.framework.Test; <add> <add>import org.apache.cxf.ws.security.SecurityConstants; <add>import org.jboss.wsf.test.JBossWSCXFTestSetup; <add>import org.jboss.wsf.test.JBossWSTest; <add> <add>/** <add> * WS-Security Policy sign & encrypt test case <add> * using GCM algorithm suite <add> * <add> * @author [email protected] <add> * @since 27-Feb-2012 <add> */ <add>public final class SignEncryptGCMTestCase extends JBossWSTest <add>{ <add> private final String serviceURL = "http://" + getServerHost() + ":8080/jaxws-samples-wsse-policy-sign-encrypt-gcm"; <add> <add> public static Test suite() <add> { <add> return new JBossWSCXFTestSetup(SignEncryptGCMTestCase.class, "jaxws-samples-wsse-policy-sign-encrypt-client.jar jaxws-samples-wsse-policy-sign-encrypt-gcm.war"); <add> } <add> <add> public void test() throws Exception <add> { <add> QName serviceName = new QName("http://www.jboss.org/jbossws/ws-extensions/wssecuritypolicy", "SecurityService"); <add> URL wsdlURL = new URL(serviceURL + "?wsdl"); <add> Service service = Service.create(wsdlURL, serviceName); <add> ServiceIface proxy = (ServiceIface)service.getPort(ServiceIface.class); <add> setupWsse(proxy); <add> try <add> { <add> assertEquals("Secure Hello World!", proxy.sayHello()); <add> } <add> catch (SOAPFaultException e) <add> { <add> throw new Exception("Please check that the Bouncy Castle provider is installed.", e); <add> } <add> } <add> <add> private void setupWsse(ServiceIface proxy) <add> { <add> ((BindingProvider)proxy).getRequestContext().put(SecurityConstants.CALLBACK_HANDLER, new KeystorePasswordCallback()); <add> ((BindingProvider)proxy).getRequestContext().put(SecurityConstants.SIGNATURE_PROPERTIES, Thread.currentThread().getContextClassLoader().getResource("META-INF/alice.properties")); <add> ((BindingProvider)proxy).getRequestContext().put(SecurityConstants.ENCRYPT_PROPERTIES, Thread.currentThread().getContextClassLoader().getResource("META-INF/alice.properties")); <add> ((BindingProvider)proxy).getRequestContext().put(SecurityConstants.SIGNATURE_USERNAME, "alice"); <add> ((BindingProvider)proxy).getRequestContext().put(SecurityConstants.ENCRYPT_USERNAME, "bob"); <add> } <add>}
Java
apache-2.0
328e929dafdc6f7ecf41fb132e2129eeaa0d3541
0
deepjava/runtime-library
/* * Copyright 2011 - 2015 NTB University of Applied Sciences in Technology * Buchs, Switzerland, http://www.ntb.ch/inf * * 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 ch.ntb.inf.deep.runtime.zynq7000; import ch.ntb.inf.deep.runtime.IdeepCompilerConstants; import ch.ntb.inf.deep.runtime.arm32.Heap; import ch.ntb.inf.deep.runtime.arm32.Iarm32; import ch.ntb.inf.deep.unsafe.US; /* changes: * 6.10.2015 NTB/Urs Graf creation */ /** * This is the kernel class. It provides basic functionalities and does the booting-up. */ public class Kernel implements Iarm32, Izybo7000, IdeepCompilerConstants { final static int stackEndPattern = 0xee22dd33; /** Clock frequency of the processor. */ public static final int clockFrequency = 400000000; // Hz static int loopAddr; static int cmdAddr; static long t = 0x1122; @SuppressWarnings("unused") private static void loop() { // endless loop US.PUT4(SLCR_UNLOCK, 0xdf0d); US.PUT4(SLCR_MIO_PIN_07, 0x600); US.PUT4(GPIO_DIR0, 0x80); while (true) { // try { if (cmdAddr != -1) { US.PUTGPR(0, cmdAddr); US.ASM("mov r14, r15"); // copy PC to LR US.ASM("mov r15, r0"); cmdAddr = -1; } // } catch (Exception e) { // cmdAddr = -1; // stop trying to run the same method // e.printStackTrace(); // Kernel.blink(2); // } US.PUT4(GPIO_DATA0, US.GET4(GPIO_DATA0) ^ 0x80); // t = time(); // US.ASM("b -8"); for (int i = 2000000; i > 0; i--); } } /** * Reads the system time. * * @return System time in \u00b5s */ public static long time() { int high1, high2, low; do { high1 = US.GET4(GTCR_U); low = US.GET4(GTCR_L); high2 = US.GET4(GTCR_U); } while (high1 != high2); long time = ((long)high1 << 32) | ((long)low & 0xffffffffL); return time; } /** * Blinks LED on MIO7 pin, nTimes with approx. 100us high time and 100us low time, blocks for 1s * * @param nTimes Number of times the led blinks. */ public static void blink(int nTimes) { US.PUT4(SLCR_UNLOCK, 0xdf0d); US.PUT4(SLCR_MIO_PIN_07, 0x600); US.PUT4(GPIO_DIR0, 0x80); int delay = 1000000; for (int i = 0; i < nTimes; i++) { US.PUT4(GPIO_DATA0, US.GET4(GPIO_DATA0) | 0x80); for (int k = 0; k < delay; k++); US.PUT4(GPIO_DATA0, US.GET4(GPIO_DATA0) ^ 0x80); for (int k = 0; k < delay; k++); } for (int k = 0; k < (10 * delay + nTimes * 2 * delay); k++); } /** * Enables interrupts globally. * Individual interrupts for peripheral components must be enabled locally. */ public static void enableInterrupts() { } /** * Blinks LED on MPIOSM pin 15 if stack end was overwritten */ public static void checkStack() { boot(); // int stackOffset = US.GET4(sysTabBaseAddr + stStackOffset); // int stackBase = US.GET4(sysTabBaseAddr + stackOffset + 4); // if (US.GET4(stackBase) != stackEndPattern) while (true) blink(3); } private static int FCS(int begin, int end) { int crc = 0xffffffff; // initial content final int poly = 0xedb88320; // reverse polynomial 0x04c11db7 int addr = begin; while (addr < end) { byte b = US.GET1(addr); int temp = (crc ^ b) & 0xff; for (int i = 0; i < 8; i++) { // read 8 bits one at a time if ((temp & 1) == 1) temp = (temp >>> 1) ^ poly; else temp = (temp >>> 1); } crc = (crc >>> 8) ^ temp; addr++; } // return crc; return 0; } private static void boot() { // set to private later blink(2); // US.ASM("b -8"); // stop here // _ init VFP (FPU // _ _ enable coprocessor 10 and 11 US.ASM("mrc p15, 0, r1, c1, c0, 2"); US.ASM("orr r1, r1, #0xf00000"); US.ASM("mcr p15, 0, r1, c1, c0, 2"); // US.ASM("b -8"); // _ _ enable vfp US.ASM("vmrs r1, FPEXC"); //US.ASM("fmrx r1, FPEXC"); US.ASM("orr r1, r1, #0x40000000"); // FPEXC_EN bit" US.ASM("vmsr FPEXC, r1"); //US.ASM("fmxr FPEXC, r1"); // fill the number 100 into d0 US.PUTGPR(5, 0x40590000); US.PUTGPR(6, 0); US.ASM("vmov d0, r6, r5"); // mark stack end with specific pattern int stackOffset = US.GET4(sysTabBaseAddr + stStackOffset); int stackBase = US.GET4(sysTabBaseAddr + stackOffset + 4); US.PUT4(stackBase, stackEndPattern); int classConstOffset = US.GET4(sysTabBaseAddr); // int state = 0; while (true) { // get addresses of classes from system table int constBlkBase = US.GET4(sysTabBaseAddr + classConstOffset); if (constBlkBase == 0) break; // check integrity of constant block for each class int constBlkSize = US.GET4(constBlkBase); if (FCS(constBlkBase, constBlkBase + constBlkSize) != 0) while(true) blink(1); // initialize class variables int varBase = US.GET4(constBlkBase + cblkVarBaseOffset); int varSize = US.GET4(constBlkBase + cblkVarSizeOffset); int begin = varBase; int end = varBase + varSize; while (begin < end) {US.PUT4(begin, 0); begin += 4;} // state++; classConstOffset += 4; } classConstOffset = US.GET4(sysTabBaseAddr); Heap.sysTabBaseAddr = sysTabBaseAddr; int kernelClinitAddr = US.GET4(sysTabBaseAddr + stKernelClinitAddr); while (true) { // get addresses of classes from system table int constBlkBase = US.GET4(sysTabBaseAddr + classConstOffset); if (constBlkBase == 0) break; // initialize classes int clinitAddr = US.GET4(constBlkBase + cblkClinitAddrOffset); if (clinitAddr != -1) { if (clinitAddr != kernelClinitAddr) { // skip kernel US.PUTGPR(0, clinitAddr); US.ASM("mov r14, r15"); // copy PC to LR US.ASM("mov r15, r0"); } else { // kernel loopAddr = US.ADR_OF_METHOD("ch/ntb/inf/deep/runtime/zynq7000/Kernel/loop"); } } // the direct call to clinitAddr destroys volatile registers, hence make sure // the variable classConstOffset is forced into nonvolatile register // this is done by call to empty() empty(); classConstOffset += 4; } } private static void empty() { } static { // try { // US.ASM("b -8"); // stop here boot(); cmdAddr = -1; // must be after class variables are zeroed by boot // blink(1); US.PUTGPR(0, loopAddr); US.ASM("mov r14, r15"); // copy PC to LR US.ASM("mov r15, r0"); // } catch (Exception e) { // e.printStackTrace(); // while (true) Kernel.blink(5); // } } }
src/ch/ntb/inf/deep/runtime/zynq7000/Kernel.java
/* * Copyright 2011 - 2015 NTB University of Applied Sciences in Technology * Buchs, Switzerland, http://www.ntb.ch/inf * * 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 ch.ntb.inf.deep.runtime.zynq7000; import ch.ntb.inf.deep.runtime.IdeepCompilerConstants; import ch.ntb.inf.deep.runtime.arm32.Heap; import ch.ntb.inf.deep.runtime.arm32.Iarm32; import ch.ntb.inf.deep.unsafe.US; /* changes: * 6.10.2015 NTB/Urs Graf creation */ /** * This is the kernel class. It provides basic functionalities and does the booting-up. */ public class Kernel implements Iarm32, Izybo7000, IdeepCompilerConstants { final static int stackEndPattern = 0xee22dd33; /** Clock frequency of the processor. */ public static final int clockFrequency = 400000000; // Hz static int loopAddr; static int cmdAddr; static long t = 0x1122; @SuppressWarnings("unused") private static void loop() { // endless loop US.PUT4(SLCR_UNLOCK, 0xdf0d); US.PUT4(SLCR_MIO_PIN_07, 0x600); US.PUT4(GPIO_DIR0, 0x80); while (true) { // try { if (cmdAddr != -1) { US.PUTGPR(0, cmdAddr); US.ASM("mov r14, r15"); // copy PC to LR US.ASM("mov r15, r0"); cmdAddr = -1; } // } catch (Exception e) { // cmdAddr = -1; // stop trying to run the same method // e.printStackTrace(); // Kernel.blink(2); // } US.PUT4(GPIO_DATA0, US.GET4(GPIO_DATA0) ^ 0x80); // t = time(); // US.ASM("b -8"); for (int i = 2000000; i > 0; i--); } } /** * Reads the system time. * * @return System time in \u00b5s */ public static long time() { int high1, high2, low; do { high1 = US.GET4(GTCR_U); low = US.GET4(GTCR_L); high2 = US.GET4(GTCR_U); } while (high1 != high2); long time = ((long)high1 << 32) | ((long)low & 0xffffffffL); return time; } /** * Blinks LED on MIO7 pin, nTimes with approx. 100us high time and 100us low time, blocks for 1s * * @param nTimes Number of times the led blinks. */ public static void blink(int nTimes) { US.PUT4(SLCR_UNLOCK, 0xdf0d); US.PUT4(SLCR_MIO_PIN_07, 0x600); US.PUT4(GPIO_DIR0, 0x80); int delay = 1000000; for (int i = 0; i < nTimes; i++) { US.PUT4(GPIO_DATA0, US.GET4(GPIO_DATA0) | 0x80); for (int k = 0; k < delay; k++); US.PUT4(GPIO_DATA0, US.GET4(GPIO_DATA0) ^ 0x80); for (int k = 0; k < delay; k++); } for (int k = 0; k < (10 * delay + nTimes * 2 * delay); k++); } /** * Enables interrupts globally. * Individual interrupts for peripheral components must be enabled locally. */ public static void enableInterrupts() { } /** * Blinks LED on MPIOSM pin 15 if stack end was overwritten */ public static void checkStack() { boot(); // int stackOffset = US.GET4(sysTabBaseAddr + stStackOffset); // int stackBase = US.GET4(sysTabBaseAddr + stackOffset + 4); // if (US.GET4(stackBase) != stackEndPattern) while (true) blink(3); } private static int FCS(int begin, int end) { int crc = 0xffffffff; // initial content final int poly = 0xedb88320; // reverse polynomial 0x04c11db7 int addr = begin; while (addr < end) { byte b = US.GET1(addr); int temp = (crc ^ b) & 0xff; for (int i = 0; i < 8; i++) { // read 8 bits one at a time if ((temp & 1) == 1) temp = (temp >>> 1) ^ poly; else temp = (temp >>> 1); } crc = (crc >>> 8) ^ temp; addr++; } // return crc; return 0; } private static void boot() { // set to private later blink(2); // US.ASM("b -8"); // stop here // mark stack end with specific pattern int stackOffset = US.GET4(sysTabBaseAddr + stStackOffset); int stackBase = US.GET4(sysTabBaseAddr + stackOffset + 4); US.PUT4(stackBase, stackEndPattern); int classConstOffset = US.GET4(sysTabBaseAddr); // int state = 0; while (true) { // get addresses of classes from system table int constBlkBase = US.GET4(sysTabBaseAddr + classConstOffset); if (constBlkBase == 0) break; // check integrity of constant block for each class int constBlkSize = US.GET4(constBlkBase); if (FCS(constBlkBase, constBlkBase + constBlkSize) != 0) while(true) blink(1); // initialize class variables int varBase = US.GET4(constBlkBase + cblkVarBaseOffset); int varSize = US.GET4(constBlkBase + cblkVarSizeOffset); int begin = varBase; int end = varBase + varSize; while (begin < end) {US.PUT4(begin, 0); begin += 4;} // state++; classConstOffset += 4; } classConstOffset = US.GET4(sysTabBaseAddr); Heap.sysTabBaseAddr = sysTabBaseAddr; int kernelClinitAddr = US.GET4(sysTabBaseAddr + stKernelClinitAddr); while (true) { // get addresses of classes from system table int constBlkBase = US.GET4(sysTabBaseAddr + classConstOffset); if (constBlkBase == 0) break; // initialize classes int clinitAddr = US.GET4(constBlkBase + cblkClinitAddrOffset); if (clinitAddr != -1) { if (clinitAddr != kernelClinitAddr) { // skip kernel US.PUTGPR(0, clinitAddr); US.ASM("mov r14, r15"); // copy PC to LR US.ASM("mov r15, r0"); } else { // kernel loopAddr = US.ADR_OF_METHOD("ch/ntb/inf/deep/runtime/zynq7000/Kernel/loop"); } } // the direct call to clinitAddr destroys volatile registers, hence make sure // the variable classConstOffset is forced into nonvolatile register // this is done by call to empty() empty(); classConstOffset += 4; } } private static void empty() { } static { // try { // US.ASM("b -8"); // stop here boot(); cmdAddr = -1; // must be after class variables are zeroed by boot // blink(1); US.PUTGPR(0, loopAddr); US.ASM("mov r14, r15"); // copy PC to LR US.ASM("mov r15, r0"); // } catch (Exception e) { // e.printStackTrace(); // while (true) Kernel.blink(5); // } } }
enable FPU
src/ch/ntb/inf/deep/runtime/zynq7000/Kernel.java
enable FPU
<ide><path>rc/ch/ntb/inf/deep/runtime/zynq7000/Kernel.java <ide> blink(2); <ide> // US.ASM("b -8"); // stop here <ide> <add> // _ init VFP (FPU <add> // _ _ enable coprocessor 10 and 11 <add> US.ASM("mrc p15, 0, r1, c1, c0, 2"); <add> US.ASM("orr r1, r1, #0xf00000"); <add> US.ASM("mcr p15, 0, r1, c1, c0, 2"); <add>// US.ASM("b -8"); <add> <add> // _ _ enable vfp <add> US.ASM("vmrs r1, FPEXC"); //US.ASM("fmrx r1, FPEXC"); <add> US.ASM("orr r1, r1, #0x40000000"); // FPEXC_EN bit" <add> US.ASM("vmsr FPEXC, r1"); //US.ASM("fmxr FPEXC, r1"); <add> <add> // fill the number 100 into d0 <add> US.PUTGPR(5, 0x40590000); <add> US.PUTGPR(6, 0); <add> US.ASM("vmov d0, r6, r5"); <add> <ide> // mark stack end with specific pattern <ide> int stackOffset = US.GET4(sysTabBaseAddr + stStackOffset); <ide> int stackBase = US.GET4(sysTabBaseAddr + stackOffset + 4);
Java
apache-2.0
6151bbc6de006b19b6f50f9b04aa0a11d81d9278
0
jaxzin/daytrader,jaxzin/daytrader
/** * * Copyright 2005 The Apache Software Foundation or its licensors, as applicable * * 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.apache.geronimo.samples.daytrader.direct; import java.math.BigDecimal; import java.util.Collection; import java.util.ArrayList; import javax.naming.InitialContext; import javax.transaction.UserTransaction; import javax.jms.*; import javax.sql.DataSource; import org.apache.geronimo.samples.daytrader.ejb.Trade; import org.apache.geronimo.samples.daytrader.ejb.TradeHome; import org.apache.geronimo.samples.daytrader.util.*; import java.rmi.RemoteException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Timestamp; import org.apache.geronimo.samples.daytrader.*; /** * TradeDirect uses direct JDBC and JMS access to a <code>javax.sql.DataSource</code> to implement the business methods * of the Trade online broker application. These business methods represent the features and operations that * can be performed by customers of the brokerage such as login, logout, get a stock quote, buy or sell a stock, etc. * and are specified in the {@link org.apache.geronimo.samples.daytrader.TradeServices} interface * * Note: In order for this class to be thread-safe, a new TradeJDBC must be created * for each call to a method from the TradeInterface interface. Otherwise, pooled * connections may not be released. * * @see org.apache.geronimo.samples.daytrader.TradeServices * @see org.apache.geronimo.samples.daytrader.ejb.Trade * */ public class TradeDirect implements TradeServices { private static String dsName = TradeConfig.DATASOURCE; private static DataSource datasource = null; private static BigDecimal ZERO = new BigDecimal(0.0); private boolean inGlobalTxn = false; /** * Zero arg constructor for TradeDirect */ public TradeDirect() { if (initialized==false) init(); } /** * @see TradeServices#getMarketSummary() */ public MarketSummaryDataBean getMarketSummary() throws Exception { MarketSummaryDataBean marketSummaryData = null; Connection conn=null; try { if (Log.doTrace()) Log.trace("TradeDirect:getMarketSummary"); conn = getConn(); PreparedStatement stmt = getStatement(conn, getTSIAQuotesOrderByChangeSQL, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); ArrayList topGainersData = new ArrayList(5); ArrayList topLosersData = new ArrayList(5); ResultSet rs = stmt.executeQuery(); int count = 0; while (rs.next() && (count++ < 5) ) { QuoteDataBean quoteData = getQuoteDataFromResultSet(rs); topLosersData.add(quoteData); } stmt.close(); stmt = getStatement(conn, "select * from quoteejb q where q.symbol like 's:1__' order by q.change1 DESC", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); rs = stmt.executeQuery(); count = 0; while (rs.next() && (count++ < 5) ) { QuoteDataBean quoteData = getQuoteDataFromResultSet(rs); topGainersData.add(quoteData); } /* rs.last(); count = 0; while (rs.previous() && (count++ < 5) ) { QuoteDataBean quoteData = getQuoteDataFromResultSet(rs); topGainersData.add(quoteData); }*/ stmt.close(); stmt = getStatement(conn, getTSIASQL); rs = stmt.executeQuery(); BigDecimal TSIA=ZERO; if (!rs.next() ) Log.error("TradeDirect:getMarketSummary -- error w/ getTSIASQL -- no results"); else TSIA = rs.getBigDecimal("TSIA"); stmt.close(); stmt = getStatement(conn, getOpenTSIASQL); rs = stmt.executeQuery(); BigDecimal openTSIA = ZERO; if (!rs.next() ) Log.error("TradeDirect:getMarketSummary -- error w/ getOpenTSIASQL -- no results"); else openTSIA = rs.getBigDecimal("openTSIA"); stmt.close(); stmt = getStatement(conn, getTSIATotalVolumeSQL); rs = stmt.executeQuery(); double volume=0.0; if (!rs.next() ) Log.error("TradeDirect:getMarketSummary -- error w/ getTSIATotalVolumeSQL -- no results"); else volume = rs.getDouble("totalVolume"); stmt.close(); commit(conn); marketSummaryData = new MarketSummaryDataBean(TSIA, openTSIA, volume, topGainersData, topLosersData); } catch (Exception e) { Log.error("TradeDirect:login -- error logging in user", e); rollBack(conn, e); } finally { releaseConn(conn); } return marketSummaryData; } /** * @see TradeServices#buy(String, String, double) */ public OrderDataBean buy(String userID, String symbol, double quantity, int orderProcessingMode) throws Exception { Connection conn=null; OrderDataBean orderData = null; UserTransaction txn = null; /* * total = (quantity * purchasePrice) + orderFee */ BigDecimal total; try { if (Log.doTrace()) Log.trace("TradeDirect:buy", userID, symbol, new Double(quantity)); if ( orderProcessingMode == TradeConfig.ASYNCH_2PHASE ) { if ( Log.doTrace() ) Log.trace("TradeDirect:buy create/begin global transaction"); //FUTURE the UserTransaction be looked up once txn = (javax.transaction.UserTransaction) context.lookup("java:comp/UserTransaction"); txn.begin(); setInGlobalTxn(true); } conn = getConn(); AccountDataBean accountData = getAccountData(conn, userID); QuoteDataBean quoteData = getQuoteData(conn, symbol); HoldingDataBean holdingData = null; // the buy operation will create the holding orderData = createOrder(conn, accountData, quoteData, holdingData, "buy", quantity); //Update -- account should be credited during completeOrder BigDecimal price = quoteData.getPrice(); BigDecimal orderFee = orderData.getOrderFee(); total = (new BigDecimal(quantity).multiply(price)).add(orderFee); // subtract total from account balance creditAccountBalance(conn, accountData, total.negate()); try { if (orderProcessingMode == TradeConfig.SYNCH) completeOrder(conn, orderData.getOrderID()); else if (orderProcessingMode == TradeConfig.ASYNCH) queueOrder(orderData.getOrderID(), false); // 1-phase commit else //TradeConfig.ASYNC_2PHASE queueOrder(orderData.getOrderID(), true); // 2-phase commit } catch (JMSException je) { Log.error("TradeBean:buy("+userID+","+symbol+","+quantity+") --> failed to queueOrder", je); /* On exception - cancel the order */ cancelOrder(conn, orderData.getOrderID()); } orderData = getOrderData(conn, orderData.getOrderID().intValue()); if (txn != null) { if ( Log.doTrace() ) Log.trace("TradeDirect:buy committing global transaction"); txn.commit(); setInGlobalTxn(false); } else commit(conn); } catch (Exception e) { Log.error("TradeDirect:buy error - rolling back", e); if ( getInGlobalTxn() ) txn.rollback(); else rollBack(conn, e); } finally { releaseConn(conn); } return orderData; } /** * @see TradeServices#sell(String, Integer) */ public OrderDataBean sell(String userID, Integer holdingID, int orderProcessingMode) throws Exception { Connection conn=null; OrderDataBean orderData = null; UserTransaction txn = null; /* * total = (quantity * purchasePrice) + orderFee */ BigDecimal total; try { if (Log.doTrace()) Log.trace("TradeDirect:sell", userID, holdingID); if ( orderProcessingMode == TradeConfig.ASYNCH_2PHASE ) { if ( Log.doTrace() ) Log.trace("TradeDirect:sell create/begin global transaction"); //FUTURE the UserTransaction be looked up once txn = (javax.transaction.UserTransaction) context.lookup("java:comp/UserTransaction"); txn.begin(); setInGlobalTxn(true); } conn = getConn(); AccountDataBean accountData = getAccountData(conn, userID); HoldingDataBean holdingData = getHoldingData(conn, holdingID.intValue() ); QuoteDataBean quoteData = null; if ( holdingData != null) quoteData = getQuoteData(conn, holdingData.getQuoteID()); if ( (accountData==null) || (holdingData==null) || (quoteData==null) ) { String error = "TradeDirect:sell -- error selling stock -- unable to find: \n\taccount=" +accountData + "\n\tholding=" + holdingData + "\n\tquote="+quoteData + "\nfor user: " + userID + " and holdingID: " + holdingID; Log.error(error); if ( getInGlobalTxn() ) txn.rollback(); else rollBack(conn, new Exception(error)); return orderData; } double quantity = holdingData.getQuantity(); orderData = createOrder(conn, accountData, quoteData, holdingData, "sell", quantity); // Set the holdingSymbol purchaseDate to selling to signify the sell is "inflight" updateHoldingStatus(conn, holdingData.getHoldingID(), holdingData.getQuoteID()); //UPDATE -- account should be credited during completeOrder BigDecimal price = quoteData.getPrice(); BigDecimal orderFee = orderData.getOrderFee(); total = (new BigDecimal(quantity).multiply(price)).subtract(orderFee); creditAccountBalance(conn, accountData, total); try { if (orderProcessingMode == TradeConfig.SYNCH) completeOrder(conn, orderData.getOrderID()); else if (orderProcessingMode == TradeConfig.ASYNCH) queueOrder(orderData.getOrderID(), false); // 1-phase commit else //TradeConfig.ASYNC_2PHASE queueOrder(orderData.getOrderID(), true); // 2-phase commit } catch (JMSException je) { Log.error("TradeBean:sell("+userID+","+holdingID+") --> failed to queueOrder", je); /* On exception - cancel the order */ cancelOrder(conn, orderData.getOrderID()); } orderData = getOrderData(conn, orderData.getOrderID().intValue()); if (txn != null) { if ( Log.doTrace() ) Log.trace("TradeDirect:sell committing global transaction"); txn.commit(); setInGlobalTxn(false); } else commit(conn); } catch (Exception e) { Log.error("TradeDirect:sell error", e); if ( getInGlobalTxn() ) txn.rollback(); else rollBack(conn, e); } finally { releaseConn(conn); } return orderData; } /** * @see TradeServices#queueOrder(Integer) */ public void queueOrder(Integer orderID, boolean twoPhase) throws Exception { if (Log.doTrace() ) Log.trace("TradeDirect:queueOrder", orderID); javax.jms.Connection conn = null; Session sess = null; try { conn = qConnFactory.createConnection(); sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = sess.createProducer(queue); TextMessage message = sess.createTextMessage(); String command= "neworder"; message.setStringProperty("command", command); message.setIntProperty("orderID", orderID.intValue()); message.setBooleanProperty("twoPhase", twoPhase); message.setBooleanProperty("direct", true); message.setLongProperty("publishTime", System.currentTimeMillis()); message.setText("neworder: orderID="+orderID + " runtimeMode=Direct twoPhase="+twoPhase); if (Log.doTrace()) Log.trace("TradeDirectBean:queueOrder Sending message: " + message.getText()); producer.send(message); sess.close(); } catch (Exception e) { throw e; // pass the exception back } finally { if (sess != null) sess.close(); } } /** * @see TradeServices#completeOrder(Integer) */ public OrderDataBean completeOrder(Integer orderID, boolean twoPhase) throws Exception { OrderDataBean orderData = null; Connection conn=null; if (!twoPhase) { if (Log.doTrace()) Log.trace("TradeDirect:completeOrder -- completing order in 1-phase, calling tradeEJB to start new txn. orderID="+orderID); return tradeEJB.completeOrderOnePhaseDirect(orderID); } try //twoPhase { if (Log.doTrace()) Log.trace("TradeDirect:completeOrder", orderID); setInGlobalTxn(twoPhase); conn = getConn(); orderData = completeOrder(conn, orderID); commit(conn); } catch (Exception e) { Log.error("TradeDirect:completeOrder -- error completing order", e); rollBack(conn, e); cancelOrder(orderID, twoPhase); } finally { releaseConn(conn); } return orderData; } public OrderDataBean completeOrderOnePhase(Integer orderID) throws Exception { OrderDataBean orderData = null; Connection conn=null; try { if (Log.doTrace()) Log.trace("TradeDirect:completeOrderOnePhase", orderID); setInGlobalTxn(false); conn = getConn(); orderData = completeOrder(conn, orderID); commit(conn); } catch (Exception e) { Log.error("TradeDirect:completeOrderOnePhase -- error completing order", e); rollBack(conn, e); cancelOrder(orderID, false); } finally { releaseConn(conn); } return orderData; } private OrderDataBean completeOrder(Connection conn, Integer orderID) throws Exception { OrderDataBean orderData = null; if (Log.doTrace()) Log.trace("TradeDirect:completeOrderInternal", orderID); PreparedStatement stmt = getStatement(conn, getOrderSQL); stmt.setInt(1, orderID.intValue()); ResultSet rs = stmt.executeQuery(); if ( !rs.next() ) { Log.error("TradeDirect:completeOrder -- unable to find order: " + orderID); stmt.close(); return orderData; } orderData = getOrderDataFromResultSet(rs); String orderType = orderData.getOrderType(); String orderStatus = orderData.getOrderStatus(); //if (order.isCompleted()) if ( (orderStatus.compareToIgnoreCase("completed") == 0) || (orderStatus.compareToIgnoreCase("alertcompleted") == 0) || (orderStatus.compareToIgnoreCase("cancelled") == 0) ) throw new Exception("TradeDirect:completeOrder -- attempt to complete Order that is already completed"); int accountID = rs.getInt("account_accountID"); String quoteID = rs.getString("quote_symbol"); int holdingID = rs.getInt("holding_holdingID"); BigDecimal price = orderData.getPrice(); double quantity = orderData.getQuantity(); BigDecimal orderFee = orderData.getOrderFee(); //get the data for the account and quote //the holding will be created for a buy or extracted for a sell /* Use the AccountID and Quote Symbol from the Order AccountDataBean accountData = getAccountData(accountID, conn); QuoteDataBean quoteData = getQuoteData(conn, quoteID); */ String userID = getAccountProfileData(conn, new Integer(accountID)).getUserID(); HoldingDataBean holdingData = null; if (Log.doTrace()) Log.trace( "TradeDirect:completeOrder--> Completing Order " + orderData.getOrderID() + "\n\t Order info: " + orderData + "\n\t Account info: " + accountID + "\n\t Quote info: " + quoteID); //if (order.isBuy()) if ( orderType.compareToIgnoreCase("buy") == 0 ) { /* Complete a Buy operation * - create a new Holding for the Account * - deduct the Order cost from the Account balance */ holdingData = createHolding(conn, accountID, quoteID, quantity, price); updateOrderHolding(conn, orderID.intValue(), holdingData.getHoldingID().intValue()); } //if (order.isSell()) { if ( orderType.compareToIgnoreCase("sell") == 0 ) { /* Complete a Sell operation * - remove the Holding from the Account * - deposit the Order proceeds to the Account balance */ holdingData = getHoldingData(conn, holdingID); if ( holdingData == null ) Log.debug("TradeDirect:completeOrder:sell -- user: " + userID + " already sold holding: " + holdingID); else removeHolding(conn, holdingID, orderID.intValue()); } updateOrderStatus(conn, orderData.getOrderID(), "closed"); if (Log.doTrace()) Log.trace( "TradeDirect:completeOrder--> Completed Order " + orderData.getOrderID() + "\n\t Order info: " + orderData + "\n\t Account info: " + accountID + "\n\t Quote info: " + quoteID + "\n\t Holding info: " + holdingData); stmt.close(); commit(conn); //signify this order for user userID is complete TradeAction tradeAction = new TradeAction(this); tradeAction.orderCompleted(userID, orderID); return orderData; } /** * @see TradeServices#cancelOrder(Integer, boolean) */ public void cancelOrder(Integer orderID, boolean twoPhase) throws Exception { OrderDataBean orderData = null; Connection conn=null; try { if (Log.doTrace()) Log.trace("TradeDirect:cancelOrder", orderID); setInGlobalTxn(twoPhase); conn = getConn(); cancelOrder(conn, orderID); commit(conn); } catch (Exception e) { Log.error("TradeDirect:cancelOrder -- error cancelling order: "+orderID, e); rollBack(conn, e); } finally { releaseConn(conn); } } public void cancelOrderOnePhase(Integer orderID) throws Exception { OrderDataBean orderData = null; Connection conn=null; try { if (Log.doTrace()) Log.trace("TradeDirect:cancelOrderOnePhase", orderID); setInGlobalTxn(false); conn = getConn(); cancelOrder(conn, orderID); commit(conn); } catch (Exception e) { Log.error("TradeDirect:cancelOrderOnePhase -- error cancelling order: "+orderID, e); rollBack(conn, e); } finally { releaseConn(conn); } } private void cancelOrder(Connection conn, Integer orderID) throws Exception { updateOrderStatus(conn, orderID, "cancelled"); } public void orderCompleted(String userID, Integer orderID) throws Exception { throw new UnsupportedOperationException("TradeDirect:orderCompleted method not supported"); } private HoldingDataBean createHolding(Connection conn, int accountID, String symbol, double quantity, BigDecimal purchasePrice) throws Exception { HoldingDataBean holdingData = null; Timestamp purchaseDate = new Timestamp(System.currentTimeMillis()); PreparedStatement stmt = getStatement(conn, createHoldingSQL); Integer holdingID = KeySequenceDirect.getNextID(conn, "holding", getInGlobalTxn()); stmt.setInt(1, holdingID.intValue()); stmt.setTimestamp(2, purchaseDate); stmt.setBigDecimal(3, purchasePrice); stmt.setDouble(4, quantity); stmt.setString(5, symbol); stmt.setInt(6, accountID); int rowCount = stmt.executeUpdate(); stmt.close(); return getHoldingData(conn, holdingID.intValue()); } private void removeHolding(Connection conn, int holdingID, int orderID) throws Exception { PreparedStatement stmt = getStatement(conn, removeHoldingSQL); stmt.setInt(1, holdingID); int rowCount = stmt.executeUpdate(); stmt.close(); // set the HoldingID to NULL for the purchase and sell order now that // the holding as been removed stmt = getStatement(conn, removeHoldingFromOrderSQL); stmt.setInt(1, holdingID); rowCount = stmt.executeUpdate(); stmt.close(); } private OrderDataBean createOrder(Connection conn, AccountDataBean accountData, QuoteDataBean quoteData, HoldingDataBean holdingData, String orderType, double quantity) throws Exception { OrderDataBean orderData = null; Timestamp currentDate = new Timestamp(System.currentTimeMillis()); PreparedStatement stmt = getStatement(conn, createOrderSQL); Integer orderID = KeySequenceDirect.getNextID(conn, "order", getInGlobalTxn()); stmt.setInt(1, orderID.intValue()); stmt.setString(2, orderType); stmt.setString(3, "open"); stmt.setTimestamp(4, currentDate); stmt.setDouble(5, quantity); stmt.setBigDecimal(6, quoteData.getPrice().setScale(FinancialUtils.SCALE, FinancialUtils.ROUND)); stmt.setBigDecimal(7, TradeConfig.getOrderFee(orderType)); stmt.setInt(8, accountData.getAccountID().intValue()); if (holdingData == null ) stmt.setNull(9, java.sql.Types.INTEGER); else stmt.setInt(9, holdingData.getHoldingID().intValue()); stmt.setString(10, quoteData.getSymbol()); int rowCount = stmt.executeUpdate(); stmt.close(); return getOrderData(conn, orderID.intValue()); } /** * @see TradeServices#getOrders(String) */ public Collection getOrders(String userID) throws Exception { Collection orderDataBeans = new ArrayList(); Connection conn=null; try { if (Log.doTrace()) Log.trace("TradeDirect:getOrders", userID); conn = getConn(); PreparedStatement stmt = getStatement(conn, getOrdersByUserSQL); stmt.setString(1, userID); ResultSet rs = stmt.executeQuery(); //TODO: return top 5 orders for now -- next version will add a getAllOrders method // also need to get orders sorted by order id descending int i=0; while ( (rs.next()) && (i++ < 5) ) { OrderDataBean orderData = getOrderDataFromResultSet(rs); orderDataBeans.add(orderData); } stmt.close(); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getOrders -- error getting user orders", e); rollBack(conn, e); } finally { releaseConn(conn); } return orderDataBeans; } /** * @see TradeServices#getClosedOrders(String) */ public Collection getClosedOrders(String userID) throws Exception { Collection orderDataBeans = new ArrayList(); Connection conn=null; try { if (Log.doTrace()) Log.trace("TradeDirect:getClosedOrders", userID); conn = getConn(); PreparedStatement stmt = getStatement(conn, getClosedOrdersSQL); stmt.setString(1, userID); ResultSet rs = stmt.executeQuery(); while ( rs.next() ) { OrderDataBean orderData = getOrderDataFromResultSet(rs); orderData.setOrderStatus("completed"); updateOrderStatus(conn, orderData.getOrderID(), orderData.getOrderStatus()); orderDataBeans.add(orderData); } stmt.close(); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getOrders -- error getting user orders", e); rollBack(conn, e); } finally { releaseConn(conn); } return orderDataBeans; } /** * @see TradeServices#createQuote(String, String, BigDecimal) */ public QuoteDataBean createQuote( String symbol, String companyName, BigDecimal price) throws Exception { QuoteDataBean quoteData = null; Connection conn=null; try { if (Log.doTrace()) Log.traceEnter("TradeDirect:createQuote"); price = price.setScale(FinancialUtils.SCALE, FinancialUtils.ROUND); double volume=0.0, change=0.0; conn = getConn(); PreparedStatement stmt = getStatement(conn, createQuoteSQL); stmt.setString(1, symbol); // symbol stmt.setString(2, companyName); // companyName stmt.setDouble(3, volume); // volume stmt.setBigDecimal(4, price); // price stmt.setBigDecimal(5, price); // open stmt.setBigDecimal(6, price); // low stmt.setBigDecimal(7, price); // high stmt.setDouble(8, change); // change stmt.executeUpdate(); stmt.close(); commit(conn); quoteData = new QuoteDataBean(symbol, companyName, volume, price, price, price, price, change); if (Log.doTrace()) Log.traceExit("TradeDirect:createQuote"); } catch (Exception e) { Log.error("TradeDirect:createQuote -- error creating quote", e); } finally { releaseConn(conn); } return quoteData; } /** * @see TradeServices#getQuote(String) */ public QuoteDataBean getQuote(String symbol) throws Exception { QuoteDataBean quoteData = null; Connection conn=null; UserTransaction txn = null; try { if (Log.doTrace()) Log.trace("TradeDirect:getQuote", symbol); conn = getConn(); quoteData = getQuote(conn, symbol); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getQuote -- error getting quote", e); rollBack(conn, e); } finally { releaseConn(conn); } return quoteData; } private QuoteDataBean getQuote(Connection conn, String symbol) throws Exception { QuoteDataBean quoteData = null; PreparedStatement stmt = getStatement(conn, getQuoteSQL); stmt.setString(1, symbol); // symbol ResultSet rs = stmt.executeQuery(); if ( !rs.next() ) Log.error("TradeDirect:getQuote -- failure no result.next() for symbol: " + symbol); else quoteData = getQuoteDataFromResultSet(rs); stmt.close(); return quoteData; } private QuoteDataBean getQuoteForUpdate(Connection conn, String symbol) throws Exception { QuoteDataBean quoteData = null; PreparedStatement stmt = getStatement(conn, getQuoteForUpdateSQL); stmt.setString(1, symbol); // symbol ResultSet rs = stmt.executeQuery(); if ( !rs.next() ) Log.error("TradeDirect:getQuote -- failure no result.next()"); else quoteData = getQuoteDataFromResultSet(rs); stmt.close(); return quoteData; } /** * @see TradeServices#getAllQuotes(String) */ public Collection getAllQuotes() throws Exception { Collection quotes = new ArrayList(); QuoteDataBean quoteData = null; Connection conn = null; try { conn = getConn(); PreparedStatement stmt = getStatement(conn, getAllQuotesSQL); ResultSet rs = stmt.executeQuery(); while (!rs.next()) { quoteData = getQuoteDataFromResultSet(rs); quotes.add(quoteData); } stmt.close(); } catch (Exception e) { Log.error("TradeDirect:getAllQuotes", e); rollBack(conn, e); } finally { releaseConn(conn); } return quotes; } /** * @see TradeServices#getHoldings(String) */ public Collection getHoldings(String userID) throws Exception { Collection holdingDataBeans = new ArrayList(); Connection conn=null; try { if (Log.doTrace()) Log.trace("TradeDirect:getHoldings", userID); conn = getConn(); PreparedStatement stmt = getStatement(conn, getHoldingsForUserSQL); stmt.setString(1, userID); ResultSet rs = stmt.executeQuery(); while ( rs.next() ) { HoldingDataBean holdingData = getHoldingDataFromResultSet(rs); holdingDataBeans.add(holdingData); } stmt.close(); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getHoldings -- error getting user holings", e); rollBack(conn, e); } finally { releaseConn(conn); } return holdingDataBeans; } /** * @see TradeServices#getHolding(Integer) */ public HoldingDataBean getHolding(Integer holdingID) throws Exception { HoldingDataBean holdingData = null; Connection conn=null; try { if (Log.doTrace()) Log.trace("TradeDirect:getHolding", holdingID); conn = getConn(); holdingData = getHoldingData(holdingID.intValue()); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getHolding -- error getting holding " + holdingID + "", e); rollBack(conn, e); } finally { releaseConn(conn); } return holdingData; } /** * @see TradeServices#getAccountData(String) */ public AccountDataBean getAccountData(String userID) throws RemoteException { try{ AccountDataBean accountData = null; Connection conn=null; try { if (Log.doTrace()) Log.trace("TradeDirect:getAccountData", userID); conn = getConn(); accountData = getAccountData(conn, userID); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getAccountData -- error getting account data", e); rollBack(conn, e); } finally { releaseConn(conn); } return accountData; }catch (Exception e){ throw new RemoteException(e.getMessage(),e); } } private AccountDataBean getAccountData(Connection conn, String userID) throws Exception { PreparedStatement stmt = getStatement(conn, getAccountForUserSQL); stmt.setString(1, userID); ResultSet rs = stmt.executeQuery(); AccountDataBean accountData = getAccountDataFromResultSet(rs); stmt.close(); return accountData; } private AccountDataBean getAccountDataForUpdate(Connection conn, String userID) throws Exception { PreparedStatement stmt = getStatement(conn, getAccountForUserForUpdateSQL); stmt.setString(1, userID); ResultSet rs = stmt.executeQuery(); AccountDataBean accountData = getAccountDataFromResultSet(rs); stmt.close(); return accountData; } /** * @see TradeServices#getAccountData(String) */ public AccountDataBean getAccountData(int accountID) throws Exception { AccountDataBean accountData = null; Connection conn=null; try { if (Log.doTrace()) Log.trace("TradeDirect:getAccountData", new Integer(accountID)); conn = getConn(); accountData = getAccountData(accountID, conn); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getAccountData -- error getting account data", e); rollBack(conn, e); } finally { releaseConn(conn); } return accountData; } private AccountDataBean getAccountData(int accountID, Connection conn) throws Exception { PreparedStatement stmt = getStatement(conn, getAccountSQL); stmt.setInt(1, accountID); ResultSet rs = stmt.executeQuery(); AccountDataBean accountData = getAccountDataFromResultSet(rs); stmt.close(); return accountData; } private AccountDataBean getAccountDataForUpdate(int accountID, Connection conn) throws Exception { PreparedStatement stmt = getStatement(conn, getAccountForUpdateSQL); stmt.setInt(1, accountID); ResultSet rs = stmt.executeQuery(); AccountDataBean accountData = getAccountDataFromResultSet(rs); stmt.close(); return accountData; } private QuoteDataBean getQuoteData(String symbol) throws Exception { QuoteDataBean quoteData = null; Connection conn=null; try { conn = getConn(); quoteData = getQuoteData(conn, symbol); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getQuoteData -- error getting data", e); rollBack(conn, e); } finally { releaseConn(conn); } return quoteData; } private QuoteDataBean getQuoteData(Connection conn, String symbol) throws Exception { QuoteDataBean quoteData = null; PreparedStatement stmt = getStatement(conn, getQuoteSQL); stmt.setString(1, symbol); ResultSet rs = stmt.executeQuery(); if (!rs.next()) Log.error("TradeDirect:getQuoteData -- could not find quote for symbol="+symbol); else quoteData = getQuoteDataFromResultSet(rs); stmt.close(); return quoteData; } private HoldingDataBean getHoldingData(int holdingID) throws Exception { HoldingDataBean holdingData = null; Connection conn=null; try { conn = getConn(); holdingData = getHoldingData(conn, holdingID); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getHoldingData -- error getting data", e); rollBack(conn, e); } finally { releaseConn(conn); } return holdingData; } private HoldingDataBean getHoldingData(Connection conn, int holdingID) throws Exception { HoldingDataBean holdingData = null; PreparedStatement stmt = getStatement(conn, getHoldingSQL); stmt.setInt(1, holdingID); ResultSet rs = stmt.executeQuery(); if (!rs.next()) Log.error("TradeDirect:getHoldingData -- no results -- holdingID="+holdingID); else holdingData = getHoldingDataFromResultSet(rs); stmt.close(); return holdingData; } private OrderDataBean getOrderData(int orderID) throws Exception { OrderDataBean orderData = null; Connection conn=null; try { conn = getConn(); orderData = getOrderData(conn, orderID); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getOrderData -- error getting data", e); rollBack(conn, e); } finally { releaseConn(conn); } return orderData; } private OrderDataBean getOrderData(Connection conn, int orderID) throws Exception { OrderDataBean orderData = null; if (Log.doTrace()) Log.trace("TradeDirect:getOrderData(conn, " + orderID + ")"); PreparedStatement stmt = getStatement(conn, getOrderSQL); stmt.setInt(1, orderID); ResultSet rs = stmt.executeQuery(); if (!rs.next()) Log.error("TradeDirect:getOrderData -- no results for orderID:" + orderID); else orderData = getOrderDataFromResultSet(rs); stmt.close(); return orderData; } /** * @see TradeServices#getAccountProfileData(String) */ public AccountProfileDataBean getAccountProfileData(String userID) throws Exception { AccountProfileDataBean accountProfileData = null; Connection conn=null; try { if (Log.doTrace()) Log.trace("TradeDirect:getAccountProfileData", userID); conn = getConn(); accountProfileData = getAccountProfileData(conn, userID); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getAccountProfileData -- error getting profile data", e); rollBack(conn, e); } finally { releaseConn(conn); } return accountProfileData; } private AccountProfileDataBean getAccountProfileData(Connection conn, String userID) throws Exception { PreparedStatement stmt = getStatement(conn, getAccountProfileSQL); stmt.setString(1, userID); ResultSet rs = stmt.executeQuery(); AccountProfileDataBean accountProfileData = getAccountProfileDataFromResultSet(rs); stmt.close(); return accountProfileData; } private AccountProfileDataBean getAccountProfileData(Integer accountID) throws Exception { AccountProfileDataBean accountProfileData = null; Connection conn=null; try { if (Log.doTrace()) Log.trace("TradeDirect:getAccountProfileData", accountID); conn = getConn(); accountProfileData = getAccountProfileData(conn, accountID); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getAccountProfileData -- error getting profile data", e); rollBack(conn, e); } finally { releaseConn(conn); } return accountProfileData; } private AccountProfileDataBean getAccountProfileData(Connection conn, Integer accountID) throws Exception { PreparedStatement stmt = getStatement(conn, getAccountProfileForAccountSQL); stmt.setInt(1, accountID.intValue()); ResultSet rs = stmt.executeQuery(); AccountProfileDataBean accountProfileData = getAccountProfileDataFromResultSet(rs); stmt.close(); return accountProfileData; } /** * @see TradeServices#updateAccountProfile(AccountProfileDataBean) */ public AccountProfileDataBean updateAccountProfile(AccountProfileDataBean profileData) throws Exception { AccountProfileDataBean accountProfileData = null; Connection conn=null; try { if (Log.doTrace()) Log.trace("TradeDirect:updateAccountProfileData", profileData.getUserID()); conn = getConn(); updateAccountProfile(conn, profileData); accountProfileData = getAccountProfileData(conn, profileData.getUserID()); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getAccountProfileData -- error getting profile data", e); rollBack(conn, e); } finally { releaseConn(conn); } return accountProfileData; } private void creditAccountBalance(Connection conn, AccountDataBean accountData, BigDecimal credit) throws Exception { PreparedStatement stmt = getStatement(conn, creditAccountBalanceSQL); stmt.setBigDecimal(1, credit); stmt.setInt(2, accountData.getAccountID().intValue()); int count = stmt.executeUpdate(); stmt.close(); } // Set Timestamp to zero to denote sell is inflight // UPDATE -- could add a "status" attribute to holding private void updateHoldingStatus(Connection conn, Integer holdingID, String symbol) throws Exception { Timestamp ts = new Timestamp(0); PreparedStatement stmt = getStatement(conn, "update holdingejb set purchasedate= ? where holdingid = ?"); stmt.setTimestamp(1, ts); stmt.setInt(2, holdingID.intValue()); int count = stmt.executeUpdate(); stmt.close(); } private void updateOrderStatus(Connection conn, Integer orderID, String status) throws Exception { PreparedStatement stmt = getStatement(conn, updateOrderStatusSQL); stmt.setString(1, status); stmt.setTimestamp(2, new Timestamp(System.currentTimeMillis())); stmt.setInt(3, orderID.intValue()); int count = stmt.executeUpdate(); stmt.close(); } private void updateOrderHolding(Connection conn, int orderID, int holdingID) throws Exception { PreparedStatement stmt = getStatement(conn, updateOrderHoldingSQL); stmt.setInt(1, holdingID); stmt.setInt(2, orderID); int count = stmt.executeUpdate(); stmt.close(); } private void updateAccountProfile(Connection conn, AccountProfileDataBean profileData) throws Exception { PreparedStatement stmt = getStatement(conn, updateAccountProfileSQL); stmt.setString(1, profileData.getPassword()); stmt.setString(2, profileData.getFullName()); stmt.setString(3, profileData.getAddress()); stmt.setString(4, profileData.getEmail()); stmt.setString(5, profileData.getCreditCard()); stmt.setString(6, profileData.getUserID()); int count = stmt.executeUpdate(); stmt.close(); } private void updateQuoteVolume(Connection conn, QuoteDataBean quoteData, double quantity) throws Exception { PreparedStatement stmt = getStatement(conn, updateQuoteVolumeSQL); stmt.setDouble(1, quantity); stmt.setString(2, quoteData.getSymbol()); int count = stmt.executeUpdate(); stmt.close(); } public QuoteDataBean updateQuotePriceVolume(String symbol, BigDecimal changeFactor, double sharesTraded) throws Exception { return updateQuotePriceVolumeInt(symbol, changeFactor, sharesTraded, publishQuotePriceChange); } /** * Update a quote's price and volume * @param symbol The PK of the quote * @param changeFactor the percent to change the old price by (between 50% and 150%) * @param sharedTraded the ammount to add to the current volume * @param publishQuotePriceChange used by the PingJDBCWrite Primitive to ensure no JMS is used, should * be true for all normal calls to this API */ public QuoteDataBean updateQuotePriceVolumeInt(String symbol, BigDecimal changeFactor, double sharesTraded, boolean publishQuotePriceChange) throws Exception { if ( TradeConfig.getUpdateQuotePrices() == false ) return new QuoteDataBean(); QuoteDataBean quoteData = null; Connection conn=null; UserTransaction txn = null; try { if (Log.doTrace()) Log.trace("TradeDirect:updateQuotePriceVolume", symbol, changeFactor, new Double(sharesTraded)); conn = getConn(); quoteData = getQuoteForUpdate(conn, symbol); BigDecimal oldPrice = quoteData.getPrice(); double newVolume = quoteData.getVolume() + sharesTraded; if (oldPrice.equals(TradeConfig.PENNY_STOCK_PRICE)) { changeFactor = TradeConfig.PENNY_STOCK_RECOVERY_MIRACLE_MULTIPLIER; } BigDecimal newPrice = changeFactor.multiply(oldPrice).setScale(2, BigDecimal.ROUND_HALF_UP); updateQuotePriceVolume(conn, quoteData.getSymbol(), newPrice, newVolume); quoteData = getQuote(conn, symbol); commit(conn); if (publishQuotePriceChange) { publishQuotePriceChange(quoteData, oldPrice, changeFactor, sharesTraded); } } catch (Exception e) { Log.error("TradeDirect:updateQuotePriceVolume -- error updating quote price/volume for symbol:" + symbol); rollBack(conn, e); throw e; } finally { releaseConn(conn); } return quoteData; } private void updateQuotePriceVolume(Connection conn, String symbol, BigDecimal newPrice, double newVolume) throws Exception { PreparedStatement stmt = getStatement(conn, updateQuotePriceVolumeSQL); stmt.setBigDecimal(1, newPrice); stmt.setBigDecimal(2, newPrice); stmt.setDouble(3, newVolume); stmt.setString(4, symbol); int count = stmt.executeUpdate(); stmt.close(); } private void publishQuotePriceChange(QuoteDataBean quoteData, BigDecimal oldPrice, BigDecimal changeFactor, double sharesTraded) throws Exception { if (Log.doTrace()) Log.trace("TradeDirect:publishQuotePrice PUBLISHING to MDB quoteData = " + quoteData); javax.jms.Connection conn = null; Session sess = null; try { conn = tConnFactory.createConnection(); sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = sess.createProducer(streamerTopic); TextMessage message = sess.createTextMessage(); String command = "updateQuote"; message.setStringProperty("command", command); message.setStringProperty("symbol", quoteData.getSymbol() ); message.setStringProperty("company", quoteData.getCompanyName() ); message.setStringProperty("price", quoteData.getPrice().toString()); message.setStringProperty("oldPrice",oldPrice.toString()); message.setStringProperty("open", quoteData.getOpen().toString()); message.setStringProperty("low", quoteData.getLow().toString()); message.setStringProperty("high", quoteData.getHigh().toString()); message.setDoubleProperty("volume", quoteData.getVolume()); message.setStringProperty("changeFactor", changeFactor.toString()); message.setDoubleProperty("sharesTraded", sharesTraded); message.setLongProperty("publishTime", System.currentTimeMillis()); message.setText("Update Stock price for " + quoteData.getSymbol() + " old price = " + oldPrice + " new price = " + quoteData.getPrice()); producer.send(message); } catch (Exception e) { throw e; //pass exception back } finally { if (conn != null) conn.close(); if (sess != null) sess.close(); } } /** * @see TradeServices#login(String, String) */ public AccountDataBean login(String userID, String password) throws Exception { AccountDataBean accountData = null; Connection conn=null; try { if (Log.doTrace()) Log.trace("TradeDirect:login", userID, password); conn = getConn(); PreparedStatement stmt = getStatement(conn, getAccountProfileSQL); stmt.setString(1, userID); ResultSet rs = stmt.executeQuery(); if ( !rs.next() ) { Log.error("TradeDirect:login -- failure to find account for" + userID); throw new javax.ejb.FinderException("Cannot find account for" + userID); } String pw = rs.getString("password"); stmt.close(); if ( (pw==null) || (pw.equals(password) == false) ) { String error = "TradeDirect:Login failure for user: " + userID + "\n\tIncorrect password-->" + userID + ":" + password; Log.error(error); throw new Exception(error); } stmt = getStatement(conn, loginSQL); stmt.setTimestamp(1, new Timestamp(System.currentTimeMillis())); stmt.setString(2, userID); int rows = stmt.executeUpdate(); //?assert rows==1? stmt = getStatement(conn, getAccountForUserSQL); stmt.setString(1, userID); rs = stmt.executeQuery(); accountData = getAccountDataFromResultSet(rs); stmt.close(); commit(conn); } catch (Exception e) { Log.error("TradeDirect:login -- error logging in user", e); rollBack(conn, e); } finally { releaseConn(conn); } return accountData; /* setLastLogin( new Timestamp(System.currentTimeMillis()) ); setLoginCount( getLoginCount() + 1 ); */ } /** * @see TradeServices#logout(String) */ public void logout(String userID) throws Exception { if (Log.doTrace()) Log.trace("TradeDirect:logout", userID); Connection conn=null; try { conn = getConn(); PreparedStatement stmt = getStatement(conn, logoutSQL); stmt.setString(1, userID); stmt.executeUpdate(); stmt.close(); commit(conn); } catch (Exception e) { Log.error("TradeDirect:logout -- error logging out user", e); rollBack(conn, e); } finally { releaseConn(conn); } } /** * @see TradeServices#register(String, String, String, String, String, String, BigDecimal, boolean) */ public AccountDataBean register( String userID, String password, String fullname, String address, String email, String creditcard, BigDecimal openBalance) throws Exception { AccountDataBean accountData = null; Connection conn=null; try { if (Log.doTrace()) Log.traceEnter("TradeDirect:register"); conn = getConn(); PreparedStatement stmt = getStatement(conn, createAccountSQL); Integer accountID = KeySequenceDirect.getNextID(conn, "account", getInGlobalTxn()); BigDecimal balance = openBalance; Timestamp creationDate = new Timestamp(System.currentTimeMillis()); Timestamp lastLogin = creationDate; int loginCount = 0; int logoutCount = 0; stmt.setInt(1, accountID.intValue()); stmt.setTimestamp(2, creationDate); stmt.setBigDecimal(3, openBalance); stmt.setBigDecimal(4, balance); stmt.setTimestamp(5, lastLogin); stmt.setInt(6, loginCount); stmt.setInt(7, logoutCount); stmt.setString(8, userID); stmt.executeUpdate(); stmt.close(); stmt = getStatement(conn, createAccountProfileSQL); stmt.setString(1, userID); stmt.setString(2, password); stmt.setString(3, fullname); stmt.setString(4, address); stmt.setString(5, email); stmt.setString(6, creditcard); stmt.executeUpdate(); stmt.close(); commit(conn); accountData = new AccountDataBean(accountID, loginCount, logoutCount, lastLogin, creationDate, balance, openBalance, userID); if (Log.doTrace()) Log.traceExit("TradeDirect:register"); } catch (Exception e) { Log.error("TradeDirect:register -- error registering new user", e); } finally { releaseConn(conn); } return accountData; } private AccountDataBean getAccountDataFromResultSet(ResultSet rs) throws Exception { AccountDataBean accountData = null; if (!rs.next() ) Log.error("TradeDirect:getAccountDataFromResultSet -- cannot find account data"); else accountData = new AccountDataBean( new Integer(rs.getInt("accountID")), rs.getInt("loginCount"), rs.getInt("logoutCount"), rs.getTimestamp("lastLogin"), rs.getTimestamp("creationDate"), rs.getBigDecimal("balance"), rs.getBigDecimal("openBalance"), rs.getString("profile_userID") ); return accountData; } private AccountProfileDataBean getAccountProfileDataFromResultSet(ResultSet rs) throws Exception { AccountProfileDataBean accountProfileData = null; if (!rs.next() ) Log.error("TradeDirect:getAccountProfileDataFromResultSet -- cannot find accountprofile data"); else accountProfileData = new AccountProfileDataBean( rs.getString("userID"), rs.getString("password"), rs.getString("fullName"), rs.getString("address"), rs.getString("email"), rs.getString("creditCard") ); return accountProfileData; } private HoldingDataBean getHoldingDataFromResultSet(ResultSet rs) throws Exception { HoldingDataBean holdingData = null; holdingData = new HoldingDataBean( new Integer(rs.getInt("holdingID")), rs.getDouble("quantity"), rs.getBigDecimal("purchasePrice"), rs.getTimestamp("purchaseDate"), rs.getString("quote_symbol") ); return holdingData; } private QuoteDataBean getQuoteDataFromResultSet(ResultSet rs) throws Exception { QuoteDataBean quoteData = null; quoteData = new QuoteDataBean( rs.getString("symbol"), rs.getString("companyName"), rs.getDouble("volume"), rs.getBigDecimal("price"), rs.getBigDecimal("open1"), rs.getBigDecimal("low"), rs.getBigDecimal("high"), rs.getDouble("change1") ); return quoteData; } private OrderDataBean getOrderDataFromResultSet(ResultSet rs) throws Exception { OrderDataBean orderData = null; orderData = new OrderDataBean( new Integer(rs.getInt("orderID")), rs.getString("orderType"), rs.getString("orderStatus"), rs.getTimestamp("openDate"), rs.getTimestamp("completionDate"), rs.getDouble("quantity"), rs.getBigDecimal("price"), rs.getBigDecimal("orderFee"), rs.getString("quote_symbol") ); return orderData; } public RunStatsDataBean resetTrade(boolean deleteAll) throws Exception { //Clear MDB Statistics MDBStats.getInstance().reset(); // Reset Trade RunStatsDataBean runStatsData = new RunStatsDataBean(); Connection conn=null; UserTransaction txn = null; try { if (Log.doTrace()) Log.traceEnter("TradeDirect:resetTrade deleteAll rows=" + deleteAll); conn = getConn(); PreparedStatement stmt=null; ResultSet rs = null; if (deleteAll) { try { stmt = getStatement(conn, "delete from quoteejb"); stmt.executeUpdate(); stmt.close(); stmt = getStatement(conn, "delete from accountejb"); stmt.executeUpdate(); stmt.close(); stmt = getStatement(conn, "delete from accountprofileejb"); stmt.executeUpdate(); stmt.close(); stmt = getStatement(conn, "delete from holdingejb"); stmt.executeUpdate(); stmt.close(); stmt = getStatement(conn, "delete from orderejb"); stmt.executeUpdate(); stmt.close(); // FUTURE: - DuplicateKeyException - For now, don't start at // zero as KeySequenceDirect and KeySequenceBean will still give out // the cached Block and then notice this change. Better solution is // to signal both classes to drop their cached blocks //stmt = getStatement(conn, "delete from keygenejb"); //stmt.executeUpdate(); //stmt.close(); commit(conn); } catch (Exception e) { Log.error(e,"TradeDirect:resetTrade(deleteAll) -- Error deleting Trade users and stock from the Trade database"); } return runStatsData; } stmt = getStatement(conn, "delete from holdingejb where holdingejb.account_accountid is null"); int x = stmt.executeUpdate(); stmt.close(); //Count and Delete newly registered users (users w/ id that start "ru:%": stmt = getStatement(conn, "delete from accountprofileejb where userid like 'ru:%'"); int rowCount = stmt.executeUpdate(); stmt.close(); stmt = getStatement(conn, "delete from orderejb where account_accountid in (select accountid from accountejb a where a.profile_userid like 'ru:%')"); rowCount = stmt.executeUpdate(); stmt.close(); stmt = getStatement(conn, "delete from holdingejb where account_accountid in (select accountid from accountejb a where a.profile_userid like 'ru:%')"); rowCount = stmt.executeUpdate(); stmt.close(); stmt = getStatement(conn, "delete from accountejb where profile_userid like 'ru:%'"); int newUserCount = stmt.executeUpdate(); runStatsData.setNewUserCount(newUserCount); stmt.close(); //Count of trade users stmt = getStatement(conn, "select count(accountid) as \"tradeUserCount\" from accountejb a where a.profile_userid like 'uid:%'"); rs = stmt.executeQuery(); rs.next(); int tradeUserCount = rs.getInt("tradeUserCount"); runStatsData.setTradeUserCount(tradeUserCount); stmt.close(); rs.close(); //Count of trade stocks stmt = getStatement(conn, "select count(symbol) as \"tradeStockCount\" from quoteejb a where a.symbol like 's:%'"); rs = stmt.executeQuery(); rs.next(); int tradeStockCount = rs.getInt("tradeStockCount"); runStatsData.setTradeStockCount(tradeStockCount); stmt.close(); //Count of trade users login, logout stmt = getStatement(conn, "select sum(loginCount) as \"sumLoginCount\", sum(logoutCount) as \"sumLogoutCount\" from accountejb a where a.profile_userID like 'uid:%'"); rs = stmt.executeQuery(); rs.next(); int sumLoginCount = rs.getInt("sumLoginCount"); int sumLogoutCount = rs.getInt("sumLogoutCount"); runStatsData.setSumLoginCount(sumLoginCount); runStatsData.setSumLogoutCount(sumLogoutCount); stmt.close(); rs.close(); //Update logoutcount and loginCount back to zero stmt = getStatement(conn, "update accountejb set logoutCount=0,loginCount=0 where profile_userID like 'uid:%'"); rowCount = stmt.executeUpdate(); stmt.close(); //count holdings for trade users stmt = getStatement(conn, "select count(holdingid) as \"holdingCount\" from holdingejb h where h.account_accountid in " + "(select accountid from accountejb a where a.profile_userid like 'uid:%')"); rs = stmt.executeQuery(); rs.next(); int holdingCount = rs.getInt("holdingCount"); runStatsData.setHoldingCount(holdingCount); stmt.close(); rs.close(); //count orders for trade users stmt = getStatement(conn, "select count(orderid) as \"orderCount\" from orderejb o where o.account_accountid in " + "(select accountid from accountejb a where a.profile_userid like 'uid:%')"); rs = stmt.executeQuery(); rs.next(); int orderCount = rs.getInt("orderCount"); runStatsData.setOrderCount(orderCount); stmt.close(); rs.close(); //count orders by type for trade users stmt = getStatement(conn, "select count(orderid) \"buyOrderCount\"from orderejb o where (o.account_accountid in " + "(select accountid from accountejb a where a.profile_userid like 'uid:%')) AND " + " (o.orderType='buy')"); rs = stmt.executeQuery(); rs.next(); int buyOrderCount = rs.getInt("buyOrderCount"); runStatsData.setBuyOrderCount(buyOrderCount); stmt.close(); rs.close(); //count orders by type for trade users stmt = getStatement(conn, "select count(orderid) \"sellOrderCount\"from orderejb o where (o.account_accountid in " + "(select accountid from accountejb a where a.profile_userid like 'uid:%')) AND " + " (o.orderType='sell')"); rs = stmt.executeQuery(); rs.next(); int sellOrderCount = rs.getInt("sellOrderCount"); runStatsData.setSellOrderCount(sellOrderCount); stmt.close(); rs.close(); //Delete cancelled orders stmt = getStatement(conn, "delete from orderejb where orderStatus='cancelled'"); int cancelledOrderCount = stmt.executeUpdate(); runStatsData.setCancelledOrderCount(cancelledOrderCount); stmt.close(); rs.close(); //count open orders by type for trade users stmt = getStatement(conn, "select count(orderid) \"openOrderCount\"from orderejb o where (o.account_accountid in " + "(select accountid from accountejb a where a.profile_userid like 'uid:%')) AND " + " (o.orderStatus='open')"); rs = stmt.executeQuery(); rs.next(); int openOrderCount = rs.getInt("openOrderCount"); runStatsData.setOpenOrderCount(openOrderCount); stmt.close(); rs.close(); //Delete orders for holding which have been purchased and sold stmt = getStatement(conn, "delete from orderejb where holding_holdingid is null"); int deletedOrderCount = stmt.executeUpdate(); runStatsData.setDeletedOrderCount(deletedOrderCount); stmt.close(); rs.close(); commit(conn); System.out.println("TradeDirect:reset Run stats data\n\n" + runStatsData); } catch (Exception e) { Log.error(e, "Failed to reset Trade"); rollBack(conn, e); throw e; } finally { releaseConn(conn); } return runStatsData; } private void releaseConn(Connection conn) throws Exception { try { if ( conn!= null ) { conn.close(); if (Log.doTrace()) { synchronized(lock) { connCount--; } Log.trace("TradeDirect:releaseConn -- connection closed, connCount="+connCount); } } } catch (Exception e) { Log.error("TradeDirect:releaseConnection -- failed to close connection", e); } } /* * Lookup the TradeData datasource * */ private void getDataSource() throws Exception { datasource = (DataSource) context.lookup(dsName); } /* * Allocate a new connection to the datasource * */ private static int connCount=0; private static Integer lock = new Integer(0); private Connection getConn() throws Exception { Connection conn = null; if ( datasource == null ) getDataSource(); conn = datasource.getConnection(); conn.setAutoCommit(false); if (Log.doTrace()) { synchronized(lock) { connCount++; } Log.trace("TradeDirect:getConn -- new connection allocated, IsolationLevel=" + conn.getTransactionIsolation() + " connectionCount = " + connCount); } return conn; } /* * Commit the provided connection if not under Global Transaction scope * - conn.commit() is not allowed in a global transaction. the txn manager will * perform the commit */ private void commit(Connection conn) throws Exception { if ( (getInGlobalTxn()==false) && (conn != null) ) conn.commit(); } /* * Rollback the statement for the given connection * */ private void rollBack(Connection conn, Exception e) throws Exception { Log.log("TradeDirect:rollBack -- rolling back conn due to previously caught exception -- inGlobalTxn=" + getInGlobalTxn()); if ( (getInGlobalTxn()==false) && (conn != null) ) conn.rollback(); else throw e; // Throw the exception // so the Global txn manager will rollBack } /* * Allocate a new prepared statment for this connection * */ private PreparedStatement getStatement(Connection conn, String sql) throws Exception { return conn.prepareStatement(sql); } private PreparedStatement getStatement(Connection conn, String sql, int type, int concurrency) throws Exception { return conn.prepareStatement(sql, type, concurrency ); } private static final String createQuoteSQL = "insert into quoteejb " + "( symbol, companyName, volume, price, open1, low, high, change1 ) " + "VALUES ( ? , ? , ? , ? , ? , ? , ? , ? )"; private static final String createAccountSQL = "insert into accountejb " + "( accountid, creationDate, openBalance, balance, lastLogin, loginCount, logoutCount, profile_userid) " + "VALUES ( ? , ? , ? , ? , ? , ? , ? , ? )"; private static final String createAccountProfileSQL = "insert into accountprofileejb " + "( userid, password, fullname, address, email, creditcard ) " + "VALUES ( ? , ? , ? , ? , ? , ? )"; private static final String createHoldingSQL = "insert into holdingejb " + "( holdingid, purchaseDate, purchasePrice, quantity, quote_symbol, account_accountid ) " + "VALUES ( ? , ? , ? , ? , ? , ? )"; private static final String createOrderSQL = "insert into orderejb " + "( orderid, ordertype, orderstatus, opendate, quantity, price, orderfee, account_accountid, holding_holdingid, quote_symbol) " + "VALUES ( ? , ? , ? , ? , ? , ? , ? , ? , ? , ?)"; private static final String removeHoldingSQL = "delete from holdingejb where holdingid = ?"; private static final String removeHoldingFromOrderSQL = "update orderejb set holding_holdingid=null where holding_holdingid = ?"; private final static String updateAccountProfileSQL = "update accountprofileejb set " + "password = ?, fullname = ?, address = ?, email = ?, creditcard = ? " + "where userid = (select profile_userid from accountejb a " + "where a.profile_userid=?)"; private final static String loginSQL= "update accountejb set lastLogin=?, logincount=logincount+1 " + "where profile_userid=?"; private static final String logoutSQL = "update accountejb set logoutcount=logoutcount+1 " + "where profile_userid=?"; private static final String getAccountSQL = "select * from accountejb a where a.accountid = ?"; private static final String getAccountForUpdateSQL = "select * from accountejb a where a.accountid = ? for update"; private final static String getAccountProfileSQL = "select * from accountprofileejb ap where ap.userid = " + "(select profile_userid from accountejb a where a.profile_userid=?)"; private final static String getAccountProfileForAccountSQL = "select * from accountprofileejb ap where ap.userid = " + "(select profile_userid from accountejb a where a.accountid=?)"; private static final String getAccountForUserSQL = "select * from accountejb a where a.profile_userid = " + "( select userid from accountprofileejb ap where ap.userid = ?)"; private static final String getAccountForUserForUpdateSQL = "select * from accountejb a where a.profile_userid = " + "( select userid from accountprofileejb ap where ap.userid = ?) for update"; private static final String getHoldingSQL = "select * from holdingejb h where h.holdingid = ?"; private static final String getHoldingsForUserSQL = "select * from holdingejb h where h.account_accountid = " + "(select a.accountid from accountejb a where a.profile_userid = ?)"; private static final String getOrderSQL = "select * from orderejb o where o.orderid = ?"; private static final String getOrdersByUserSQL = "select * from orderejb o where o.account_accountid = " + "(select a.accountid from accountejb a where a.profile_userid = ?)"; private static final String getClosedOrdersSQL = "select * from orderejb o " + "where o.orderstatus = 'closed' AND o.account_accountid = " + "(select a.accountid from accountejb a where a.profile_userid = ?)"; private static final String getQuoteSQL = "select * from quoteejb q where q.symbol=?"; private static final String getAllQuotesSQL = "select * from quoteejb q"; private static final String getQuoteForUpdateSQL = "select * from quoteejb q where q.symbol=? For Update"; private static final String getTSIAQuotesOrderByChangeSQL = "select * from quoteejb q " + "where q.symbol like 's:1__' order by q.change1"; private static final String getTSIASQL = "select SUM(price)/count(*) as TSIA from quoteejb q " + "where q.symbol like 's:1__'"; private static final String getOpenTSIASQL = "select SUM(open1)/count(*) as openTSIA from quoteejb q " + "where q.symbol like 's:1__'"; private static final String getTSIATotalVolumeSQL = "select SUM(volume) as totalVolume from quoteejb q " + "where q.symbol like 's:1__'"; private static final String creditAccountBalanceSQL = "update accountejb set " + "balance = balance + ? " + "where accountid = ?"; private static final String updateOrderStatusSQL = "update orderejb set " + "orderstatus = ?, completiondate = ? " + "where orderid = ?"; private static final String updateOrderHoldingSQL = "update orderejb set " + "holding_holdingID = ? " + "where orderid = ?"; private static final String updateQuoteVolumeSQL = "update quoteejb set " + "volume = volume + ? " + "where symbol = ?"; private static final String updateQuotePriceVolumeSQL = "update quoteejb set " + "price = ?, change1 = ? - open1, volume = ? " + "where symbol = ?"; private static boolean initialized = false; public static synchronized void init() { TradeHome tradeHome=null; if (initialized) return; if (Log.doTrace()) Log.trace("TradeDirect:init -- *** initializing"); try { if (Log.doTrace()) Log.trace("TradeDirect: init"); context = new InitialContext(); datasource = (DataSource) context.lookup(dsName); } catch (Exception e) { Log.error("TradeDirect:init -- error on JNDI lookups of DataSource -- TradeDirect will not work", e); return; } try { tradeHome = (TradeHome) ( javax.rmi.PortableRemoteObject.narrow( context.lookup("java:comp/env/ejb/Trade"), TradeHome.class)); } catch (Exception e) { Log.error("TradeDirect:init -- error on JNDI lookup of Trade Session Bean -- TradeDirect will not work", e); return; } try { qConnFactory = (ConnectionFactory) context.lookup("java:comp/env/jms/QueueConnectionFactory"); } catch (Exception e) { Log.error("TradeDirect:init Unable to locate QueueConnectionFactory.\n\t -- Asynchronous mode will not work correctly and Quote Price change publishing will be disabled"); publishQuotePriceChange = false; } try { queue = (Queue) context.lookup("java:comp/env/jms/TradeBrokerQueue"); } catch (Exception e) { Log.error("TradeDirect:init Unable to locate TradeBrokerQueue.\n\t -- Asynchronous mode will not work correctly and Quote Price change publishing will be disabled"); publishQuotePriceChange = false; } try { tConnFactory = (ConnectionFactory) context.lookup("java:comp/env/jms/TopicConnectionFactory"); } catch (Exception e) { Log.error("TradeDirect:init Unable to locate TopicConnectionFactory.\n\t -- Asynchronous mode will not work correctly and Quote Price change publishing will be disabled"); publishQuotePriceChange = false; } try { streamerTopic = (Topic) context.lookup("java:comp/env/jms/TradeStreamerTopic"); } catch (Exception e) { Log.error("TradeDirect:init Unable to locate TradeStreamerTopic.\n\t -- Asynchronous mode will not work correctly and Quote Price change publishing will be disabled"); publishQuotePriceChange = false; } try { tradeEJB = (Trade) tradeHome.create(); } catch (Exception e) { Log.error("TradeDirect:init -- error looking up TradeEJB -- Asynchronous 1-phase will not work", e); } if (Log.doTrace()) Log.trace("TradeDirect:init -- +++ initialized"); initialized = true; } public static void destroy() { try { if (!initialized) return; Log.trace("TradeDirect:destroy"); } catch (Exception e) { Log.error("TradeDirect:destroy", e); } } private static InitialContext context; private static ConnectionFactory qConnFactory; private static Queue queue; private static ConnectionFactory tConnFactory; private static Topic streamerTopic; private static Trade tradeEJB; private static boolean publishQuotePriceChange = true; /** * Gets the inGlobalTxn * @return Returns a boolean */ private boolean getInGlobalTxn() { return inGlobalTxn; } /** * Sets the inGlobalTxn * @param inGlobalTxn The inGlobalTxn to set */ private void setInGlobalTxn(boolean inGlobalTxn) { this.inGlobalTxn = inGlobalTxn; } }
modules/ejb/src/main/java/org/apache/geronimo/samples/daytrader/direct/TradeDirect.java
/** * * Copyright 2005 The Apache Software Foundation or its licensors, as applicable * * 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.apache.geronimo.samples.daytrader.direct; import java.math.BigDecimal; import java.util.Collection; import java.util.ArrayList; import javax.naming.InitialContext; import javax.transaction.UserTransaction; import javax.jms.*; import javax.sql.DataSource; import org.apache.geronimo.samples.daytrader.ejb.Trade; import org.apache.geronimo.samples.daytrader.ejb.TradeHome; import org.apache.geronimo.samples.daytrader.util.*; import java.rmi.RemoteException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Timestamp; import org.apache.geronimo.samples.daytrader.*; /** * TradeDirect uses direct JDBC and JMS access to a <code>javax.sql.DataSource</code> to implement the business methods * of the Trade online broker application. These business methods represent the features and operations that * can be performed by customers of the brokerage such as login, logout, get a stock quote, buy or sell a stock, etc. * and are specified in the {@link org.apache.geronimo.samples.daytrader.TradeServices} interface * * Note: In order for this class to be thread-safe, a new TradeJDBC must be created * for each call to a method from the TradeInterface interface. Otherwise, pooled * connections may not be released. * * @see org.apache.geronimo.samples.daytrader.TradeServices * @see org.apache.geronimo.samples.daytrader.ejb.Trade * */ public class TradeDirect implements TradeServices { private static String dsName = TradeConfig.DATASOURCE; private static DataSource datasource = null; private static BigDecimal ZERO = new BigDecimal(0.0); private boolean inGlobalTxn = false; /** * Zero arg constructor for TradeDirect */ public TradeDirect() { if (initialized==false) init(); } /** * @see TradeServices#getMarketSummary() */ public MarketSummaryDataBean getMarketSummary() throws Exception { MarketSummaryDataBean marketSummaryData = null; Connection conn=null; try { if (Log.doTrace()) Log.trace("TradeDirect:getMarketSummary"); conn = getConn(); PreparedStatement stmt = getStatement(conn, getTSIAQuotesOrderByChangeSQL, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); ArrayList topGainersData = new ArrayList(5); ArrayList topLosersData = new ArrayList(5); ResultSet rs = stmt.executeQuery(); int count = 0; while (rs.next() && (count++ < 5) ) { QuoteDataBean quoteData = getQuoteDataFromResultSet(rs); topLosersData.add(quoteData); } stmt.close(); stmt = getStatement(conn, "select * from quoteejb q where q.symbol like 's:1__' order by q.change1 DESC", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); rs = stmt.executeQuery(); count = 0; while (rs.next() && (count++ < 5) ) { QuoteDataBean quoteData = getQuoteDataFromResultSet(rs); topGainersData.add(quoteData); } /* rs.last(); count = 0; while (rs.previous() && (count++ < 5) ) { QuoteDataBean quoteData = getQuoteDataFromResultSet(rs); topGainersData.add(quoteData); }*/ stmt.close(); stmt = getStatement(conn, getTSIASQL); rs = stmt.executeQuery(); BigDecimal TSIA=ZERO; if (!rs.next() ) Log.error("TradeDirect:getMarketSummary -- error w/ getTSIASQL -- no results"); else TSIA = rs.getBigDecimal("TSIA"); stmt.close(); stmt = getStatement(conn, getOpenTSIASQL); rs = stmt.executeQuery(); BigDecimal openTSIA = ZERO; if (!rs.next() ) Log.error("TradeDirect:getMarketSummary -- error w/ getOpenTSIASQL -- no results"); else openTSIA = rs.getBigDecimal("openTSIA"); stmt.close(); stmt = getStatement(conn, getTSIATotalVolumeSQL); rs = stmt.executeQuery(); double volume=0.0; if (!rs.next() ) Log.error("TradeDirect:getMarketSummary -- error w/ getTSIATotalVolumeSQL -- no results"); else volume = rs.getDouble("totalVolume"); stmt.close(); commit(conn); marketSummaryData = new MarketSummaryDataBean(TSIA, openTSIA, volume, topGainersData, topLosersData); } catch (Exception e) { Log.error("TradeDirect:login -- error logging in user", e); rollBack(conn, e); } finally { releaseConn(conn); } return marketSummaryData; } /** * @see TradeServices#buy(String, String, double) */ public OrderDataBean buy(String userID, String symbol, double quantity, int orderProcessingMode) throws Exception { Connection conn=null; OrderDataBean orderData = null; UserTransaction txn = null; /* * total = (quantity * purchasePrice) + orderFee */ BigDecimal total; try { if (Log.doTrace()) Log.trace("TradeDirect:buy", userID, symbol, new Double(quantity)); if ( orderProcessingMode == TradeConfig.ASYNCH_2PHASE ) { if ( Log.doTrace() ) Log.trace("TradeDirect:buy create/begin global transaction"); //FUTURE the UserTransaction be looked up once txn = (javax.transaction.UserTransaction) context.lookup("java:comp/UserTransaction"); txn.begin(); setInGlobalTxn(true); } conn = getConn(); AccountDataBean accountData = getAccountData(conn, userID); QuoteDataBean quoteData = getQuoteData(conn, symbol); HoldingDataBean holdingData = null; // the buy operation will create the holding orderData = createOrder(conn, accountData, quoteData, holdingData, "buy", quantity); //Update -- account should be credited during completeOrder BigDecimal price = quoteData.getPrice(); BigDecimal orderFee = orderData.getOrderFee(); total = (new BigDecimal(quantity).multiply(price)).add(orderFee); // subtract total from account balance creditAccountBalance(conn, accountData, total.negate()); try { if (orderProcessingMode == TradeConfig.SYNCH) completeOrder(conn, orderData.getOrderID()); else if (orderProcessingMode == TradeConfig.ASYNCH) queueOrder(orderData.getOrderID(), false); // 1-phase commit else //TradeConfig.ASYNC_2PHASE queueOrder(orderData.getOrderID(), true); // 2-phase commit } catch (JMSException je) { Log.error("TradeBean:buy("+userID+","+symbol+","+quantity+") --> failed to queueOrder", je); /* On exception - cancel the order */ cancelOrder(conn, orderData.getOrderID()); } if (txn != null) { if ( Log.doTrace() ) Log.trace("TradeDirect:buy committing global transaction"); txn.commit(); setInGlobalTxn(false); } else commit(conn); } catch (Exception e) { Log.error("TradeDirect:buy error - rolling back", e); if ( getInGlobalTxn() ) txn.rollback(); else rollBack(conn, e); } finally { releaseConn(conn); } return orderData; } /** * @see TradeServices#sell(String, Integer) */ public OrderDataBean sell(String userID, Integer holdingID, int orderProcessingMode) throws Exception { Connection conn=null; OrderDataBean orderData = null; UserTransaction txn = null; /* * total = (quantity * purchasePrice) + orderFee */ BigDecimal total; try { if (Log.doTrace()) Log.trace("TradeDirect:sell", userID, holdingID); if ( orderProcessingMode == TradeConfig.ASYNCH_2PHASE ) { if ( Log.doTrace() ) Log.trace("TradeDirect:sell create/begin global transaction"); //FUTURE the UserTransaction be looked up once txn = (javax.transaction.UserTransaction) context.lookup("java:comp/UserTransaction"); txn.begin(); setInGlobalTxn(true); } conn = getConn(); AccountDataBean accountData = getAccountData(conn, userID); HoldingDataBean holdingData = getHoldingData(conn, holdingID.intValue() ); QuoteDataBean quoteData = null; if ( holdingData != null) quoteData = getQuoteData(conn, holdingData.getQuoteID()); if ( (accountData==null) || (holdingData==null) || (quoteData==null) ) { String error = "TradeDirect:sell -- error selling stock -- unable to find: \n\taccount=" +accountData + "\n\tholding=" + holdingData + "\n\tquote="+quoteData + "\nfor user: " + userID + " and holdingID: " + holdingID; Log.error(error); if ( getInGlobalTxn() ) txn.rollback(); else rollBack(conn, new Exception(error)); return orderData; } double quantity = holdingData.getQuantity(); orderData = createOrder(conn, accountData, quoteData, holdingData, "sell", quantity); // Set the holdingSymbol purchaseDate to selling to signify the sell is "inflight" updateHoldingStatus(conn, holdingData.getHoldingID(), holdingData.getQuoteID()); //UPDATE -- account should be credited during completeOrder BigDecimal price = quoteData.getPrice(); BigDecimal orderFee = orderData.getOrderFee(); total = (new BigDecimal(quantity).multiply(price)).subtract(orderFee); creditAccountBalance(conn, accountData, total); try { if (orderProcessingMode == TradeConfig.SYNCH) completeOrder(conn, orderData.getOrderID()); else if (orderProcessingMode == TradeConfig.ASYNCH) queueOrder(orderData.getOrderID(), false); // 1-phase commit else //TradeConfig.ASYNC_2PHASE queueOrder(orderData.getOrderID(), true); // 2-phase commit } catch (JMSException je) { Log.error("TradeBean:sell("+userID+","+holdingID+") --> failed to queueOrder", je); /* On exception - cancel the order */ cancelOrder(conn, orderData.getOrderID()); } if (txn != null) { if ( Log.doTrace() ) Log.trace("TradeDirect:sell committing global transaction"); txn.commit(); setInGlobalTxn(false); } else commit(conn); } catch (Exception e) { Log.error("TradeDirect:sell error", e); if ( getInGlobalTxn() ) txn.rollback(); else rollBack(conn, e); } finally { releaseConn(conn); } return orderData; } /** * @see TradeServices#queueOrder(Integer) */ public void queueOrder(Integer orderID, boolean twoPhase) throws Exception { if (Log.doTrace() ) Log.trace("TradeDirect:queueOrder", orderID); javax.jms.Connection conn = null; Session sess = null; try { conn = qConnFactory.createConnection(); sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = sess.createProducer(queue); TextMessage message = sess.createTextMessage(); String command= "neworder"; message.setStringProperty("command", command); message.setIntProperty("orderID", orderID.intValue()); message.setBooleanProperty("twoPhase", twoPhase); message.setBooleanProperty("direct", true); message.setLongProperty("publishTime", System.currentTimeMillis()); message.setText("neworder: orderID="+orderID + " runtimeMode=Direct twoPhase="+twoPhase); if (Log.doTrace()) Log.trace("TradeDirectBean:queueOrder Sending message: " + message.getText()); producer.send(message); sess.close(); } catch (Exception e) { throw e; // pass the exception back } finally { if (sess != null) sess.close(); } } /** * @see TradeServices#completeOrder(Integer) */ public OrderDataBean completeOrder(Integer orderID, boolean twoPhase) throws Exception { OrderDataBean orderData = null; Connection conn=null; if (!twoPhase) { if (Log.doTrace()) Log.trace("TradeDirect:completeOrder -- completing order in 1-phase, calling tradeEJB to start new txn. orderID="+orderID); return tradeEJB.completeOrderOnePhaseDirect(orderID); } try //twoPhase { if (Log.doTrace()) Log.trace("TradeDirect:completeOrder", orderID); setInGlobalTxn(twoPhase); conn = getConn(); orderData = completeOrder(conn, orderID); commit(conn); } catch (Exception e) { Log.error("TradeDirect:completeOrder -- error completing order", e); rollBack(conn, e); cancelOrder(orderID, twoPhase); } finally { releaseConn(conn); } return orderData; } public OrderDataBean completeOrderOnePhase(Integer orderID) throws Exception { OrderDataBean orderData = null; Connection conn=null; try { if (Log.doTrace()) Log.trace("TradeDirect:completeOrderOnePhase", orderID); setInGlobalTxn(false); conn = getConn(); orderData = completeOrder(conn, orderID); commit(conn); } catch (Exception e) { Log.error("TradeDirect:completeOrderOnePhase -- error completing order", e); rollBack(conn, e); cancelOrder(orderID, false); } finally { releaseConn(conn); } return orderData; } private OrderDataBean completeOrder(Connection conn, Integer orderID) throws Exception { OrderDataBean orderData = null; if (Log.doTrace()) Log.trace("TradeDirect:completeOrderInternal", orderID); PreparedStatement stmt = getStatement(conn, getOrderSQL); stmt.setInt(1, orderID.intValue()); ResultSet rs = stmt.executeQuery(); if ( !rs.next() ) { Log.error("TradeDirect:completeOrder -- unable to find order: " + orderID); stmt.close(); return orderData; } orderData = getOrderDataFromResultSet(rs); String orderType = orderData.getOrderType(); String orderStatus = orderData.getOrderStatus(); //if (order.isCompleted()) if ( (orderStatus.compareToIgnoreCase("completed") == 0) || (orderStatus.compareToIgnoreCase("alertcompleted") == 0) || (orderStatus.compareToIgnoreCase("cancelled") == 0) ) throw new Exception("TradeDirect:completeOrder -- attempt to complete Order that is already completed"); int accountID = rs.getInt("account_accountID"); String quoteID = rs.getString("quote_symbol"); int holdingID = rs.getInt("holding_holdingID"); BigDecimal price = orderData.getPrice(); double quantity = orderData.getQuantity(); BigDecimal orderFee = orderData.getOrderFee(); //get the data for the account and quote //the holding will be created for a buy or extracted for a sell /* Use the AccountID and Quote Symbol from the Order AccountDataBean accountData = getAccountData(accountID, conn); QuoteDataBean quoteData = getQuoteData(conn, quoteID); */ String userID = getAccountProfileData(conn, new Integer(accountID)).getUserID(); HoldingDataBean holdingData = null; if (Log.doTrace()) Log.trace( "TradeDirect:completeOrder--> Completing Order " + orderData.getOrderID() + "\n\t Order info: " + orderData + "\n\t Account info: " + accountID + "\n\t Quote info: " + quoteID); //if (order.isBuy()) if ( orderType.compareToIgnoreCase("buy") == 0 ) { /* Complete a Buy operation * - create a new Holding for the Account * - deduct the Order cost from the Account balance */ holdingData = createHolding(conn, accountID, quoteID, quantity, price); updateOrderHolding(conn, orderID.intValue(), holdingData.getHoldingID().intValue()); } //if (order.isSell()) { if ( orderType.compareToIgnoreCase("sell") == 0 ) { /* Complete a Sell operation * - remove the Holding from the Account * - deposit the Order proceeds to the Account balance */ holdingData = getHoldingData(conn, holdingID); if ( holdingData == null ) Log.debug("TradeDirect:completeOrder:sell -- user: " + userID + " already sold holding: " + holdingID); else removeHolding(conn, holdingID, orderID.intValue()); } updateOrderStatus(conn, orderData.getOrderID(), "closed"); if (Log.doTrace()) Log.trace( "TradeDirect:completeOrder--> Completed Order " + orderData.getOrderID() + "\n\t Order info: " + orderData + "\n\t Account info: " + accountID + "\n\t Quote info: " + quoteID + "\n\t Holding info: " + holdingData); stmt.close(); commit(conn); //signify this order for user userID is complete TradeAction tradeAction = new TradeAction(this); tradeAction.orderCompleted(userID, orderID); return orderData; } /** * @see TradeServices#cancelOrder(Integer, boolean) */ public void cancelOrder(Integer orderID, boolean twoPhase) throws Exception { OrderDataBean orderData = null; Connection conn=null; try { if (Log.doTrace()) Log.trace("TradeDirect:cancelOrder", orderID); setInGlobalTxn(twoPhase); conn = getConn(); cancelOrder(conn, orderID); commit(conn); } catch (Exception e) { Log.error("TradeDirect:cancelOrder -- error cancelling order: "+orderID, e); rollBack(conn, e); } finally { releaseConn(conn); } } public void cancelOrderOnePhase(Integer orderID) throws Exception { OrderDataBean orderData = null; Connection conn=null; try { if (Log.doTrace()) Log.trace("TradeDirect:cancelOrderOnePhase", orderID); setInGlobalTxn(false); conn = getConn(); cancelOrder(conn, orderID); commit(conn); } catch (Exception e) { Log.error("TradeDirect:cancelOrderOnePhase -- error cancelling order: "+orderID, e); rollBack(conn, e); } finally { releaseConn(conn); } } private void cancelOrder(Connection conn, Integer orderID) throws Exception { updateOrderStatus(conn, orderID, "cancelled"); } public void orderCompleted(String userID, Integer orderID) throws Exception { throw new UnsupportedOperationException("TradeDirect:orderCompleted method not supported"); } private HoldingDataBean createHolding(Connection conn, int accountID, String symbol, double quantity, BigDecimal purchasePrice) throws Exception { HoldingDataBean holdingData = null; Timestamp purchaseDate = new Timestamp(System.currentTimeMillis()); PreparedStatement stmt = getStatement(conn, createHoldingSQL); Integer holdingID = KeySequenceDirect.getNextID(conn, "holding", getInGlobalTxn()); stmt.setInt(1, holdingID.intValue()); stmt.setTimestamp(2, purchaseDate); stmt.setBigDecimal(3, purchasePrice); stmt.setDouble(4, quantity); stmt.setString(5, symbol); stmt.setInt(6, accountID); int rowCount = stmt.executeUpdate(); stmt.close(); return getHoldingData(conn, holdingID.intValue()); } private void removeHolding(Connection conn, int holdingID, int orderID) throws Exception { PreparedStatement stmt = getStatement(conn, removeHoldingSQL); stmt.setInt(1, holdingID); int rowCount = stmt.executeUpdate(); stmt.close(); // set the HoldingID to NULL for the purchase and sell order now that // the holding as been removed stmt = getStatement(conn, removeHoldingFromOrderSQL); stmt.setInt(1, holdingID); rowCount = stmt.executeUpdate(); stmt.close(); } private OrderDataBean createOrder(Connection conn, AccountDataBean accountData, QuoteDataBean quoteData, HoldingDataBean holdingData, String orderType, double quantity) throws Exception { OrderDataBean orderData = null; Timestamp currentDate = new Timestamp(System.currentTimeMillis()); PreparedStatement stmt = getStatement(conn, createOrderSQL); Integer orderID = KeySequenceDirect.getNextID(conn, "order", getInGlobalTxn()); stmt.setInt(1, orderID.intValue()); stmt.setString(2, orderType); stmt.setString(3, "open"); stmt.setTimestamp(4, currentDate); stmt.setDouble(5, quantity); stmt.setBigDecimal(6, quoteData.getPrice().setScale(FinancialUtils.SCALE, FinancialUtils.ROUND)); stmt.setBigDecimal(7, TradeConfig.getOrderFee(orderType)); stmt.setInt(8, accountData.getAccountID().intValue()); if (holdingData == null ) stmt.setNull(9, java.sql.Types.INTEGER); else stmt.setInt(9, holdingData.getHoldingID().intValue()); stmt.setString(10, quoteData.getSymbol()); int rowCount = stmt.executeUpdate(); stmt.close(); return getOrderData(conn, orderID.intValue()); } /** * @see TradeServices#getOrders(String) */ public Collection getOrders(String userID) throws Exception { Collection orderDataBeans = new ArrayList(); Connection conn=null; try { if (Log.doTrace()) Log.trace("TradeDirect:getOrders", userID); conn = getConn(); PreparedStatement stmt = getStatement(conn, getOrdersByUserSQL); stmt.setString(1, userID); ResultSet rs = stmt.executeQuery(); //TODO: return top 5 orders for now -- next version will add a getAllOrders method // also need to get orders sorted by order id descending int i=0; while ( (rs.next()) && (i++ < 5) ) { OrderDataBean orderData = getOrderDataFromResultSet(rs); orderDataBeans.add(orderData); } stmt.close(); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getOrders -- error getting user orders", e); rollBack(conn, e); } finally { releaseConn(conn); } return orderDataBeans; } /** * @see TradeServices#getClosedOrders(String) */ public Collection getClosedOrders(String userID) throws Exception { Collection orderDataBeans = new ArrayList(); Connection conn=null; try { if (Log.doTrace()) Log.trace("TradeDirect:getClosedOrders", userID); conn = getConn(); PreparedStatement stmt = getStatement(conn, getClosedOrdersSQL); stmt.setString(1, userID); ResultSet rs = stmt.executeQuery(); while ( rs.next() ) { OrderDataBean orderData = getOrderDataFromResultSet(rs); orderData.setOrderStatus("completed"); updateOrderStatus(conn, orderData.getOrderID(), orderData.getOrderStatus()); orderDataBeans.add(orderData); } stmt.close(); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getOrders -- error getting user orders", e); rollBack(conn, e); } finally { releaseConn(conn); } return orderDataBeans; } /** * @see TradeServices#createQuote(String, String, BigDecimal) */ public QuoteDataBean createQuote( String symbol, String companyName, BigDecimal price) throws Exception { QuoteDataBean quoteData = null; Connection conn=null; try { if (Log.doTrace()) Log.traceEnter("TradeDirect:createQuote"); price = price.setScale(FinancialUtils.SCALE, FinancialUtils.ROUND); double volume=0.0, change=0.0; conn = getConn(); PreparedStatement stmt = getStatement(conn, createQuoteSQL); stmt.setString(1, symbol); // symbol stmt.setString(2, companyName); // companyName stmt.setDouble(3, volume); // volume stmt.setBigDecimal(4, price); // price stmt.setBigDecimal(5, price); // open stmt.setBigDecimal(6, price); // low stmt.setBigDecimal(7, price); // high stmt.setDouble(8, change); // change stmt.executeUpdate(); stmt.close(); commit(conn); quoteData = new QuoteDataBean(symbol, companyName, volume, price, price, price, price, change); if (Log.doTrace()) Log.traceExit("TradeDirect:createQuote"); } catch (Exception e) { Log.error("TradeDirect:createQuote -- error creating quote", e); } finally { releaseConn(conn); } return quoteData; } /** * @see TradeServices#getQuote(String) */ public QuoteDataBean getQuote(String symbol) throws Exception { QuoteDataBean quoteData = null; Connection conn=null; UserTransaction txn = null; try { if (Log.doTrace()) Log.trace("TradeDirect:getQuote", symbol); conn = getConn(); quoteData = getQuote(conn, symbol); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getQuote -- error getting quote", e); rollBack(conn, e); } finally { releaseConn(conn); } return quoteData; } private QuoteDataBean getQuote(Connection conn, String symbol) throws Exception { QuoteDataBean quoteData = null; PreparedStatement stmt = getStatement(conn, getQuoteSQL); stmt.setString(1, symbol); // symbol ResultSet rs = stmt.executeQuery(); if ( !rs.next() ) Log.error("TradeDirect:getQuote -- failure no result.next() for symbol: " + symbol); else quoteData = getQuoteDataFromResultSet(rs); stmt.close(); return quoteData; } private QuoteDataBean getQuoteForUpdate(Connection conn, String symbol) throws Exception { QuoteDataBean quoteData = null; PreparedStatement stmt = getStatement(conn, getQuoteForUpdateSQL); stmt.setString(1, symbol); // symbol ResultSet rs = stmt.executeQuery(); if ( !rs.next() ) Log.error("TradeDirect:getQuote -- failure no result.next()"); else quoteData = getQuoteDataFromResultSet(rs); stmt.close(); return quoteData; } /** * @see TradeServices#getAllQuotes(String) */ public Collection getAllQuotes() throws Exception { Collection quotes = new ArrayList(); QuoteDataBean quoteData = null; Connection conn = null; try { conn = getConn(); PreparedStatement stmt = getStatement(conn, getAllQuotesSQL); ResultSet rs = stmt.executeQuery(); while (!rs.next()) { quoteData = getQuoteDataFromResultSet(rs); quotes.add(quoteData); } stmt.close(); } catch (Exception e) { Log.error("TradeDirect:getAllQuotes", e); rollBack(conn, e); } finally { releaseConn(conn); } return quotes; } /** * @see TradeServices#getHoldings(String) */ public Collection getHoldings(String userID) throws Exception { Collection holdingDataBeans = new ArrayList(); Connection conn=null; try { if (Log.doTrace()) Log.trace("TradeDirect:getHoldings", userID); conn = getConn(); PreparedStatement stmt = getStatement(conn, getHoldingsForUserSQL); stmt.setString(1, userID); ResultSet rs = stmt.executeQuery(); while ( rs.next() ) { HoldingDataBean holdingData = getHoldingDataFromResultSet(rs); holdingDataBeans.add(holdingData); } stmt.close(); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getHoldings -- error getting user holings", e); rollBack(conn, e); } finally { releaseConn(conn); } return holdingDataBeans; } /** * @see TradeServices#getHolding(Integer) */ public HoldingDataBean getHolding(Integer holdingID) throws Exception { HoldingDataBean holdingData = null; Connection conn=null; try { if (Log.doTrace()) Log.trace("TradeDirect:getHolding", holdingID); conn = getConn(); holdingData = getHoldingData(holdingID.intValue()); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getHolding -- error getting holding " + holdingID + "", e); rollBack(conn, e); } finally { releaseConn(conn); } return holdingData; } /** * @see TradeServices#getAccountData(String) */ public AccountDataBean getAccountData(String userID) throws RemoteException { try{ AccountDataBean accountData = null; Connection conn=null; try { if (Log.doTrace()) Log.trace("TradeDirect:getAccountData", userID); conn = getConn(); accountData = getAccountData(conn, userID); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getAccountData -- error getting account data", e); rollBack(conn, e); } finally { releaseConn(conn); } return accountData; }catch (Exception e){ throw new RemoteException(e.getMessage(),e); } } private AccountDataBean getAccountData(Connection conn, String userID) throws Exception { PreparedStatement stmt = getStatement(conn, getAccountForUserSQL); stmt.setString(1, userID); ResultSet rs = stmt.executeQuery(); AccountDataBean accountData = getAccountDataFromResultSet(rs); stmt.close(); return accountData; } private AccountDataBean getAccountDataForUpdate(Connection conn, String userID) throws Exception { PreparedStatement stmt = getStatement(conn, getAccountForUserForUpdateSQL); stmt.setString(1, userID); ResultSet rs = stmt.executeQuery(); AccountDataBean accountData = getAccountDataFromResultSet(rs); stmt.close(); return accountData; } /** * @see TradeServices#getAccountData(String) */ public AccountDataBean getAccountData(int accountID) throws Exception { AccountDataBean accountData = null; Connection conn=null; try { if (Log.doTrace()) Log.trace("TradeDirect:getAccountData", new Integer(accountID)); conn = getConn(); accountData = getAccountData(accountID, conn); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getAccountData -- error getting account data", e); rollBack(conn, e); } finally { releaseConn(conn); } return accountData; } private AccountDataBean getAccountData(int accountID, Connection conn) throws Exception { PreparedStatement stmt = getStatement(conn, getAccountSQL); stmt.setInt(1, accountID); ResultSet rs = stmt.executeQuery(); AccountDataBean accountData = getAccountDataFromResultSet(rs); stmt.close(); return accountData; } private AccountDataBean getAccountDataForUpdate(int accountID, Connection conn) throws Exception { PreparedStatement stmt = getStatement(conn, getAccountForUpdateSQL); stmt.setInt(1, accountID); ResultSet rs = stmt.executeQuery(); AccountDataBean accountData = getAccountDataFromResultSet(rs); stmt.close(); return accountData; } private QuoteDataBean getQuoteData(String symbol) throws Exception { QuoteDataBean quoteData = null; Connection conn=null; try { conn = getConn(); quoteData = getQuoteData(conn, symbol); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getQuoteData -- error getting data", e); rollBack(conn, e); } finally { releaseConn(conn); } return quoteData; } private QuoteDataBean getQuoteData(Connection conn, String symbol) throws Exception { QuoteDataBean quoteData = null; PreparedStatement stmt = getStatement(conn, getQuoteSQL); stmt.setString(1, symbol); ResultSet rs = stmt.executeQuery(); if (!rs.next()) Log.error("TradeDirect:getQuoteData -- could not find quote for symbol="+symbol); else quoteData = getQuoteDataFromResultSet(rs); stmt.close(); return quoteData; } private HoldingDataBean getHoldingData(int holdingID) throws Exception { HoldingDataBean holdingData = null; Connection conn=null; try { conn = getConn(); holdingData = getHoldingData(conn, holdingID); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getHoldingData -- error getting data", e); rollBack(conn, e); } finally { releaseConn(conn); } return holdingData; } private HoldingDataBean getHoldingData(Connection conn, int holdingID) throws Exception { HoldingDataBean holdingData = null; PreparedStatement stmt = getStatement(conn, getHoldingSQL); stmt.setInt(1, holdingID); ResultSet rs = stmt.executeQuery(); if (!rs.next()) Log.error("TradeDirect:getHoldingData -- no results -- holdingID="+holdingID); else holdingData = getHoldingDataFromResultSet(rs); stmt.close(); return holdingData; } private OrderDataBean getOrderData(int orderID) throws Exception { OrderDataBean orderData = null; Connection conn=null; try { conn = getConn(); orderData = getOrderData(conn, orderID); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getOrderData -- error getting data", e); rollBack(conn, e); } finally { releaseConn(conn); } return orderData; } private OrderDataBean getOrderData(Connection conn, int orderID) throws Exception { OrderDataBean orderData = null; if (Log.doTrace()) Log.trace("TradeDirect:getOrderData(conn, " + orderID + ")"); PreparedStatement stmt = getStatement(conn, getOrderSQL); stmt.setInt(1, orderID); ResultSet rs = stmt.executeQuery(); if (!rs.next()) Log.error("TradeDirect:getOrderData -- no results for orderID:" + orderID); else orderData = getOrderDataFromResultSet(rs); stmt.close(); return orderData; } /** * @see TradeServices#getAccountProfileData(String) */ public AccountProfileDataBean getAccountProfileData(String userID) throws Exception { AccountProfileDataBean accountProfileData = null; Connection conn=null; try { if (Log.doTrace()) Log.trace("TradeDirect:getAccountProfileData", userID); conn = getConn(); accountProfileData = getAccountProfileData(conn, userID); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getAccountProfileData -- error getting profile data", e); rollBack(conn, e); } finally { releaseConn(conn); } return accountProfileData; } private AccountProfileDataBean getAccountProfileData(Connection conn, String userID) throws Exception { PreparedStatement stmt = getStatement(conn, getAccountProfileSQL); stmt.setString(1, userID); ResultSet rs = stmt.executeQuery(); AccountProfileDataBean accountProfileData = getAccountProfileDataFromResultSet(rs); stmt.close(); return accountProfileData; } private AccountProfileDataBean getAccountProfileData(Integer accountID) throws Exception { AccountProfileDataBean accountProfileData = null; Connection conn=null; try { if (Log.doTrace()) Log.trace("TradeDirect:getAccountProfileData", accountID); conn = getConn(); accountProfileData = getAccountProfileData(conn, accountID); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getAccountProfileData -- error getting profile data", e); rollBack(conn, e); } finally { releaseConn(conn); } return accountProfileData; } private AccountProfileDataBean getAccountProfileData(Connection conn, Integer accountID) throws Exception { PreparedStatement stmt = getStatement(conn, getAccountProfileForAccountSQL); stmt.setInt(1, accountID.intValue()); ResultSet rs = stmt.executeQuery(); AccountProfileDataBean accountProfileData = getAccountProfileDataFromResultSet(rs); stmt.close(); return accountProfileData; } /** * @see TradeServices#updateAccountProfile(AccountProfileDataBean) */ public AccountProfileDataBean updateAccountProfile(AccountProfileDataBean profileData) throws Exception { AccountProfileDataBean accountProfileData = null; Connection conn=null; try { if (Log.doTrace()) Log.trace("TradeDirect:updateAccountProfileData", profileData.getUserID()); conn = getConn(); updateAccountProfile(conn, profileData); accountProfileData = getAccountProfileData(conn, profileData.getUserID()); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getAccountProfileData -- error getting profile data", e); rollBack(conn, e); } finally { releaseConn(conn); } return accountProfileData; } private void creditAccountBalance(Connection conn, AccountDataBean accountData, BigDecimal credit) throws Exception { PreparedStatement stmt = getStatement(conn, creditAccountBalanceSQL); stmt.setBigDecimal(1, credit); stmt.setInt(2, accountData.getAccountID().intValue()); int count = stmt.executeUpdate(); stmt.close(); } // Set Timestamp to zero to denote sell is inflight // UPDATE -- could add a "status" attribute to holding private void updateHoldingStatus(Connection conn, Integer holdingID, String symbol) throws Exception { Timestamp ts = new Timestamp(0); PreparedStatement stmt = getStatement(conn, "update holdingejb set purchasedate= ? where holdingid = ?"); stmt.setTimestamp(1, ts); stmt.setInt(2, holdingID.intValue()); int count = stmt.executeUpdate(); stmt.close(); } private void updateOrderStatus(Connection conn, Integer orderID, String status) throws Exception { PreparedStatement stmt = getStatement(conn, updateOrderStatusSQL); stmt.setString(1, status); stmt.setTimestamp(2, new Timestamp(System.currentTimeMillis())); stmt.setInt(3, orderID.intValue()); int count = stmt.executeUpdate(); stmt.close(); } private void updateOrderHolding(Connection conn, int orderID, int holdingID) throws Exception { PreparedStatement stmt = getStatement(conn, updateOrderHoldingSQL); stmt.setInt(1, holdingID); stmt.setInt(2, orderID); int count = stmt.executeUpdate(); stmt.close(); } private void updateAccountProfile(Connection conn, AccountProfileDataBean profileData) throws Exception { PreparedStatement stmt = getStatement(conn, updateAccountProfileSQL); stmt.setString(1, profileData.getPassword()); stmt.setString(2, profileData.getFullName()); stmt.setString(3, profileData.getAddress()); stmt.setString(4, profileData.getEmail()); stmt.setString(5, profileData.getCreditCard()); stmt.setString(6, profileData.getUserID()); int count = stmt.executeUpdate(); stmt.close(); } private void updateQuoteVolume(Connection conn, QuoteDataBean quoteData, double quantity) throws Exception { PreparedStatement stmt = getStatement(conn, updateQuoteVolumeSQL); stmt.setDouble(1, quantity); stmt.setString(2, quoteData.getSymbol()); int count = stmt.executeUpdate(); stmt.close(); } public QuoteDataBean updateQuotePriceVolume(String symbol, BigDecimal changeFactor, double sharesTraded) throws Exception { return updateQuotePriceVolumeInt(symbol, changeFactor, sharesTraded, publishQuotePriceChange); } /** * Update a quote's price and volume * @param symbol The PK of the quote * @param changeFactor the percent to change the old price by (between 50% and 150%) * @param sharedTraded the ammount to add to the current volume * @param publishQuotePriceChange used by the PingJDBCWrite Primitive to ensure no JMS is used, should * be true for all normal calls to this API */ public QuoteDataBean updateQuotePriceVolumeInt(String symbol, BigDecimal changeFactor, double sharesTraded, boolean publishQuotePriceChange) throws Exception { if ( TradeConfig.getUpdateQuotePrices() == false ) return new QuoteDataBean(); QuoteDataBean quoteData = null; Connection conn=null; UserTransaction txn = null; try { if (Log.doTrace()) Log.trace("TradeDirect:updateQuotePriceVolume", symbol, changeFactor, new Double(sharesTraded)); conn = getConn(); quoteData = getQuoteForUpdate(conn, symbol); BigDecimal oldPrice = quoteData.getPrice(); double newVolume = quoteData.getVolume() + sharesTraded; if (oldPrice.equals(TradeConfig.PENNY_STOCK_PRICE)) { changeFactor = TradeConfig.PENNY_STOCK_RECOVERY_MIRACLE_MULTIPLIER; } BigDecimal newPrice = changeFactor.multiply(oldPrice).setScale(2, BigDecimal.ROUND_HALF_UP); updateQuotePriceVolume(conn, quoteData.getSymbol(), newPrice, newVolume); quoteData = getQuote(conn, symbol); commit(conn); if (publishQuotePriceChange) { publishQuotePriceChange(quoteData, oldPrice, changeFactor, sharesTraded); } } catch (Exception e) { Log.error("TradeDirect:updateQuotePriceVolume -- error updating quote price/volume for symbol:" + symbol); rollBack(conn, e); throw e; } finally { releaseConn(conn); } return quoteData; } private void updateQuotePriceVolume(Connection conn, String symbol, BigDecimal newPrice, double newVolume) throws Exception { PreparedStatement stmt = getStatement(conn, updateQuotePriceVolumeSQL); stmt.setBigDecimal(1, newPrice); stmt.setBigDecimal(2, newPrice); stmt.setDouble(3, newVolume); stmt.setString(4, symbol); int count = stmt.executeUpdate(); stmt.close(); } private void publishQuotePriceChange(QuoteDataBean quoteData, BigDecimal oldPrice, BigDecimal changeFactor, double sharesTraded) throws Exception { if (Log.doTrace()) Log.trace("TradeDirect:publishQuotePrice PUBLISHING to MDB quoteData = " + quoteData); javax.jms.Connection conn = null; Session sess = null; try { conn = tConnFactory.createConnection(); sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = sess.createProducer(streamerTopic); TextMessage message = sess.createTextMessage(); String command = "updateQuote"; message.setStringProperty("command", command); message.setStringProperty("symbol", quoteData.getSymbol() ); message.setStringProperty("company", quoteData.getCompanyName() ); message.setStringProperty("price", quoteData.getPrice().toString()); message.setStringProperty("oldPrice",oldPrice.toString()); message.setStringProperty("open", quoteData.getOpen().toString()); message.setStringProperty("low", quoteData.getLow().toString()); message.setStringProperty("high", quoteData.getHigh().toString()); message.setDoubleProperty("volume", quoteData.getVolume()); message.setStringProperty("changeFactor", changeFactor.toString()); message.setDoubleProperty("sharesTraded", sharesTraded); message.setLongProperty("publishTime", System.currentTimeMillis()); message.setText("Update Stock price for " + quoteData.getSymbol() + " old price = " + oldPrice + " new price = " + quoteData.getPrice()); producer.send(message); } catch (Exception e) { throw e; //pass exception back } finally { if (conn != null) conn.close(); if (sess != null) sess.close(); } } /** * @see TradeServices#login(String, String) */ public AccountDataBean login(String userID, String password) throws Exception { AccountDataBean accountData = null; Connection conn=null; try { if (Log.doTrace()) Log.trace("TradeDirect:login", userID, password); conn = getConn(); PreparedStatement stmt = getStatement(conn, getAccountProfileSQL); stmt.setString(1, userID); ResultSet rs = stmt.executeQuery(); if ( !rs.next() ) { Log.error("TradeDirect:login -- failure to find account for" + userID); throw new javax.ejb.FinderException("Cannot find account for" + userID); } String pw = rs.getString("password"); stmt.close(); if ( (pw==null) || (pw.equals(password) == false) ) { String error = "TradeDirect:Login failure for user: " + userID + "\n\tIncorrect password-->" + userID + ":" + password; Log.error(error); throw new Exception(error); } stmt = getStatement(conn, loginSQL); stmt.setTimestamp(1, new Timestamp(System.currentTimeMillis())); stmt.setString(2, userID); int rows = stmt.executeUpdate(); //?assert rows==1? stmt = getStatement(conn, getAccountForUserSQL); stmt.setString(1, userID); rs = stmt.executeQuery(); accountData = getAccountDataFromResultSet(rs); stmt.close(); commit(conn); } catch (Exception e) { Log.error("TradeDirect:login -- error logging in user", e); rollBack(conn, e); } finally { releaseConn(conn); } return accountData; /* setLastLogin( new Timestamp(System.currentTimeMillis()) ); setLoginCount( getLoginCount() + 1 ); */ } /** * @see TradeServices#logout(String) */ public void logout(String userID) throws Exception { if (Log.doTrace()) Log.trace("TradeDirect:logout", userID); Connection conn=null; try { conn = getConn(); PreparedStatement stmt = getStatement(conn, logoutSQL); stmt.setString(1, userID); stmt.executeUpdate(); stmt.close(); commit(conn); } catch (Exception e) { Log.error("TradeDirect:logout -- error logging out user", e); rollBack(conn, e); } finally { releaseConn(conn); } } /** * @see TradeServices#register(String, String, String, String, String, String, BigDecimal, boolean) */ public AccountDataBean register( String userID, String password, String fullname, String address, String email, String creditcard, BigDecimal openBalance) throws Exception { AccountDataBean accountData = null; Connection conn=null; try { if (Log.doTrace()) Log.traceEnter("TradeDirect:register"); conn = getConn(); PreparedStatement stmt = getStatement(conn, createAccountSQL); Integer accountID = KeySequenceDirect.getNextID(conn, "account", getInGlobalTxn()); BigDecimal balance = openBalance; Timestamp creationDate = new Timestamp(System.currentTimeMillis()); Timestamp lastLogin = creationDate; int loginCount = 0; int logoutCount = 0; stmt.setInt(1, accountID.intValue()); stmt.setTimestamp(2, creationDate); stmt.setBigDecimal(3, openBalance); stmt.setBigDecimal(4, balance); stmt.setTimestamp(5, lastLogin); stmt.setInt(6, loginCount); stmt.setInt(7, logoutCount); stmt.setString(8, userID); stmt.executeUpdate(); stmt.close(); stmt = getStatement(conn, createAccountProfileSQL); stmt.setString(1, userID); stmt.setString(2, password); stmt.setString(3, fullname); stmt.setString(4, address); stmt.setString(5, email); stmt.setString(6, creditcard); stmt.executeUpdate(); stmt.close(); commit(conn); accountData = new AccountDataBean(accountID, loginCount, logoutCount, lastLogin, creationDate, balance, openBalance, userID); if (Log.doTrace()) Log.traceExit("TradeDirect:register"); } catch (Exception e) { Log.error("TradeDirect:register -- error registering new user", e); } finally { releaseConn(conn); } return accountData; } private AccountDataBean getAccountDataFromResultSet(ResultSet rs) throws Exception { AccountDataBean accountData = null; if (!rs.next() ) Log.error("TradeDirect:getAccountDataFromResultSet -- cannot find account data"); else accountData = new AccountDataBean( new Integer(rs.getInt("accountID")), rs.getInt("loginCount"), rs.getInt("logoutCount"), rs.getTimestamp("lastLogin"), rs.getTimestamp("creationDate"), rs.getBigDecimal("balance"), rs.getBigDecimal("openBalance"), rs.getString("profile_userID") ); return accountData; } private AccountProfileDataBean getAccountProfileDataFromResultSet(ResultSet rs) throws Exception { AccountProfileDataBean accountProfileData = null; if (!rs.next() ) Log.error("TradeDirect:getAccountProfileDataFromResultSet -- cannot find accountprofile data"); else accountProfileData = new AccountProfileDataBean( rs.getString("userID"), rs.getString("password"), rs.getString("fullName"), rs.getString("address"), rs.getString("email"), rs.getString("creditCard") ); return accountProfileData; } private HoldingDataBean getHoldingDataFromResultSet(ResultSet rs) throws Exception { HoldingDataBean holdingData = null; holdingData = new HoldingDataBean( new Integer(rs.getInt("holdingID")), rs.getDouble("quantity"), rs.getBigDecimal("purchasePrice"), rs.getTimestamp("purchaseDate"), rs.getString("quote_symbol") ); return holdingData; } private QuoteDataBean getQuoteDataFromResultSet(ResultSet rs) throws Exception { QuoteDataBean quoteData = null; quoteData = new QuoteDataBean( rs.getString("symbol"), rs.getString("companyName"), rs.getDouble("volume"), rs.getBigDecimal("price"), rs.getBigDecimal("open1"), rs.getBigDecimal("low"), rs.getBigDecimal("high"), rs.getDouble("change1") ); return quoteData; } private OrderDataBean getOrderDataFromResultSet(ResultSet rs) throws Exception { OrderDataBean orderData = null; orderData = new OrderDataBean( new Integer(rs.getInt("orderID")), rs.getString("orderType"), rs.getString("orderStatus"), rs.getTimestamp("openDate"), rs.getTimestamp("completionDate"), rs.getDouble("quantity"), rs.getBigDecimal("price"), rs.getBigDecimal("orderFee"), rs.getString("quote_symbol") ); return orderData; } public RunStatsDataBean resetTrade(boolean deleteAll) throws Exception { //Clear MDB Statistics MDBStats.getInstance().reset(); // Reset Trade RunStatsDataBean runStatsData = new RunStatsDataBean(); Connection conn=null; UserTransaction txn = null; try { if (Log.doTrace()) Log.traceEnter("TradeDirect:resetTrade deleteAll rows=" + deleteAll); conn = getConn(); PreparedStatement stmt=null; ResultSet rs = null; if (deleteAll) { try { stmt = getStatement(conn, "delete from quoteejb"); stmt.executeUpdate(); stmt.close(); stmt = getStatement(conn, "delete from accountejb"); stmt.executeUpdate(); stmt.close(); stmt = getStatement(conn, "delete from accountprofileejb"); stmt.executeUpdate(); stmt.close(); stmt = getStatement(conn, "delete from holdingejb"); stmt.executeUpdate(); stmt.close(); stmt = getStatement(conn, "delete from orderejb"); stmt.executeUpdate(); stmt.close(); // FUTURE: - DuplicateKeyException - For now, don't start at // zero as KeySequenceDirect and KeySequenceBean will still give out // the cached Block and then notice this change. Better solution is // to signal both classes to drop their cached blocks //stmt = getStatement(conn, "delete from keygenejb"); //stmt.executeUpdate(); //stmt.close(); commit(conn); } catch (Exception e) { Log.error(e,"TradeDirect:resetTrade(deleteAll) -- Error deleting Trade users and stock from the Trade database"); } return runStatsData; } stmt = getStatement(conn, "delete from holdingejb where holdingejb.account_accountid is null"); int x = stmt.executeUpdate(); stmt.close(); //Count and Delete newly registered users (users w/ id that start "ru:%": stmt = getStatement(conn, "delete from accountprofileejb where userid like 'ru:%'"); int rowCount = stmt.executeUpdate(); stmt.close(); stmt = getStatement(conn, "delete from orderejb where account_accountid in (select accountid from accountejb a where a.profile_userid like 'ru:%')"); rowCount = stmt.executeUpdate(); stmt.close(); stmt = getStatement(conn, "delete from holdingejb where account_accountid in (select accountid from accountejb a where a.profile_userid like 'ru:%')"); rowCount = stmt.executeUpdate(); stmt.close(); stmt = getStatement(conn, "delete from accountejb where profile_userid like 'ru:%'"); int newUserCount = stmt.executeUpdate(); runStatsData.setNewUserCount(newUserCount); stmt.close(); //Count of trade users stmt = getStatement(conn, "select count(accountid) as \"tradeUserCount\" from accountejb a where a.profile_userid like 'uid:%'"); rs = stmt.executeQuery(); rs.next(); int tradeUserCount = rs.getInt("tradeUserCount"); runStatsData.setTradeUserCount(tradeUserCount); stmt.close(); rs.close(); //Count of trade stocks stmt = getStatement(conn, "select count(symbol) as \"tradeStockCount\" from quoteejb a where a.symbol like 's:%'"); rs = stmt.executeQuery(); rs.next(); int tradeStockCount = rs.getInt("tradeStockCount"); runStatsData.setTradeStockCount(tradeStockCount); stmt.close(); //Count of trade users login, logout stmt = getStatement(conn, "select sum(loginCount) as \"sumLoginCount\", sum(logoutCount) as \"sumLogoutCount\" from accountejb a where a.profile_userID like 'uid:%'"); rs = stmt.executeQuery(); rs.next(); int sumLoginCount = rs.getInt("sumLoginCount"); int sumLogoutCount = rs.getInt("sumLogoutCount"); runStatsData.setSumLoginCount(sumLoginCount); runStatsData.setSumLogoutCount(sumLogoutCount); stmt.close(); rs.close(); //Update logoutcount and loginCount back to zero stmt = getStatement(conn, "update accountejb set logoutCount=0,loginCount=0 where profile_userID like 'uid:%'"); rowCount = stmt.executeUpdate(); stmt.close(); //count holdings for trade users stmt = getStatement(conn, "select count(holdingid) as \"holdingCount\" from holdingejb h where h.account_accountid in " + "(select accountid from accountejb a where a.profile_userid like 'uid:%')"); rs = stmt.executeQuery(); rs.next(); int holdingCount = rs.getInt("holdingCount"); runStatsData.setHoldingCount(holdingCount); stmt.close(); rs.close(); //count orders for trade users stmt = getStatement(conn, "select count(orderid) as \"orderCount\" from orderejb o where o.account_accountid in " + "(select accountid from accountejb a where a.profile_userid like 'uid:%')"); rs = stmt.executeQuery(); rs.next(); int orderCount = rs.getInt("orderCount"); runStatsData.setOrderCount(orderCount); stmt.close(); rs.close(); //count orders by type for trade users stmt = getStatement(conn, "select count(orderid) \"buyOrderCount\"from orderejb o where (o.account_accountid in " + "(select accountid from accountejb a where a.profile_userid like 'uid:%')) AND " + " (o.orderType='buy')"); rs = stmt.executeQuery(); rs.next(); int buyOrderCount = rs.getInt("buyOrderCount"); runStatsData.setBuyOrderCount(buyOrderCount); stmt.close(); rs.close(); //count orders by type for trade users stmt = getStatement(conn, "select count(orderid) \"sellOrderCount\"from orderejb o where (o.account_accountid in " + "(select accountid from accountejb a where a.profile_userid like 'uid:%')) AND " + " (o.orderType='sell')"); rs = stmt.executeQuery(); rs.next(); int sellOrderCount = rs.getInt("sellOrderCount"); runStatsData.setSellOrderCount(sellOrderCount); stmt.close(); rs.close(); //Delete cancelled orders stmt = getStatement(conn, "delete from orderejb where orderStatus='cancelled'"); int cancelledOrderCount = stmt.executeUpdate(); runStatsData.setCancelledOrderCount(cancelledOrderCount); stmt.close(); rs.close(); //count open orders by type for trade users stmt = getStatement(conn, "select count(orderid) \"openOrderCount\"from orderejb o where (o.account_accountid in " + "(select accountid from accountejb a where a.profile_userid like 'uid:%')) AND " + " (o.orderStatus='open')"); rs = stmt.executeQuery(); rs.next(); int openOrderCount = rs.getInt("openOrderCount"); runStatsData.setOpenOrderCount(openOrderCount); stmt.close(); rs.close(); //Delete orders for holding which have been purchased and sold stmt = getStatement(conn, "delete from orderejb where holding_holdingid is null"); int deletedOrderCount = stmt.executeUpdate(); runStatsData.setDeletedOrderCount(deletedOrderCount); stmt.close(); rs.close(); commit(conn); System.out.println("TradeDirect:reset Run stats data\n\n" + runStatsData); } catch (Exception e) { Log.error(e, "Failed to reset Trade"); rollBack(conn, e); throw e; } finally { releaseConn(conn); } return runStatsData; } private void releaseConn(Connection conn) throws Exception { try { if ( conn!= null ) { conn.close(); if (Log.doTrace()) { synchronized(lock) { connCount--; } Log.trace("TradeDirect:releaseConn -- connection closed, connCount="+connCount); } } } catch (Exception e) { Log.error("TradeDirect:releaseConnection -- failed to close connection", e); } } /* * Lookup the TradeData datasource * */ private void getDataSource() throws Exception { datasource = (DataSource) context.lookup(dsName); } /* * Allocate a new connection to the datasource * */ private static int connCount=0; private static Integer lock = new Integer(0); private Connection getConn() throws Exception { Connection conn = null; if ( datasource == null ) getDataSource(); conn = datasource.getConnection(); conn.setAutoCommit(false); if (Log.doTrace()) { synchronized(lock) { connCount++; } Log.trace("TradeDirect:getConn -- new connection allocated, IsolationLevel=" + conn.getTransactionIsolation() + " connectionCount = " + connCount); } return conn; } /* * Commit the provided connection if not under Global Transaction scope * - conn.commit() is not allowed in a global transaction. the txn manager will * perform the commit */ private void commit(Connection conn) throws Exception { if ( (getInGlobalTxn()==false) && (conn != null) ) conn.commit(); } /* * Rollback the statement for the given connection * */ private void rollBack(Connection conn, Exception e) throws Exception { Log.log("TradeDirect:rollBack -- rolling back conn due to previously caught exception -- inGlobalTxn=" + getInGlobalTxn()); if ( (getInGlobalTxn()==false) && (conn != null) ) conn.rollback(); else throw e; // Throw the exception // so the Global txn manager will rollBack } /* * Allocate a new prepared statment for this connection * */ private PreparedStatement getStatement(Connection conn, String sql) throws Exception { return conn.prepareStatement(sql); } private PreparedStatement getStatement(Connection conn, String sql, int type, int concurrency) throws Exception { return conn.prepareStatement(sql, type, concurrency ); } private static final String createQuoteSQL = "insert into quoteejb " + "( symbol, companyName, volume, price, open1, low, high, change1 ) " + "VALUES ( ? , ? , ? , ? , ? , ? , ? , ? )"; private static final String createAccountSQL = "insert into accountejb " + "( accountid, creationDate, openBalance, balance, lastLogin, loginCount, logoutCount, profile_userid) " + "VALUES ( ? , ? , ? , ? , ? , ? , ? , ? )"; private static final String createAccountProfileSQL = "insert into accountprofileejb " + "( userid, password, fullname, address, email, creditcard ) " + "VALUES ( ? , ? , ? , ? , ? , ? )"; private static final String createHoldingSQL = "insert into holdingejb " + "( holdingid, purchaseDate, purchasePrice, quantity, quote_symbol, account_accountid ) " + "VALUES ( ? , ? , ? , ? , ? , ? )"; private static final String createOrderSQL = "insert into orderejb " + "( orderid, ordertype, orderstatus, opendate, quantity, price, orderfee, account_accountid, holding_holdingid, quote_symbol) " + "VALUES ( ? , ? , ? , ? , ? , ? , ? , ? , ? , ?)"; private static final String removeHoldingSQL = "delete from holdingejb where holdingid = ?"; private static final String removeHoldingFromOrderSQL = "update orderejb set holding_holdingid=null where holding_holdingid = ?"; private final static String updateAccountProfileSQL = "update accountprofileejb set " + "password = ?, fullname = ?, address = ?, email = ?, creditcard = ? " + "where userid = (select profile_userid from accountejb a " + "where a.profile_userid=?)"; private final static String loginSQL= "update accountejb set lastLogin=?, logincount=logincount+1 " + "where profile_userid=?"; private static final String logoutSQL = "update accountejb set logoutcount=logoutcount+1 " + "where profile_userid=?"; private static final String getAccountSQL = "select * from accountejb a where a.accountid = ?"; private static final String getAccountForUpdateSQL = "select * from accountejb a where a.accountid = ? for update"; private final static String getAccountProfileSQL = "select * from accountprofileejb ap where ap.userid = " + "(select profile_userid from accountejb a where a.profile_userid=?)"; private final static String getAccountProfileForAccountSQL = "select * from accountprofileejb ap where ap.userid = " + "(select profile_userid from accountejb a where a.accountid=?)"; private static final String getAccountForUserSQL = "select * from accountejb a where a.profile_userid = " + "( select userid from accountprofileejb ap where ap.userid = ?)"; private static final String getAccountForUserForUpdateSQL = "select * from accountejb a where a.profile_userid = " + "( select userid from accountprofileejb ap where ap.userid = ?) for update"; private static final String getHoldingSQL = "select * from holdingejb h where h.holdingid = ?"; private static final String getHoldingsForUserSQL = "select * from holdingejb h where h.account_accountid = " + "(select a.accountid from accountejb a where a.profile_userid = ?)"; private static final String getOrderSQL = "select * from orderejb o where o.orderid = ?"; private static final String getOrdersByUserSQL = "select * from orderejb o where o.account_accountid = " + "(select a.accountid from accountejb a where a.profile_userid = ?)"; private static final String getClosedOrdersSQL = "select * from orderejb o " + "where o.orderstatus = 'closed' AND o.account_accountid = " + "(select a.accountid from accountejb a where a.profile_userid = ?)"; private static final String getQuoteSQL = "select * from quoteejb q where q.symbol=?"; private static final String getAllQuotesSQL = "select * from quoteejb q"; private static final String getQuoteForUpdateSQL = "select * from quoteejb q where q.symbol=? For Update"; private static final String getTSIAQuotesOrderByChangeSQL = "select * from quoteejb q " + "where q.symbol like 's:1__' order by q.change1"; private static final String getTSIASQL = "select SUM(price)/count(*) as TSIA from quoteejb q " + "where q.symbol like 's:1__'"; private static final String getOpenTSIASQL = "select SUM(open1)/count(*) as openTSIA from quoteejb q " + "where q.symbol like 's:1__'"; private static final String getTSIATotalVolumeSQL = "select SUM(volume) as totalVolume from quoteejb q " + "where q.symbol like 's:1__'"; private static final String creditAccountBalanceSQL = "update accountejb set " + "balance = balance + ? " + "where accountid = ?"; private static final String updateOrderStatusSQL = "update orderejb set " + "orderstatus = ?, completiondate = ? " + "where orderid = ?"; private static final String updateOrderHoldingSQL = "update orderejb set " + "holding_holdingID = ? " + "where orderid = ?"; private static final String updateQuoteVolumeSQL = "update quoteejb set " + "volume = volume + ? " + "where symbol = ?"; private static final String updateQuotePriceVolumeSQL = "update quoteejb set " + "price = ?, change1 = ? - open1, volume = ? " + "where symbol = ?"; private static boolean initialized = false; public static synchronized void init() { TradeHome tradeHome=null; if (initialized) return; if (Log.doTrace()) Log.trace("TradeDirect:init -- *** initializing"); try { if (Log.doTrace()) Log.trace("TradeDirect: init"); context = new InitialContext(); datasource = (DataSource) context.lookup(dsName); } catch (Exception e) { Log.error("TradeDirect:init -- error on JNDI lookups of DataSource -- TradeDirect will not work", e); return; } try { tradeHome = (TradeHome) ( javax.rmi.PortableRemoteObject.narrow( context.lookup("java:comp/env/ejb/Trade"), TradeHome.class)); } catch (Exception e) { Log.error("TradeDirect:init -- error on JNDI lookup of Trade Session Bean -- TradeDirect will not work", e); return; } try { qConnFactory = (ConnectionFactory) context.lookup("java:comp/env/jms/QueueConnectionFactory"); } catch (Exception e) { Log.error("TradeDirect:init Unable to locate QueueConnectionFactory.\n\t -- Asynchronous mode will not work correctly and Quote Price change publishing will be disabled"); publishQuotePriceChange = false; } try { queue = (Queue) context.lookup("java:comp/env/jms/TradeBrokerQueue"); } catch (Exception e) { Log.error("TradeDirect:init Unable to locate TradeBrokerQueue.\n\t -- Asynchronous mode will not work correctly and Quote Price change publishing will be disabled"); publishQuotePriceChange = false; } try { tConnFactory = (ConnectionFactory) context.lookup("java:comp/env/jms/TopicConnectionFactory"); } catch (Exception e) { Log.error("TradeDirect:init Unable to locate TopicConnectionFactory.\n\t -- Asynchronous mode will not work correctly and Quote Price change publishing will be disabled"); publishQuotePriceChange = false; } try { streamerTopic = (Topic) context.lookup("java:comp/env/jms/TradeStreamerTopic"); } catch (Exception e) { Log.error("TradeDirect:init Unable to locate TradeStreamerTopic.\n\t -- Asynchronous mode will not work correctly and Quote Price change publishing will be disabled"); publishQuotePriceChange = false; } try { tradeEJB = (Trade) tradeHome.create(); } catch (Exception e) { Log.error("TradeDirect:init -- error looking up TradeEJB -- Asynchronous 1-phase will not work", e); } if (Log.doTrace()) Log.trace("TradeDirect:init -- +++ initialized"); initialized = true; } public static void destroy() { try { if (!initialized) return; Log.trace("TradeDirect:destroy"); } catch (Exception e) { Log.error("TradeDirect:destroy", e); } } private static InitialContext context; private static ConnectionFactory qConnFactory; private static Queue queue; private static ConnectionFactory tConnFactory; private static Topic streamerTopic; private static Trade tradeEJB; private static boolean publishQuotePriceChange = true; /** * Gets the inGlobalTxn * @return Returns a boolean */ private boolean getInGlobalTxn() { return inGlobalTxn; } /** * Sets the inGlobalTxn * @param inGlobalTxn The inGlobalTxn to set */ private void setInGlobalTxn(boolean inGlobalTxn) { this.inGlobalTxn = inGlobalTxn; } }
DAYTRADER-8 Correct small difference in Sync Order Processing between Direct and EJB Mode git-svn-id: 52591b3751b2475bb1ae80497c335c234b34aa33@425477 13f79535-47bb-0310-9956-ffa450edef68
modules/ejb/src/main/java/org/apache/geronimo/samples/daytrader/direct/TradeDirect.java
DAYTRADER-8 Correct small difference in Sync Order Processing between Direct and EJB Mode
<ide><path>odules/ejb/src/main/java/org/apache/geronimo/samples/daytrader/direct/TradeDirect.java <ide> <ide> cancelOrder(conn, orderData.getOrderID()); <ide> } <add> <add> orderData = getOrderData(conn, orderData.getOrderID().intValue()); <ide> <ide> if (txn != null) { <ide> if ( Log.doTrace() ) <ide> <ide> cancelOrder(conn, orderData.getOrderID()); <ide> } <add> <add> orderData = getOrderData(conn, orderData.getOrderID().intValue()); <add> <ide> if (txn != null) { <ide> if ( Log.doTrace() ) <ide> Log.trace("TradeDirect:sell committing global transaction");
Java
apache-2.0
b0602b2b34a2e75a08d92b52f0a75667495363c3
0
tpb1908/AndroidProjectsClient,tpb1908/AndroidProjectsClient,tpb1908/AndroidProjectsClient
/* * Copyright (C) 2013-2015 Dominik Schürmann <[email protected]> * Copyright (C) 2013-2015 Juha Kuitunen * Copyright (C) 2013 Mohammed Lakkadshaw * Copyright (C) 2007 The Android Open Source Project * * 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.tpb.mdtext; import android.graphics.Color; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.util.Pair; import android.text.Editable; import android.text.Html; import android.text.Layout; import android.text.Spannable; import android.text.Spanned; import android.text.TextPaint; import android.text.style.AlignmentSpan; import android.text.style.BackgroundColorSpan; import android.text.style.BulletSpan; import android.text.style.ForegroundColorSpan; import android.text.style.LeadingMarginSpan; import android.text.style.StrikethroughSpan; import android.text.style.TypefaceSpan; import android.util.Log; import android.widget.TextView; import com.tpb.mdtext.handlers.CodeClickHandler; import com.tpb.mdtext.handlers.LinkClickHandler; import com.tpb.mdtext.handlers.TableClickHandler; import com.tpb.mdtext.views.spans.CleanURLSpan; import com.tpb.mdtext.views.spans.CodeSpan; import com.tpb.mdtext.views.spans.HorizontalRuleSpan; import com.tpb.mdtext.views.spans.InlineCodeSpan; import com.tpb.mdtext.views.spans.ListNumberSpan; import com.tpb.mdtext.views.spans.QuoteSpan; import com.tpb.mdtext.views.spans.RoundedBackgroundEndSpan; import com.tpb.mdtext.views.spans.TableSpan; import com.tpb.mdtext.views.spans.WrappingClickableSpan; import org.xml.sax.XMLReader; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; import java.util.Stack; import java.util.regex.Pattern; import static com.tpb.mdtext.TextUtils.isValidURL; public class HtmlTagHandler implements Html.TagHandler { private static final String TAG = HtmlTagHandler.class.getSimpleName(); private static final String UNORDERED_LIST_TAG = "ESCAPED_UL_TAG"; private static final String ORDERED_LIST_TAG = "ESCAPED_OL_TAG"; private static final String LIST_ITEM_TAG = "ESCAPED_LI_TAG"; private static final String BLOCKQUOTE_TAG = "ESCAPED_BLOCKQUOTE_TAG"; private static final String A_TAG = "ESCAPED_A_TAG"; private static final String FONT_TAG = "ESCAPED_FONT_TAG"; private static final Map<String, String> ESCAPE_MAP = new HashMap<>(); static { ESCAPE_MAP.put("<ul", "<" + UNORDERED_LIST_TAG); ESCAPE_MAP.put("</ul>", "</" + UNORDERED_LIST_TAG + ">"); ESCAPE_MAP.put("<ol", "<" + ORDERED_LIST_TAG); ESCAPE_MAP.put("</ol>", "</" + ORDERED_LIST_TAG + ">"); ESCAPE_MAP.put("<li", "<" + LIST_ITEM_TAG); ESCAPE_MAP.put("</li>", "</" + LIST_ITEM_TAG + ">"); ESCAPE_MAP.put("<blockquote>", "<" + BLOCKQUOTE_TAG + ">"); ESCAPE_MAP.put("</blockquote>", "</" + BLOCKQUOTE_TAG + ">"); ESCAPE_MAP.put("<a", "<" + A_TAG); ESCAPE_MAP.put("</a>", "</" + A_TAG + ">"); ESCAPE_MAP.put("<font", "<" + FONT_TAG); ESCAPE_MAP.put("</font>", "</" + FONT_TAG + ">"); } private static final Pattern ESCAPE_PATTERN = TextUtils.generatePattern(ESCAPE_MAP.keySet()); /** * Android captures some tags before they get here, so we escape them */ public String overrideTags(@Nullable String html) { return TextUtils.replace(html, ESCAPE_MAP, ESCAPE_PATTERN); } /** * Stack of nested list tags, bulleted flag and list type (For OL) */ private final Stack<Triple<String, Boolean, ListNumberSpan.ListType>> mLists = new Stack<>(); /** * Tracks indexes of ordered lists so that after a nested list ends * we can continue with correct index of outer list */ private final Stack<Pair<Integer, ListNumberSpan.ListType>> mOlIndices = new Stack<>(); private StringBuilder mTableHtmlBuilder = new StringBuilder(); private int mTableLevel = 0; private static int mSingleIndent = 10; private static final int mListIndent = mSingleIndent * 2; private final TextPaint mTextPaint; private LinkClickHandler mLinkHandler; private CodeClickHandler mCodeHandler; private TableClickHandler mTableHandler; public HtmlTagHandler(TextView tv, @Nullable LinkClickHandler linkHandler, @Nullable CodeClickHandler codeHandler, @Nullable TableClickHandler tableHandler) { mTextPaint = tv.getPaint(); mSingleIndent = (int) mTextPaint.measureText("t"); mLinkHandler = linkHandler; mCodeHandler = codeHandler; mTableHandler = tableHandler; } @Override public void handleTag(final boolean opening, final String tag, Editable output, final XMLReader xmlReader) { if(opening) { handleOpeningTag(tag, output, xmlReader); } else { handleClosingTag(tag, output); } storeTableTags(opening, tag); } private void handleOpeningTag(final String tag, Editable output, final XMLReader xmlReader) { switch(tag.toUpperCase()) { case UNORDERED_LIST_TAG: mLists.push( new Triple<>( tag, safelyParseBoolean(getAttribute("bulleted", xmlReader, "true"), true ), ListNumberSpan.ListType.NUMBER ) ); break; case ORDERED_LIST_TAG: final ListNumberSpan.ListType type = ListNumberSpan.ListType .fromString(getAttribute("type", xmlReader, "")); mLists.push( new Triple<>( tag, safelyParseBoolean(getAttribute("numbered", xmlReader, "true"), true ), type ) ); mOlIndices.push(Pair.create(1, type)); break; case LIST_ITEM_TAG: if(output.length() > 0 && output.charAt(output.length() - 1) != '\n') { output.append("\n"); } if(!mLists.isEmpty()) { String parentList = mLists.peek().first; if(parentList.equalsIgnoreCase(ORDERED_LIST_TAG)) { start(output, new Ol()); mOlIndices.push(Pair.create(mOlIndices.pop().first + 1, mLists.peek().third)); } else if(parentList.equalsIgnoreCase(UNORDERED_LIST_TAG)) { start(output, new Ul()); } } else { start(output, new Ol()); mOlIndices.push(Pair.create(1, ListNumberSpan.ListType.NUMBER)); } break; case "TABLE": start(output, new Table()); if(mTableLevel == 0) { mTableHtmlBuilder = new StringBuilder(); } mTableLevel++; break; case FONT_TAG: final String font = getAttribute("face", xmlReader, ""); final String fgColor = getAttribute("color", xmlReader, ""); final String bgColor = getAttribute("background-color", xmlReader, ""); final boolean rounded = safelyParseBoolean(getAttribute("rounded", xmlReader, ""), false ); if(font != null && !font.isEmpty()) { start(output, new Font(font)); } if(fgColor != null && !fgColor.isEmpty()) { start(output, new ForegroundColor(fgColor)); } if(bgColor != null && !bgColor.isEmpty()) { start(output, new BackgroundColor(bgColor, rounded)); } break; case "CODE": start(output, new Code()); break; case "CENTER": start(output, new Center()); break; case "S": case "STRIKE": start(output, new StrikeThrough()); break; case "TR": start(output, new Tr()); break; case "TH": start(output, new Th()); break; case "TD": start(output, new Td()); break; case "HR": start(output, new HorizontalRule()); break; case BLOCKQUOTE_TAG: start(output, new BlockQuote()); break; case A_TAG: start(output, new A(getAttribute("href", xmlReader, "invalid_url"))); break; case "INLINECODE": start(output, new InlineCode()); break; } } private void handleClosingTag(final String tag, Editable output) { switch(tag.toUpperCase()) { case UNORDERED_LIST_TAG: mLists.pop(); break; case ORDERED_LIST_TAG: mLists.pop(); mOlIndices.pop(); break; case LIST_ITEM_TAG: if(!mLists.isEmpty()) { if(mLists.peek().first.equalsIgnoreCase(UNORDERED_LIST_TAG)) { handleULTag(output); } else if(mLists.peek().first.equalsIgnoreCase(ORDERED_LIST_TAG)) { handleOLTag(output); } } else { end(output, Ol.class, true); } break; case "CODE": handleCodeTag(output); break; case "HR": handleHorizontalRule(output); break; case "CENTER": end(output, Center.class, true, new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER) ); break; case "S": case "STRIKE": end(output, StrikeThrough.class, false, new StrikethroughSpan()); break; case "TABLE": handleTableTag(output); break; case BLOCKQUOTE_TAG: handleBlockQuoteTag(output); break; case A_TAG: handleATag(output); break; case "INLINECODE": handleInlineCodeTag(output); break; case FONT_TAG: handleFontTag(output); break; case "TR": end(output, Tr.class, false); break; case "TH": end(output, Th.class, false); break; case "TD": end(output, Td.class, false); break; } } private void handleBlockQuoteTag(Editable output) { Object obj = getLast(output, BlockQuote.class); final int start = output.getSpanStart(obj); final int end = output.length(); output.removeSpan(obj); output.setSpan(new QuoteSpan(), start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE); } private void handleInlineCodeTag(Editable output) { final Object obj = getLast(output, InlineCode.class); final int start = output.getSpanStart(obj); final int end = output.length(); output.removeSpan(obj); output.setSpan(new InlineCodeSpan(mTextPaint.getTextSize()), start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE ); } private void handleTableTag(Editable output) { mTableLevel--; // When we're back at the root-level table if(mTableLevel == 0) { final Table obj = getLast(output, Table.class); final int start = output.getSpanStart(obj); output.removeSpan(obj); //Remove the old span output.insert(start, "\n"); output.replace(start + 1, output.length(), " "); //We need a non-empty span final TableSpan table = new TableSpan(mTableHtmlBuilder.toString(), mTableHandler); output.setSpan(table, start, start + 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); output.setSpan(new WrappingClickableSpan(table), start, start + 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ); } else { end(output, Table.class, false); } } private void handleHorizontalRule(Editable output) { final Object obj = getLast(output, HorizontalRule.class); final int start = output.getSpanStart(obj); output.removeSpan(obj); //Remove the old span output.replace(start, output.length(), " "); //We need a non-empty span output.setSpan(new HorizontalRuleSpan(), start, start + 1, 0); //Insert the bar span } private void handleCodeTag(Editable output) { final Object obj = getLast(output, Code.class); final int start = output.getSpanStart(obj); final int end = output.length(); if(end > start + 1) { output.removeSpan(obj); final char[] chars = new char[end - start]; output.getChars(start, end, chars, 0); output.insert(start, "\n"); // Another line for our CodeSpan to cover output.replace(start + 1, end, " "); final CodeSpan code = new CodeSpan(new String(chars), mCodeHandler); output.setSpan(code, start, start + 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); output.setSpan(new WrappingClickableSpan(code), start, start + 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ); } } private void handleULTag(Editable output) { if(output.length() > 0 && output.charAt(output.length() - 1) != '\n') { output.append("\n"); } if(mLists.peek().second) { //Check for checkboxes if(output.length() > 2 && ((output.charAt(0) >= '\u2610' && output.charAt(0) <= '\u2612') || (output.charAt(1) >= '\u2610' && output .charAt(1) <= '\u2612') )) { end(output, Ul.class, false, new LeadingMarginSpan.Standard( mListIndent * (mLists.size() - 1)) ); } else { end(output, Ul.class, false, new LeadingMarginSpan.Standard( mListIndent * (mLists.size() - 1)), new BulletSpan(mSingleIndent) ); } } else { end(output, Ul.class, false, new LeadingMarginSpan.Standard(mListIndent * (mLists.size() - 1)) ); } } private void handleOLTag(Editable output) { if(output.length() > 0 && output.charAt(output.length() - 1) != '\n') { output.append("\n"); } int numberMargin = mListIndent * (mLists.size() - 1); if(mLists.size() > 2) { // Same as in ordered lists: counter the effect of nested Spans numberMargin -= (mLists.size() - 2) * mListIndent; } if(mLists.peek().second) { end(output, Ol.class, false, new LeadingMarginSpan.Standard(numberMargin), new ListNumberSpan(mTextPaint, mOlIndices.lastElement().first - 1, mLists.peek().third ) ); } else { end(output, Ol.class, false, new LeadingMarginSpan.Standard(numberMargin) ); } } private void handleFontTag(Editable output) { final ForegroundColor fgc = getLast(output, ForegroundColor.class); final BackgroundColor bgc = getLast(output, BackgroundColor.class); final Font f = getLast(output, Font.class); if(fgc != null) { final int start = output.getSpanStart(fgc); final int end = output.length(); output.removeSpan(fgc); output.setSpan(new ForegroundColorSpan(safelyParseColor(fgc.color)), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ); } if(bgc != null) { final int start = output.getSpanStart(bgc); final int end = output.length(); output.removeSpan(bgc); final int color = safelyParseColor(bgc.color); if(bgc.rounded) { output.insert(end, " "); output.insert(start, " "); output.setSpan(new RoundedBackgroundEndSpan(color, false), start, start + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ); output.setSpan(new RoundedBackgroundEndSpan(color, true), end, end + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ); output.setSpan(new BackgroundColorSpan(color), start + 1, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE ); } else { output.setSpan(new BackgroundColorSpan(color), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ); } } if(f != null) { final int start = output.getSpanStart(f); final int end = output.length(); output.removeSpan(f); output.setSpan(new TypefaceSpan(f.face), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ); } } private void handleATag(Editable output) { final A obj = getLast(output, A.class); final int start = output.getSpanStart(obj); final int end = output.length(); output.removeSpan(obj); if(isValidURL(obj.href)) { output.setSpan(new CleanURLSpan(obj.href, mLinkHandler), start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE ); } } private static int safelyParseColor(String color) { try { return Color.parseColor(color); } catch(Exception e) { switch(color) { case "black": return Color.BLACK; case "white": return Color.WHITE; case "red": return Color.RED; case "blue": return Color.BLUE; case "green": return Color.GREEN; case "grey": return Color.GRAY; case "yellow": return Color.YELLOW; case "aqua": return 0xff00ffff; case "fuchsia": return 0xffff00ff; case "lime": return 0xff00ff00; case "maroon": return 0xff800000; case "navy": return 0xffff00ff; case "olive": return 0xff808000; case "purple": return 0xff800080; case "silver": return 0xffc0c0c0; case "teal": return 0xff008080; default: return Color.WHITE; } } } private static Boolean safelyParseBoolean(String bool, boolean def) { try { return Boolean.valueOf(bool); } catch(Exception e) { return def; } } private static String getAttribute(@NonNull String attr, @NonNull XMLReader reader, String defaultAttr) { try { final Field fElement = reader.getClass().getDeclaredField("theNewElement"); fElement.setAccessible(true); final Object element = fElement.get(reader); final Field fAtts = element.getClass().getDeclaredField("theAtts"); fAtts.setAccessible(true); final Object attrs = fAtts.get(element); final Field fData = attrs.getClass().getDeclaredField("data"); fData.setAccessible(true); final String[] data = (String[]) fData.get(attrs); final Field fLength = attrs.getClass().getDeclaredField("length"); fLength.setAccessible(true); final int len = (Integer) fLength.get(attrs); for(int i = 0; i < len; i++) { if(attr.equals(data[i * 5 + 1])) { return data[i * 5 + 4]; } } } catch(Exception e) { Log.e(TAG, "handleTag: ", e); } return defaultAttr; } /** * If we're arriving at a table tag or are already within a table tag, then we should store it * the raw HTML for our ClickableTableSpan */ private void storeTableTags(boolean opening, String tag) { if(mTableLevel > 0 || tag.equalsIgnoreCase("table")) { mTableHtmlBuilder.append("<"); if(!opening) { mTableHtmlBuilder.append("/"); } mTableHtmlBuilder .append(tag.toLowerCase()) .append(">"); } } /** * Mark the opening tag by using private classes */ private void start(Editable output, Object mark) { final int point = output.length(); output.setSpan(mark, point, point, Spannable.SPAN_MARK_MARK); } /** * Modified from {@link android.text.Html} */ private void end(Editable output, Class kind, boolean paragraphStyle, Object... replaces) { Object obj = getLast(output, kind); // start of the tag int start = output.getSpanStart(obj); // end of the tag int end = output.length(); // If we're in a table, then we need to store the raw HTML for later if(mTableLevel > 0) { final CharSequence extractedSpanText = extractSpanText(output, kind); mTableHtmlBuilder.append(extractedSpanText); } output.removeSpan(obj); if(start != end) { int len = end; // paragraph styles like AlignmentSpan need to end with a new line! if(paragraphStyle) { output.append("\n"); len++; } for(Object replace : replaces) { if(output.length() > 0) { output.setSpan(replace, start, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } } } /** * Returns the text contained within a span and deletes it from the output string */ private CharSequence extractSpanText(Editable output, Class kind) { final Object obj = getLast(output, kind); final int start = output.getSpanStart(obj); final int end = output.length(); final CharSequence extractedSpanText = output.subSequence(start, end); output.delete(start, end); return extractedSpanText; } /** * Get last marked position of a specific tag kind (private class) */ private static <T> T getLast(Editable text, Class<T> kind) { final T[] objs = text.getSpans(0, text.length(), kind); if(objs.length == 0) { return null; } else { for(int i = objs.length; i > 0; i--) { if(text.getSpanFlags(objs[i - 1]) == Spannable.SPAN_MARK_MARK) { return objs[i - 1]; } } return null; } } private static class Ul { } private static class Ol { } private static class Code { } private static class Center { } private static class StrikeThrough { } private static class Table { } private static class Tr { } private static class Th { } private static class Td { } private static class HorizontalRule { } private static class BlockQuote { } private static class InlineCode { } private static class A { String href; A(String href) { this.href = href; } } private static class ForegroundColor { String color; ForegroundColor(String color) { this.color = color; } } private static class BackgroundColor { String color; boolean rounded; BackgroundColor(String color, boolean rounded) { this.color = color; this.rounded = rounded; } } private static class Font { String face; Font(String face) { this.face = face; } } private static class Triple<T, U, V> { T first; U second; V third; Triple(T t, U u, V v) { first = t; second = u; third = v; } } }
markdowntextview/src/main/java/com/tpb/mdtext/HtmlTagHandler.java
/* * Copyright (C) 2013-2015 Dominik Schürmann <[email protected]> * Copyright (C) 2013-2015 Juha Kuitunen * Copyright (C) 2013 Mohammed Lakkadshaw * Copyright (C) 2007 The Android Open Source Project * * 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.tpb.mdtext; import android.graphics.Color; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.util.Pair; import android.text.Editable; import android.text.Html; import android.text.Layout; import android.text.Spannable; import android.text.Spanned; import android.text.TextPaint; import android.text.style.AlignmentSpan; import android.text.style.BackgroundColorSpan; import android.text.style.BulletSpan; import android.text.style.ForegroundColorSpan; import android.text.style.LeadingMarginSpan; import android.text.style.StrikethroughSpan; import android.text.style.TypefaceSpan; import android.util.Log; import android.widget.TextView; import com.tpb.mdtext.handlers.CodeClickHandler; import com.tpb.mdtext.handlers.LinkClickHandler; import com.tpb.mdtext.handlers.TableClickHandler; import com.tpb.mdtext.views.spans.CleanURLSpan; import com.tpb.mdtext.views.spans.CodeSpan; import com.tpb.mdtext.views.spans.HorizontalRuleSpan; import com.tpb.mdtext.views.spans.InlineCodeSpan; import com.tpb.mdtext.views.spans.ListNumberSpan; import com.tpb.mdtext.views.spans.QuoteSpan; import com.tpb.mdtext.views.spans.RoundedBackgroundEndSpan; import com.tpb.mdtext.views.spans.TableSpan; import com.tpb.mdtext.views.spans.WrappingClickableSpan; import org.xml.sax.XMLReader; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; import java.util.Stack; import java.util.regex.Pattern; import static com.tpb.mdtext.TextUtils.isValidURL; public class HtmlTagHandler implements Html.TagHandler { private static final String TAG = HtmlTagHandler.class.getSimpleName(); private static final String UNORDERED_LIST_TAG = "ESCAPED_UL_TAG"; private static final String ORDERED_LIST_TAG = "ESCAPED_OL_TAG"; private static final String LIST_ITEM_TAG = "ESCAPED_LI_TAG"; private static final String BLOCKQUOTE_TAG = "ESCAPED_BLOCKQUOTE_TAG"; private static final String A_TAG = "ESCAPED_A_TAG"; private static final String FONT_TAG = "ESCAPED_FONT_TAG"; private static final Map<String, String> ESCAPE_MAP = new HashMap<>(); static { ESCAPE_MAP.put("<ul", "<" + UNORDERED_LIST_TAG); ESCAPE_MAP.put("</ul>", "</" + UNORDERED_LIST_TAG + ">"); ESCAPE_MAP.put("<ol", "<" + ORDERED_LIST_TAG); ESCAPE_MAP.put("</ol>", "</" + ORDERED_LIST_TAG + ">"); ESCAPE_MAP.put("<li", "<" + LIST_ITEM_TAG); ESCAPE_MAP.put("</li>", "</" + LIST_ITEM_TAG + ">"); ESCAPE_MAP.put("<blockquote>", "<" + BLOCKQUOTE_TAG + ">"); ESCAPE_MAP.put("</blockquote>", "</" + BLOCKQUOTE_TAG + ">"); ESCAPE_MAP.put("<a", "<" + A_TAG); ESCAPE_MAP.put("</a>", "</" + A_TAG + ">"); ESCAPE_MAP.put("<font", "<" + FONT_TAG); ESCAPE_MAP.put("</font>", "</" + FONT_TAG + ">"); } private static final Pattern ESCAPE_PATTERN = TextUtils.generatePattern(ESCAPE_MAP.keySet()); /** * Android captures some tags before they get here, so we escape them */ public String overrideTags(@Nullable String html) { return TextUtils.replace(html, ESCAPE_MAP, ESCAPE_PATTERN); } /** * Stack of nested list tags, bulleted flag and list type (For OL) */ private final Stack<Triple<String, Boolean, ListNumberSpan.ListType>> mLists = new Stack<>(); /** * Tracks indexes of ordered lists so that after a nested list ends * we can continue with correct index of outer list */ private final Stack<Pair<Integer, ListNumberSpan.ListType>> mOlIndices = new Stack<>(); private StringBuilder mTableHtmlBuilder = new StringBuilder(); private int mTableLevel = 0; private static int mSingleIndent = 10; private static final int mListIndent = mSingleIndent * 2; private final TextPaint mTextPaint; private LinkClickHandler mLinkHandler; private CodeClickHandler mCodeHandler; private TableClickHandler mTableHandler; public HtmlTagHandler(TextView tv, @Nullable LinkClickHandler linkHandler, @Nullable CodeClickHandler codeHandler, @Nullable TableClickHandler tableHandler) { mTextPaint = tv.getPaint(); mSingleIndent = (int) mTextPaint.measureText("t"); mLinkHandler = linkHandler; mCodeHandler = codeHandler; mTableHandler = tableHandler; } @Override public void handleTag(final boolean opening, final String tag, Editable output, final XMLReader xmlReader) { if(opening) { handleOpeningTag(tag, output, xmlReader); } else { handleClosingTag(tag, output); } storeTableTags(opening, tag); } private void handleOpeningTag(final String tag, Editable output, final XMLReader xmlReader) { switch(tag.toUpperCase()) { case UNORDERED_LIST_TAG: mLists.push( new Triple<>( tag, safelyParseBoolean(getAttribute("bulleted", xmlReader, "true"), true ), ListNumberSpan.ListType.NUMBER ) ); break; case ORDERED_LIST_TAG: final ListNumberSpan.ListType type = ListNumberSpan.ListType .fromString(getAttribute("type", xmlReader, "")); mLists.push( new Triple<>( tag, safelyParseBoolean(getAttribute("numbered", xmlReader, "true"), true ), type ) ); mOlIndices.push(Pair.create(1, type)); break; case LIST_ITEM_TAG: if(output.length() > 0 && output.charAt(output.length() - 1) != '\n') { output.append("\n"); } if(!mLists.isEmpty()) { String parentList = mLists.peek().first; if(parentList.equalsIgnoreCase(ORDERED_LIST_TAG)) { start(output, new Ol()); mOlIndices.push(Pair.create(mOlIndices.pop().first + 1, mLists.peek().third)); } else if(parentList.equalsIgnoreCase(UNORDERED_LIST_TAG)) { start(output, new Ul()); } } else { start(output, new Ol()); mOlIndices.push(Pair.create(1, ListNumberSpan.ListType.NUMBER)); } break; case "TABLE": start(output, new Table()); if(mTableLevel == 0) { mTableHtmlBuilder = new StringBuilder(); } mTableLevel++; break; case FONT_TAG: final String font = getAttribute("face", xmlReader, ""); final String fgColor = getAttribute("color", xmlReader, ""); final String bgColor = getAttribute("background-color", xmlReader, ""); final boolean rounded = safelyParseBoolean(getAttribute("rounded", xmlReader, ""), false ); if(font != null && !font.isEmpty()) { start(output, new Font(font)); } if(fgColor != null && !fgColor.isEmpty()) { start(output, new ForegroundColor(fgColor)); } if(bgColor != null && !bgColor.isEmpty()) { start(output, new BackgroundColor(bgColor, rounded)); } break; case "CODE": start(output, new Code()); break; case "CENTER": start(output, new Center()); break; case "S": case "STRIKE": start(output, new StrikeThrough()); break; case "TR": start(output, new Tr()); break; case "TH": start(output, new Th()); break; case "TD": start(output, new Td()); break; case "HR": start(output, new HorizontalRule()); break; case BLOCKQUOTE_TAG: start(output, new BlockQuote()); break; case A_TAG: start(output, new A(getAttribute("href", xmlReader, "invalid_url"))); break; case "INLINECODE": start(output, new InlineCode()); break; } } private void handleClosingTag(final String tag, Editable output) { switch(tag.toUpperCase()) { case UNORDERED_LIST_TAG: mLists.pop(); break; case ORDERED_LIST_TAG: mLists.pop(); mOlIndices.pop(); break; case LIST_ITEM_TAG: if(!mLists.isEmpty()) { if(mLists.peek().first.equalsIgnoreCase(UNORDERED_LIST_TAG)) { handleULTag(output); } else if(mLists.peek().first.equalsIgnoreCase(ORDERED_LIST_TAG)) { handleOLTag(output); } } else { end(output, Ol.class, true); } break; case "CODE": handleCodeTag(output); break; case "HR": handleHorizontalRule(output); break; case "CENTER": end(output, Center.class, true, new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER) ); break; case "S": case "STRIKE": end(output, StrikeThrough.class, false, new StrikethroughSpan()); break; case "TABLE": handleTableTag(output); break; case BLOCKQUOTE_TAG: handleBlockQuoteTag(output); break; case A_TAG: handleATag(output); break; case "INLINECODE": handleInlineCodeTag(output); break; case FONT_TAG: handleFontTag(output); break; case "TR": end(output, Tr.class, false); break; case "TH": end(output, Th.class, false); break; case "TD": end(output, Td.class, false); break; } } private void handleBlockQuoteTag(Editable output) { Object obj = getLast(output, BlockQuote.class); final int start = output.getSpanStart(obj); final int end = output.length(); output.removeSpan(obj); output.setSpan(new QuoteSpan(), start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE); } private void handleInlineCodeTag(Editable output) { final Object obj = getLast(output, InlineCode.class); final int start = output.getSpanStart(obj); final int end = output.length(); output.removeSpan(obj); output.setSpan(new InlineCodeSpan(mTextPaint.getTextSize()), start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE ); } private void handleTableTag(Editable output) { mTableLevel--; // When we're back at the root-level table if(mTableLevel == 0) { final Table obj = getLast(output, Table.class); final int start = output.getSpanStart(obj); output.removeSpan(obj); //Remove the old span output.insert(start, "\n"); output.replace(start + 1, output.length(), " "); //We need a non-empty span final TableSpan table = new TableSpan(mTableHtmlBuilder.toString(), mTableHandler); output.setSpan(table, start, start + 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); output.setSpan(new WrappingClickableSpan(table), start, start + 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ); } else { end(output, Table.class, false); } } private void handleHorizontalRule(Editable output) { final Object obj = getLast(output, HorizontalRule.class); final int start = output.getSpanStart(obj); output.removeSpan(obj); //Remove the old span output.replace(start, output.length(), " "); //We need a non-empty span output.setSpan(new HorizontalRuleSpan(), start, start + 1, 0); //Insert the bar span } private void handleCodeTag(Editable output) { final Object obj = getLast(output, Code.class); final int start = output.getSpanStart(obj); final int end = output.length(); if(end > start + 1) { output.removeSpan(obj); final char[] chars = new char[end - start]; output.getChars(start, end, chars, 0); output.insert(start, "\n"); // Another line for our CodeSpan to cover output.replace(start + 1, end, " "); final CodeSpan code = new CodeSpan(new String(chars), mCodeHandler); output.setSpan(code, start, start + 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); output.setSpan(new WrappingClickableSpan(code), start, start + 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ); } } private void handleULTag(Editable output) { if(output.length() > 0 && output.charAt(output.length() - 1) != '\n') { output.append("\n"); } if(mLists.peek().second) { //Check for checkboxes if(output.length() > 2 && ((output.charAt(0) >= '\u2610' && output.charAt(0) <= '\u2612') || (output.charAt(1) >= '\u2610' && output .charAt(1) <= '\u2612') )) { end(output, Ul.class, false, new LeadingMarginSpan.Standard( mListIndent * (mLists.size() - 1)) ); } else { end(output, Ul.class, false, new LeadingMarginSpan.Standard( mListIndent * (mLists.size() - 1)), new BulletSpan(mSingleIndent) ); } } else { end(output, Ul.class, false, new LeadingMarginSpan.Standard(mListIndent * (mLists.size() - 1)) ); } } private void handleOLTag(Editable output) { if(output.length() > 0 && output.charAt(output.length() - 1) != '\n') { output.append("\n"); } int numberMargin = mListIndent * (mLists.size() - 1); if(mLists.size() > 2) { // Same as in ordered lists: counter the effect of nested Spans numberMargin -= (mLists.size() - 2) * mListIndent; } if(mLists.peek().second) { end(output, Ol.class, false, new LeadingMarginSpan.Standard(numberMargin), new ListNumberSpan(mTextPaint, mOlIndices.lastElement().first - 1, mLists.peek().third ) ); } else { end(output, Ol.class, false, new LeadingMarginSpan.Standard(numberMargin) ); } } private void handleFontTag(Editable output) { final ForegroundColor fgc = getLast(output, ForegroundColor.class); final BackgroundColor bgc = getLast(output, BackgroundColor.class); final Font f = getLast(output, Font.class); if(fgc != null) { final int start = output.getSpanStart(fgc); final int end = output.length(); output.removeSpan(fgc); output.setSpan(new ForegroundColorSpan(safelyParseColor(fgc.color)), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ); } if(bgc != null) { final int start = output.getSpanStart(bgc); final int end = output.length(); output.removeSpan(bgc); final int color = safelyParseColor(bgc.color); if(bgc.rounded) { output.insert(end, " "); output.insert(start, " "); output.setSpan(new RoundedBackgroundEndSpan(color, false), start, start + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ); output.setSpan(new RoundedBackgroundEndSpan(color, true), end, end + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ); output.setSpan(new BackgroundColorSpan(color), start + 1, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE ); } else { output.setSpan(new BackgroundColorSpan(color), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ); } } if(f != null) { final int start = output.getSpanStart(f); final int end = output.length(); output.removeSpan(f); output.setSpan(new TypefaceSpan(f.face), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ); } } private void handleATag(Editable output) { final A obj = getLast(output, A.class); final int start = output.getSpanStart(obj); final int end = output.length(); output.removeSpan(obj); if(isValidURL(obj.href)) { output.setSpan(new CleanURLSpan(obj.href, mLinkHandler), start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE ); } } private static int safelyParseColor(String color) { try { return Color.parseColor(color); } catch(Exception e) { switch(color) { case "black": return Color.BLACK; case "white": return Color.WHITE; case "red": return Color.RED; case "blue": return Color.BLUE; case "green": return Color.GREEN; case "grey": return Color.GRAY; case "yellow": return Color.YELLOW; case "aqua": return 0xff00ffff; case "fuchsia": return 0xffff00ff; case "lime": return 0xff00ff00; case "maroon": return 0xff800000; case "navy": return 0xffff00ff; case "olive": return 0xff808000; case "purple": return 0xff800080; case "silver": return 0xffc0c0c0; case "teal": return 0xff008080; default: return Color.WHITE; } } } private static Boolean safelyParseBoolean(String bool, boolean def) { try { return Boolean.valueOf(bool); } catch(Exception e) { return def; } } private static String getAttribute(@NonNull String attr, @NonNull XMLReader reader, String defaultAttr) { try { final Field fElement = reader.getClass().getDeclaredField("theNewElement"); fElement.setAccessible(true); final Object element = fElement.get(reader); final Field fAtts = element.getClass().getDeclaredField("theAtts"); fAtts.setAccessible(true); final Object attrs = fAtts.get(element); final Field fData = attrs.getClass().getDeclaredField("data"); fData.setAccessible(true); final String[] data = (String[]) fData.get(attrs); final Field fLength = attrs.getClass().getDeclaredField("length"); fLength.setAccessible(true); final int len = (Integer) fLength.get(attrs); for(int i = 0; i < len; i++) { if(attr.equals(data[i * 5 + 1])) { return data[i * 5 + 4]; } } } catch(Exception e) { Log.e(TAG, "handleTag: ", e); } return defaultAttr; } /** * If we're arriving at a table tag or are already within a table tag, then we should store it * the raw HTML for our ClickableTableSpan */ private void storeTableTags(boolean opening, String tag) { if(mTableLevel > 0 || tag.equalsIgnoreCase("table")) { mTableHtmlBuilder.append("<"); if(!opening) { mTableHtmlBuilder.append("/"); } mTableHtmlBuilder .append(tag.toLowerCase()) .append(">"); } } /** * Mark the opening tag by using private classes */ private void start(Editable output, Object mark) { final int point = output.length(); output.setSpan(mark, point, point, Spannable.SPAN_MARK_MARK); } /** * Modified from {@link android.text.Html} */ private void end(Editable output, Class kind, boolean paragraphStyle, Object... replaces) { Object obj = getLast(output, kind); // start of the tag int start = output.getSpanStart(obj); // end of the tag int end = output.length(); // If we're in a table, then we need to store the raw HTML for later if(mTableLevel > 0) { final CharSequence extractedSpanText = extractSpanText(output, kind); mTableHtmlBuilder.append(extractedSpanText); } output.removeSpan(obj); if(start != end) { int len = end; // paragraph styles like AlignmentSpan need to end with a new line! if(paragraphStyle) { output.append("\n"); len++; } for(Object replace : replaces) { if(len < output.length()) { output.setSpan(replace, start, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } } } /** * Returns the text contained within a span and deletes it from the output string */ private CharSequence extractSpanText(Editable output, Class kind) { final Object obj = getLast(output, kind); final int start = output.getSpanStart(obj); final int end = output.length(); final CharSequence extractedSpanText = output.subSequence(start, end); output.delete(start, end); return extractedSpanText; } /** * Get last marked position of a specific tag kind (private class) */ private static <T> T getLast(Editable text, Class<T> kind) { final T[] objs = text.getSpans(0, text.length(), kind); if(objs.length == 0) { return null; } else { for(int i = objs.length; i > 0; i--) { if(text.getSpanFlags(objs[i - 1]) == Spannable.SPAN_MARK_MARK) { return objs[i - 1]; } } return null; } } private static class Ul { } private static class Ol { } private static class Code { } private static class Center { } private static class StrikeThrough { } private static class Table { } private static class Tr { } private static class Th { } private static class Td { } private static class HorizontalRule { } private static class BlockQuote { } private static class InlineCode { } private static class A { String href; A(String href) { this.href = href; } } private static class ForegroundColor { String color; ForegroundColor(String color) { this.color = color; } } private static class BackgroundColor { String color; boolean rounded; BackgroundColor(String color, boolean rounded) { this.color = color; this.rounded = rounded; } } private static class Font { String face; Font(String face) { this.face = face; } } private static class Triple<T, U, V> { T first; U second; V third; Triple(T t, U u, V v) { first = t; second = u; third = v; } } }
Fixed crash when replacing in a 0 length Editable.
markdowntextview/src/main/java/com/tpb/mdtext/HtmlTagHandler.java
Fixed crash when replacing in a 0 length Editable.
<ide><path>arkdowntextview/src/main/java/com/tpb/mdtext/HtmlTagHandler.java <ide> new LeadingMarginSpan.Standard(mListIndent * (mLists.size() - 1)) <ide> ); <ide> } <del> <ide> } <ide> <ide> private void handleOLTag(Editable output) { <ide> len++; <ide> } <ide> for(Object replace : replaces) { <del> if(len < output.length()) { <add> if(output.length() > 0) { <ide> output.setSpan(replace, start, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); <ide> } <ide> }
Java
mit
0b5836884f29574bae8f6236d955d26c8e609f24
0
algoliareadmebot/algoliasearch-client-android,algolia/algoliasearch-client-android,algoliareadmebot/algoliasearch-client-android,algolia/algoliasearch-client-android,algolia/algoliasearch-client-android
/* * Copyright (c) 2015 Algolia * http://www.algolia.com/ * * 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. */ package com.algolia.search.saas; import android.support.annotation.NonNull; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * A proxy to an Algolia index. * <p> * You cannot construct this class directly. Please use {@link Client#initIndex(String)} to obtain an instance. * </p> * <p> * WARNING: For performance reasons, arguments to asynchronous methods are not cloned. Therefore, you should not * modify mutable arguments after they have been passed (unless explicitly noted). * </p> */ public class Index { /** The client to which this index belongs. */ private Client client; /** This index's name. */ private String indexName; /** This index's name, URL-encoded. Cached for optimization. */ private String encodedIndexName; private ExpiringCache<String, byte[]> searchCache; private boolean isCacheEnabled = false; // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final long MAX_TIME_MS_TO_WAIT = 10000L; // ---------------------------------------------------------------------- // Initialization // ---------------------------------------------------------------------- protected Index(@NonNull Client client, @NonNull String indexName) { try { this.client = client; this.encodedIndexName = URLEncoder.encode(indexName, "UTF-8"); this.indexName = indexName; } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); // should never happen, as UTF-8 is always supported } } // ---------------------------------------------------------------------- // Accessors // ---------------------------------------------------------------------- @Override public String toString() { return String.format("%s{%s}", this.getClass().getSimpleName(), getIndexName()); } public String getIndexName() { return indexName; } public Client getClient() { return client; } protected String getEncodedIndexName() { return encodedIndexName; } // ---------------------------------------------------------------------- // Public operations // ---------------------------------------------------------------------- /** * Search inside this index (asynchronously). * * @param query Search parameters. May be null to use an empty query. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request searchAsync(@NonNull Query query, @NonNull CompletionHandler completionHandler) { final Query queryCopy = new Query(query); return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return search(queryCopy); } }.start(); } /** * Search inside this index (synchronously). * * @return Search results. */ public JSONObject searchSync(@NonNull Query query) throws AlgoliaException { return search(query); } /** * Run multiple queries on this index with one API call. * A variant of {@link Client#multipleQueriesAsync(List, Client.MultipleQueriesStrategy, CompletionHandler)} * where the targeted index is always the receiver. * * @param queries The queries to run. * @param strategy The strategy to use. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request multipleQueriesAsync(final @NonNull List<Query> queries, final Client.MultipleQueriesStrategy strategy, @NonNull CompletionHandler completionHandler) { final List<Query> queriesCopy = new ArrayList<>(queries.size()); for (Query query : queries) { queriesCopy.add(new Query(query)); } return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return multipleQueries(queriesCopy, strategy == null ? null : strategy.toString()); } }.start(); } /** * Search inside this index synchronously. * * @return Search results. */ protected byte[] searchSyncRaw(@NonNull Query query) throws AlgoliaException { return searchRaw(query); } /** * Perform a search with disjunctive facets, generating as many queries as number of disjunctive facets (helper). * * @param query The query. * @param disjunctiveFacets List of disjunctive facets. * @param refinements The current refinements, mapping facet names to a list of values. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request searchDisjunctiveFacetingAsync(@NonNull Query query, @NonNull final List<String> disjunctiveFacets, @NonNull final Map<String, List<String>> refinements, @NonNull final CompletionHandler completionHandler) { final List<Query> queries = computeDisjunctiveFacetingQueries(query, disjunctiveFacets, refinements); return multipleQueriesAsync(queries, null, new CompletionHandler() { @Override public void requestCompleted(JSONObject content, AlgoliaException error) { JSONObject aggregatedResults = null; try { if (content != null) { aggregatedResults = aggregateDisjunctiveFacetingResults(content, disjunctiveFacets, refinements); } } catch (AlgoliaException e) { error = e; } completionHandler.requestCompleted(aggregatedResults, error); } }); } /** * Add an object to this index (asynchronously). * <p> * WARNING: For performance reasons, the arguments are not cloned. Since the method is executed in the background, * you should not modify the object after it has been passed. * </p> * * @param object The object to add. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request addObjectAsync(final @NonNull JSONObject object, CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return addObject(object); } }.start(); } /** * Add an object to this index, assigning it the specified object ID (asynchronously). * If an object already exists with the same object ID, the existing object will be overwritten. * <p> * WARNING: For performance reasons, the arguments are not cloned. Since the method is executed in the background, * you should not modify the object after it has been passed. * </p> * * @param object The object to add. * @param objectID Identifier that you want to assign this object. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request addObjectAsync(final @NonNull JSONObject object, final @NonNull String objectID, CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return addObject(object, objectID); } }.start(); } /** * Add several objects to this index (asynchronously). * * @param objects Objects to add. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request addObjectsAsync(final @NonNull JSONArray objects, CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return addObjects(objects); } }.start(); } /** * Update an object (asynchronously). * * @param object New version of the object to update. * @param objectID Identifier of the object to update. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request saveObjectAsync(final @NonNull JSONObject object, final @NonNull String objectID, CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return saveObject(object, objectID); } }.start(); } /** * Update several objects (asynchronously). * * @param objects Objects to update. Each object must contain an <code>objectID</code> attribute. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request saveObjectsAsync(final @NonNull JSONArray objects, @NonNull CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return saveObjects(objects); } }.start(); } /** * Partially update an object (asynchronously). * * @param partialObject New value/operations for the object. * @param objectID Identifier of object to be updated. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request partialUpdateObjectAsync(final @NonNull JSONObject partialObject, final @NonNull String objectID, CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return partialUpdateObject(partialObject, objectID); } }.start(); } /** * Partially update several objects (asynchronously). * * @param partialObjects New values/operations for the objects. Each object must contain an <code>objectID</code> * attribute. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request partialUpdateObjectsAsync(final @NonNull JSONArray partialObjects, CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return partialUpdateObjects(partialObjects); } }.start(); } /** * Get an object from this index (asynchronously). * * @param objectID Identifier of the object to retrieve. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request getObjectAsync(final @NonNull String objectID, @NonNull CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return getObject(objectID); } }.start(); } /** * Get an object from this index, optionally restricting the retrieved content (asynchronously). * * @param objectID Identifier of the object to retrieve. * @param attributesToRetrieve List of attributes to retrieve. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request getObjectAsync(final @NonNull String objectID, final List<String> attributesToRetrieve, @NonNull CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return getObject(objectID, attributesToRetrieve); } }.start(); } /** * Get several objects from this index (asynchronously). * * @param objectIDs Identifiers of objects to retrieve. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request getObjectsAsync(final @NonNull List<String> objectIDs, @NonNull CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return getObjects(objectIDs); } }.start(); } /** * Wait until the publication of a task on the server (helper). * All server tasks are asynchronous. This method helps you check that a task is published. * * @param taskID Identifier of the task (as returned by the server). * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request waitTaskAsync(final @NonNull String taskID, @NonNull CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return waitTask(taskID); } }.start(); } /** * Delete an object from this index (asynchronously). * * @param objectID Identifier of the object to delete. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request deleteObjectAsync(final @NonNull String objectID, CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return deleteObject(objectID); } }.start(); } /** * Delete several objects from this index (asynchronously). * * @param objectIDs Identifiers of objects to delete. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request deleteObjectsAsync(final @NonNull List<String> objectIDs, CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return deleteObjects(objectIDs); } }.start(); } /** * Delete all objects matching a query (helper). * * @param query The query that objects to delete must match. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request deleteByQueryAsync(@NonNull Query query, CompletionHandler completionHandler) { final Query queryCopy = new Query(query); return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { deleteByQuery(queryCopy); return new JSONObject(); } }.start(); } /** * Get this index's settings (asynchronously). * * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request getSettingsAsync(@NonNull CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return getSettings(); } }.start(); } /** * Set this index's settings (asynchronously). * * Please refer to our <a href="https://www.algolia.com/doc/android#index-settings">API documentation</a> for the * list of supported settings. * * @param settings New settings. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request setSettingsAsync(final @NonNull JSONObject settings, CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return setSettings(settings); } }.start(); } /** * Browse all index content (initial call). * This method should be called once to initiate a browse. It will return the first page of results and a cursor, * unless the end of the index has been reached. To retrieve subsequent pages, call `browseFromAsync` with that * cursor. * * @param query The query parameters for the browse. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request browseAsync(@NonNull Query query, @NonNull CompletionHandler completionHandler) { final Query queryCopy = new Query(query); return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return browse(queryCopy); } }.start(); } /** * Browse the index from a cursor. * This method should be called after an initial call to `browseAsync()`. It returns a cursor, unless the end of * the index has been reached. * * @param cursor The cursor of the next page to retrieve. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request browseFromAsync(final @NonNull String cursor, @NonNull CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return browseFrom(cursor); } }.start(); } /** * Clear this index. * * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request clearIndexAsync(CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return clearIndex(); } }.start(); } // ---------------------------------------------------------------------- // Search cache // ---------------------------------------------------------------------- /** * Enable search cache with default parameters */ public void enableSearchCache() { enableSearchCache(ExpiringCache.defaultExpirationTimeout, ExpiringCache.defaultMaxSize); } /** * Enable search cache with custom parameters * * @param timeoutInSeconds duration during which an request is kept in cache * @param maxRequests maximum amount of requests to keep before removing the least recently used */ public void enableSearchCache(int timeoutInSeconds, int maxRequests) { isCacheEnabled = true; searchCache = new ExpiringCache<>(timeoutInSeconds, maxRequests); } /** * Disable and reset cache */ public void disableSearchCache() { isCacheEnabled = false; if (searchCache != null) { searchCache.reset(); } } /** * Remove all entries from cache */ public void clearSearchCache() { if (searchCache != null) { searchCache.reset(); } } // ---------------------------------------------------------------------- // Internal operations // ---------------------------------------------------------------------- /** * Add an object in this index * * @param obj the object to add. * @throws AlgoliaException */ protected JSONObject addObject(JSONObject obj) throws AlgoliaException { return client.postRequest("/1/indexes/" + encodedIndexName, obj.toString(), false); } /** * Add an object in this index * * @param obj the object to add. * @param objectID an objectID you want to attribute to this object * (if the attribute already exist the old object will be overwrite) * @throws AlgoliaException */ protected JSONObject addObject(JSONObject obj, String objectID) throws AlgoliaException { try { return client.putRequest("/1/indexes/" + encodedIndexName + "/" + URLEncoder.encode(objectID, "UTF-8"), obj.toString()); } catch (UnsupportedEncodingException e) { throw new AlgoliaException(e.getMessage()); } } /** * Custom batch * * @param actions the array of actions * @throws AlgoliaException */ protected JSONObject batch(JSONArray actions) throws AlgoliaException { try { JSONObject content = new JSONObject(); content.put("requests", actions); return client.postRequest("/1/indexes/" + encodedIndexName + "/batch", content.toString(), false); } catch (JSONException e) { throw new AlgoliaException(e.getMessage()); } } /** * Add several objects * * @param inputArray contains an array of objects to add. * @throws AlgoliaException */ protected JSONObject addObjects(JSONArray inputArray) throws AlgoliaException { try { JSONArray array = new JSONArray(); for (int n = 0; n < inputArray.length(); n++) { JSONObject action = new JSONObject(); action.put("action", "addObject"); action.put("body", inputArray.getJSONObject(n)); array.put(action); } return batch(array); } catch (JSONException e) { throw new AlgoliaException(e.getMessage()); } } /** * Get an object from this index * * @param objectID the unique identifier of the object to retrieve * @throws AlgoliaException */ protected JSONObject getObject(String objectID) throws AlgoliaException { try { return client.getRequest("/1/indexes/" + encodedIndexName + "/" + URLEncoder.encode(objectID, "UTF-8"), false); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } /** * Get an object from this index * * @param objectID the unique identifier of the object to retrieve * @param attributesToRetrieve contains the list of attributes to retrieve. * @throws AlgoliaException */ protected JSONObject getObject(String objectID, List<String> attributesToRetrieve) throws AlgoliaException { try { StringBuilder params = new StringBuilder(); params.append("?attributes="); for (int i = 0; i < attributesToRetrieve.size(); ++i) { if (i > 0) { params.append(","); } params.append(URLEncoder.encode(attributesToRetrieve.get(i), "UTF-8")); } return client.getRequest("/1/indexes/" + encodedIndexName + "/" + URLEncoder.encode(objectID, "UTF-8") + params.toString(), false); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } /** * Get several objects from this index * * @param objectIDs the array of unique identifier of objects to retrieve * @throws AlgoliaException */ protected JSONObject getObjects(List<String> objectIDs) throws AlgoliaException { try { JSONArray requests = new JSONArray(); for (String id : objectIDs) { JSONObject request = new JSONObject(); request.put("indexName", this.indexName); request.put("objectID", id); requests.put(request); } JSONObject body = new JSONObject(); body.put("requests", requests); return client.postRequest("/1/indexes/*/objects", body.toString(), true); } catch (JSONException e) { throw new AlgoliaException(e.getMessage()); } } /** * Update partially an object (only update attributes passed in argument) * * @param partialObject the object attributes to override * @throws AlgoliaException */ protected JSONObject partialUpdateObject(JSONObject partialObject, String objectID) throws AlgoliaException { try { return client.postRequest("/1/indexes/" + encodedIndexName + "/" + URLEncoder.encode(objectID, "UTF-8") + "/partial", partialObject.toString(), false); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } /** * Partially Override the content of several objects * * @param inputArray the array of objects to update (each object must contains an objectID attribute) * @throws AlgoliaException */ protected JSONObject partialUpdateObjects(JSONArray inputArray) throws AlgoliaException { try { JSONArray array = new JSONArray(); for (int n = 0; n < inputArray.length(); n++) { JSONObject obj = inputArray.getJSONObject(n); JSONObject action = new JSONObject(); action.put("action", "partialUpdateObject"); action.put("objectID", obj.getString("objectID")); action.put("body", obj); array.put(action); } return batch(array); } catch (JSONException e) { throw new AlgoliaException(e.getMessage()); } } /** * Override the content of object * * @param object the object to save * @throws AlgoliaException */ protected JSONObject saveObject(JSONObject object, String objectID) throws AlgoliaException { try { return client.putRequest("/1/indexes/" + encodedIndexName + "/" + URLEncoder.encode(objectID, "UTF-8"), object.toString()); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } /** * Override the content of several objects * * @param inputArray contains an array of objects to update (each object must contains an objectID attribute) * @throws AlgoliaException */ protected JSONObject saveObjects(JSONArray inputArray) throws AlgoliaException { try { JSONArray array = new JSONArray(); for (int n = 0; n < inputArray.length(); n++) { JSONObject obj = inputArray.getJSONObject(n); JSONObject action = new JSONObject(); action.put("action", "updateObject"); action.put("objectID", obj.getString("objectID")); action.put("body", obj); array.put(action); } return batch(array); } catch (JSONException e) { throw new AlgoliaException(e.getMessage()); } } /** * Delete an object from the index * * @param objectID the unique identifier of object to delete * @throws AlgoliaException */ protected JSONObject deleteObject(String objectID) throws AlgoliaException { if (objectID.length() == 0) { throw new AlgoliaException("Invalid objectID"); } try { return client.deleteRequest("/1/indexes/" + encodedIndexName + "/" + URLEncoder.encode(objectID, "UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } /** * Delete several objects * * @param objects the array of objectIDs to delete * @throws AlgoliaException */ protected JSONObject deleteObjects(List<String> objects) throws AlgoliaException { try { JSONArray array = new JSONArray(); for (String id : objects) { JSONObject obj = new JSONObject(); obj.put("objectID", id); JSONObject action = new JSONObject(); action.put("action", "deleteObject"); action.put("body", obj); array.put(action); } return batch(array); } catch (JSONException e) { throw new AlgoliaException(e.getMessage()); } } /** * Delete all objects matching a query * * @param query the query string * @throws AlgoliaException */ protected void deleteByQuery(@NonNull Query query) throws AlgoliaException { try { boolean hasMore; do { // Browse index for the next batch of objects. // WARNING: Since deletion invalidates cursors, we always browse from the start. List<String> objectIDs = new ArrayList<>(1000); JSONObject content = browse(query); JSONArray hits = content.getJSONArray("hits"); for (int i = 0; i < hits.length(); ++i) { JSONObject hit = hits.getJSONObject(i); objectIDs.add(hit.getString("objectID")); } hasMore = content.optString("cursor", null) != null; // Delete objects. JSONObject task = this.deleteObjects(objectIDs); this.waitTask(task.getString("taskID")); } while (hasMore); } catch (JSONException e) { throw new AlgoliaException(e.getMessage()); } } /** * Search inside the index * * @return a JSONObject containing search results * @throws AlgoliaException */ protected JSONObject search(@NonNull Query query) throws AlgoliaException { String cacheKey = null; byte[] rawResponse = null; if (isCacheEnabled) { cacheKey = query.build(); rawResponse = searchCache.get(cacheKey); } try { if (rawResponse == null) { rawResponse = searchRaw(query); if (isCacheEnabled) { searchCache.put(cacheKey, rawResponse); } } return Client._getJSONObject(rawResponse); } catch (UnsupportedEncodingException | JSONException e) { throw new AlgoliaException(e.getMessage()); } } /** * Search inside the index * * @return a byte array containing search results * @throws AlgoliaException */ protected byte[] searchRaw(@NonNull Query query) throws AlgoliaException { try { String paramsString = query.build(); if (paramsString.length() > 0) { JSONObject body = new JSONObject(); body.put("params", paramsString); return client.postRequestRaw("/1/indexes/" + encodedIndexName + "/query", body.toString(), true); } else { return client.getRequestRaw("/1/indexes/" + encodedIndexName, true); } } catch (JSONException e) { throw new RuntimeException(e); // should never happen } } /** * Wait the publication of a task on the server. * All server task are asynchronous and you can check with this method that the task is published. * * @param taskID the id of the task returned by server * @param timeToWait time to sleep seed * @throws AlgoliaException */ protected JSONObject waitTask(String taskID, long timeToWait) throws AlgoliaException { try { while (true) { JSONObject obj = client.getRequest("/1/indexes/" + encodedIndexName + "/task/" + URLEncoder.encode(taskID, "UTF-8"), false); if (obj.getString("status").equals("published")) { return obj; } try { Thread.sleep(timeToWait >= MAX_TIME_MS_TO_WAIT ? MAX_TIME_MS_TO_WAIT : timeToWait); } catch (InterruptedException e) { continue; } timeToWait *= 2; } } catch (JSONException e) { throw new AlgoliaException(e.getMessage()); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } /** * Wait the publication of a task on the server. * All server task are asynchronous and you can check with this method that the task is published. * * @param taskID the id of the task returned by server * @throws AlgoliaException */ protected JSONObject waitTask(String taskID) throws AlgoliaException { return waitTask(taskID, MAX_TIME_MS_TO_WAIT); } /** * Get settings of this index * * @throws AlgoliaException */ protected JSONObject getSettings() throws AlgoliaException { return client.getRequest("/1/indexes/" + encodedIndexName + "/settings", false); } /** * Set settings for this index, not forwarding to slave indices. * * @param settings the settings object. * @throws AlgoliaException */ protected JSONObject setSettings(JSONObject settings) throws AlgoliaException { return setSettings(settings, false); } /** * Set settings for this index. * * @param settings the settings object. * @param forwardToSlaves if true, the new settings will be forwarded to slave indices. * @throws AlgoliaException */ protected JSONObject setSettings(JSONObject settings, boolean forwardToSlaves) throws AlgoliaException { final String url = "/1/indexes/" + encodedIndexName + "/settings" + "?forwardToSlaves=" + forwardToSlaves; return client.putRequest(url, settings.toString()); } /** * Delete the index content without removing settings and index specific API keys. * * @throws AlgoliaException */ protected JSONObject clearIndex() throws AlgoliaException { return client.postRequest("/1/indexes/" + encodedIndexName + "/clear", "", false); } /** * Filter disjunctive refinements from generic refinements and a list of disjunctive facets. * * @param disjunctiveFacets the array of disjunctive facets * @param refinements Map representing the current refinements * @return The disjunctive refinements */ private @NonNull Map<String, List<String>> computeDisjunctiveRefinements(@NonNull List<String> disjunctiveFacets, @NonNull Map<String, List<String>> refinements) { Map<String, List<String>> disjunctiveRefinements = new HashMap<>(); for (Map.Entry<String, List<String>> elt : refinements.entrySet()) { if (disjunctiveFacets.contains(elt.getKey())) { disjunctiveRefinements.put(elt.getKey(), elt.getValue()); } } return disjunctiveRefinements; } /** * Compute the queries to run to implement disjunctive faceting. * * @param query The query. * @param disjunctiveFacets List of disjunctive facets. * @param refinements The current refinements, mapping facet names to a list of values. * @return A list of queries suitable for {@link Index#multipleQueries}. */ private @NonNull List<Query> computeDisjunctiveFacetingQueries(@NonNull Query query, @NonNull List<String> disjunctiveFacets, @NonNull Map<String, List<String>> refinements) { // Retain only refinements corresponding to the disjunctive facets. Map<String, List<String>> disjunctiveRefinements = computeDisjunctiveRefinements(disjunctiveFacets, refinements); // build queries List<Query> queries = new ArrayList<>(); // hits + regular facets query JSONArray filters = new JSONArray(); for (Map.Entry<String, List<String>> elt : refinements.entrySet()) { JSONArray or = new JSONArray(); final boolean isDisjunctiveFacet = disjunctiveRefinements.containsKey(elt.getKey()); for (String val : elt.getValue()) { if (isDisjunctiveFacet) { // disjunctive refinements are ORed or.put(String.format("%s:%s", elt.getKey(), val)); } else { filters.put(String.format("%s:%s", elt.getKey(), val)); } } // Add or if (isDisjunctiveFacet) { filters.put(or); } } queries.add(new Query(query).setFacetFilters(filters)); // one query per disjunctive facet (use all refinements but the current one + hitsPerPage=1 + single facet for (String disjunctiveFacet : disjunctiveFacets) { filters = new JSONArray(); for (Map.Entry<String, List<String>> elt : refinements.entrySet()) { if (disjunctiveFacet.equals(elt.getKey())) { continue; } JSONArray or = new JSONArray(); final boolean isDisjunctiveFacet = disjunctiveRefinements.containsKey(elt.getKey()); for (String val : elt.getValue()) { if (isDisjunctiveFacet) { // disjunctive refinements are ORed or.put(String.format("%s:%s", elt.getKey(), val)); } else { filters.put(String.format("%s:%s", elt.getKey(), val)); } } // Add or if (isDisjunctiveFacet) { filters.put(or); } } String[] facets = new String[]{disjunctiveFacet}; queries.add(new Query(query).setHitsPerPage(0).setAnalytics(false) .setAttributesToRetrieve().setAttributesToHighlight().setAttributesToSnippet() .setFacets(facets).setFacetFilters(filters)); } return queries; } /** * Aggregate results from multiple queries into disjunctive faceting results. * * @param answers The response from the multiple queries. * @param disjunctiveFacets List of disjunctive facets. * @param refinements Facet refinements. * @return The aggregated results. * @throws AlgoliaException */ JSONObject aggregateDisjunctiveFacetingResults(@NonNull JSONObject answers, @NonNull List<String> disjunctiveFacets, @NonNull Map<String, List<String>> refinements) throws AlgoliaException { Map<String, List<String>> disjunctiveRefinements = computeDisjunctiveRefinements(disjunctiveFacets, refinements); // aggregate answers // first answer stores the hits + regular facets try { boolean nonExhaustiveFacetsCount = false; JSONArray results = answers.getJSONArray("results"); JSONObject aggregatedAnswer = results.getJSONObject(0); JSONObject disjunctiveFacetsJSON = new JSONObject(); for (int i = 1; i < results.length(); ++i) { if (!results.getJSONObject(i).optBoolean("exhaustiveFacetsCount")) { nonExhaustiveFacetsCount = true; } JSONObject facets = results.getJSONObject(i).getJSONObject("facets"); @SuppressWarnings("unchecked") Iterator<String> keys = facets.keys(); while (keys.hasNext()) { String key = keys.next(); // Add the facet to the disjunctive facet hash disjunctiveFacetsJSON.put(key, facets.getJSONObject(key)); // concatenate missing refinements if (!disjunctiveRefinements.containsKey(key)) { continue; } for (String refine : disjunctiveRefinements.get(key)) { if (!disjunctiveFacetsJSON.getJSONObject(key).has(refine)) { disjunctiveFacetsJSON.getJSONObject(key).put(refine, 0); } } } } aggregatedAnswer.put("disjunctiveFacets", disjunctiveFacetsJSON); if (nonExhaustiveFacetsCount) { aggregatedAnswer.put("exhaustiveFacetsCount", false); } return aggregatedAnswer; } catch (JSONException e) { throw new AlgoliaException("Failed to aggregate results", e); } } protected JSONObject browse(@NonNull Query query) throws AlgoliaException { return client.getRequest("/1/indexes/" + encodedIndexName + "/browse?" + query.build(), true); } protected JSONObject browseFrom(@NonNull String cursor) throws AlgoliaException { try { return client.getRequest("/1/indexes/" + encodedIndexName + "/browse?cursor=" + URLEncoder.encode(cursor, "UTF-8"), true); } catch (UnsupportedEncodingException e) { throw new Error(e); // Should never happen: UTF-8 is always supported. } } /** * Run multiple queries on this index with one API call. * A variant of {@link Client#multipleQueries(List, String)} where all queries target this index. * * @param queries Queries to run. * @param strategy Strategy to use. * @return The JSON results returned by the server. * @throws AlgoliaException */ protected JSONObject multipleQueries(@NonNull List<Query> queries, String strategy) throws AlgoliaException { List<IndexQuery> requests = new ArrayList<>(queries.size()); for (Query query : queries) { requests.add(new IndexQuery(this, query)); } return client.multipleQueries(requests, strategy); } }
algoliasearch/src/main/java/com/algolia/search/saas/Index.java
/* * Copyright (c) 2015 Algolia * http://www.algolia.com/ * * 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. */ package com.algolia.search.saas; import android.support.annotation.NonNull; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * A proxy to an Algolia index. * <p> * You cannot construct this class directly. Please use {@link Client#initIndex(String)} to obtain an instance. * </p> * <p> * WARNING: For performance reasons, arguments to asynchronous methods are not cloned. Therefore, you should not * modify mutable arguments after they have been passed (unless explicitly noted). * </p> */ public class Index { /** The client to which this index belongs. */ private Client client; /** This index's name. */ private String indexName; /** This index's name, URL-encoded. Cached for optimization. */ private String encodedIndexName; private ExpiringCache<String, byte[]> searchCache; private boolean isCacheEnabled = false; // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final long MAX_TIME_MS_TO_WAIT = 10000L; // ---------------------------------------------------------------------- // Initialization // ---------------------------------------------------------------------- protected Index(@NonNull Client client, @NonNull String indexName) { try { this.client = client; this.encodedIndexName = URLEncoder.encode(indexName, "UTF-8"); this.indexName = indexName; } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); // should never happen, as UTF-8 is always supported } } // ---------------------------------------------------------------------- // Accessors // ---------------------------------------------------------------------- @Override public String toString() { return String.format("%s{%s}", this.getClass().getSimpleName(), getIndexName()); } public String getIndexName() { return indexName; } public Client getClient() { return client; } protected String getEncodedIndexName() { return encodedIndexName; } // ---------------------------------------------------------------------- // Public operations // ---------------------------------------------------------------------- /** * Search inside this index (asynchronously). * * @param query Search parameters. May be null to use an empty query. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request searchAsync(@NonNull Query query, @NonNull CompletionHandler completionHandler) { final Query queryCopy = new Query(query); return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return search(queryCopy); } }.start(); } /** * Search inside this index (synchronously). * * @return Search results. */ public JSONObject searchSync(@NonNull Query query) throws AlgoliaException { return search(query); } /** * Run multiple queries on this index with one API call. * A variant of {@link Client#multipleQueriesAsync(List, Client.MultipleQueriesStrategy, CompletionHandler)} * where the targeted index is always the receiver. * * @param queries The queries to run. * @param strategy The strategy to use. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request multipleQueriesAsync(final @NonNull List<Query> queries, final Client.MultipleQueriesStrategy strategy, @NonNull CompletionHandler completionHandler) { final List<Query> queriesCopy = new ArrayList<>(queries.size()); for (Query query : queries) { queriesCopy.add(new Query(query)); } return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return multipleQueries(queriesCopy, strategy == null ? null : strategy.toString()); } }.start(); } /** * Search inside this index synchronously. * * @return Search results. */ protected byte[] searchSyncRaw(@NonNull Query query) throws AlgoliaException { return searchRaw(query); } /** * Perform a search with disjunctive facets, generating as many queries as number of disjunctive facets (helper). * * @param query The query. * @param disjunctiveFacets List of disjunctive facets. * @param refinements The current refinements, mapping facet names to a list of values. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request searchDisjunctiveFacetingAsync(@NonNull Query query, @NonNull final List<String> disjunctiveFacets, @NonNull final Map<String, List<String>> refinements, @NonNull final CompletionHandler completionHandler) { final List<Query> queries = computeDisjunctiveFacetingQueries(query, disjunctiveFacets, refinements); return multipleQueriesAsync(queries, null, new CompletionHandler() { @Override public void requestCompleted(JSONObject content, AlgoliaException error) { JSONObject aggregatedResults = null; try { if (content != null) { aggregatedResults = aggregateDisjunctiveFacetingResults(content, disjunctiveFacets, refinements); } } catch (AlgoliaException e) { error = e; } completionHandler.requestCompleted(aggregatedResults, error); } }); } /** * Add an object to this index (asynchronously). * <p> * WARNING: For performance reasons, the arguments are not cloned. Since the method is executed in the background, * you should not modify the object after it has been passed. * </p> * * @param object The object to add. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request addObjectAsync(final @NonNull JSONObject object, CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return addObject(object); } }.start(); } /** * Add an object to this index, assigning it the specified object ID (asynchronously). * If an object already exists with the same object ID, the existing object will be overwritten. * <p> * WARNING: For performance reasons, the arguments are not cloned. Since the method is executed in the background, * you should not modify the object after it has been passed. * </p> * * @param object The object to add. * @param objectID Identifier that you want to assign this object. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request addObjectAsync(final @NonNull JSONObject object, final @NonNull String objectID, CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return addObject(object, objectID); } }.start(); } /** * Add several objects to this index (asynchronously). * * @param objects Objects to add. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request addObjectsAsync(final @NonNull JSONArray objects, CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return addObjects(objects); } }.start(); } /** * Update an object (asynchronously). * * @param object New version of the object to update. * @param objectID Identifier of the object to update. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request saveObjectAsync(final @NonNull JSONObject object, final @NonNull String objectID, CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return saveObject(object, objectID); } }.start(); } /** * Update several objects (asynchronously). * * @param objects Objects to update. Each object must contain an <code>objectID</code> attribute. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request saveObjectsAsync(final @NonNull JSONArray objects, @NonNull CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return saveObjects(objects); } }.start(); } /** * Partially update an object (asynchronously). * * @param partialObject New value/operations for the object. * @param objectID Identifier of object to be updated. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request partialUpdateObjectAsync(final @NonNull JSONObject partialObject, final @NonNull String objectID, CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return partialUpdateObject(partialObject, objectID); } }.start(); } /** * Partially update several objects (asynchronously). * * @param partialObjects New values/operations for the objects. Each object must contain an <code>objectID</code> * attribute. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request partialUpdateObjectsAsync(final @NonNull JSONArray partialObjects, CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return partialUpdateObjects(partialObjects); } }.start(); } /** * Get an object from this index (asynchronously). * * @param objectID Identifier of the object to retrieve. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request getObjectAsync(final @NonNull String objectID, @NonNull CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return getObject(objectID); } }.start(); } /** * Get an object from this index, optionally restricting the retrieved content (asynchronously). * * @param objectID Identifier of the object to retrieve. * @param attributesToRetrieve List of attributes to retrieve. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request getObjectAsync(final @NonNull String objectID, final List<String> attributesToRetrieve, @NonNull CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return getObject(objectID, attributesToRetrieve); } }.start(); } /** * Get several objects from this index (asynchronously). * * @param objectIDs Identifiers of objects to retrieve. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request getObjectsAsync(final @NonNull List<String> objectIDs, @NonNull CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return getObjects(objectIDs); } }.start(); } /** * Wait until the publication of a task on the server (helper). * All server tasks are asynchronous. This method helps you check that a task is published. * * @param taskID Identifier of the task (as returned by the server). * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request waitTaskAsync(final @NonNull String taskID, @NonNull CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return waitTask(taskID); } }.start(); } /** * Delete an object from this index (asynchronously). * * @param objectID Identifier of the object to delete. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request deleteObjectAsync(final @NonNull String objectID, CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return deleteObject(objectID); } }.start(); } /** * Delete several objects from this index (asynchronously). * * @param objectIDs Identifiers of objects to delete. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request deleteObjectsAsync(final @NonNull List<String> objectIDs, CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return deleteObjects(objectIDs); } }.start(); } /** * Delete all objects matching a query (helper). * * @param query The query that objects to delete must match. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request deleteByQueryAsync(@NonNull Query query, CompletionHandler completionHandler) { final Query queryCopy = new Query(query); return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { deleteByQuery(queryCopy); return new JSONObject(); } }.start(); } /** * Get this index's settings (asynchronously). * * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request getSettingsAsync(@NonNull CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return getSettings(); } }.start(); } /** * Set this index's settings (asynchronously). * <p/> * Please refer to our <a href="https://www.algolia.com/doc/android#index-settings">API documentation</a> for the * list of supported settings. * * @param settings New settings. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request setSettingsAsync(final @NonNull JSONObject settings, CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return setSettings(settings); } }.start(); } /** * Browse all index content (initial call). * This method should be called once to initiate a browse. It will return the first page of results and a cursor, * unless the end of the index has been reached. To retrieve subsequent pages, call `browseFromAsync` with that * cursor. * * @param query The query parameters for the browse. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request browseAsync(@NonNull Query query, @NonNull CompletionHandler completionHandler) { final Query queryCopy = new Query(query); return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return browse(queryCopy); } }.start(); } /** * Browse the index from a cursor. * This method should be called after an initial call to `browseAsync()`. It returns a cursor, unless the end of * the index has been reached. * * @param cursor The cursor of the next page to retrieve. * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request browseFromAsync(final @NonNull String cursor, @NonNull CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return browseFrom(cursor); } }.start(); } /** * Clear this index. * * @param completionHandler The listener that will be notified of the request's outcome. * @return A cancellable request. */ public Request clearIndexAsync(CompletionHandler completionHandler) { return getClient().new AsyncTaskRequest(completionHandler) { @NonNull @Override JSONObject run() throws AlgoliaException { return clearIndex(); } }.start(); } // ---------------------------------------------------------------------- // Search cache // ---------------------------------------------------------------------- /** * Enable search cache with default parameters */ public void enableSearchCache() { enableSearchCache(ExpiringCache.defaultExpirationTimeout, ExpiringCache.defaultMaxSize); } /** * Enable search cache with custom parameters * * @param timeoutInSeconds duration during which an request is kept in cache * @param maxRequests maximum amount of requests to keep before removing the least recently used */ public void enableSearchCache(int timeoutInSeconds, int maxRequests) { isCacheEnabled = true; searchCache = new ExpiringCache<>(timeoutInSeconds, maxRequests); } /** * Disable and reset cache */ public void disableSearchCache() { isCacheEnabled = false; if (searchCache != null) { searchCache.reset(); } } /** * Remove all entries from cache */ public void clearSearchCache() { if (searchCache != null) { searchCache.reset(); } } // ---------------------------------------------------------------------- // Internal operations // ---------------------------------------------------------------------- /** * Add an object in this index * * @param obj the object to add. * @throws AlgoliaException */ protected JSONObject addObject(JSONObject obj) throws AlgoliaException { return client.postRequest("/1/indexes/" + encodedIndexName, obj.toString(), false); } /** * Add an object in this index * * @param obj the object to add. * @param objectID an objectID you want to attribute to this object * (if the attribute already exist the old object will be overwrite) * @throws AlgoliaException */ protected JSONObject addObject(JSONObject obj, String objectID) throws AlgoliaException { try { return client.putRequest("/1/indexes/" + encodedIndexName + "/" + URLEncoder.encode(objectID, "UTF-8"), obj.toString()); } catch (UnsupportedEncodingException e) { throw new AlgoliaException(e.getMessage()); } } /** * Custom batch * * @param actions the array of actions * @throws AlgoliaException */ protected JSONObject batch(JSONArray actions) throws AlgoliaException { try { JSONObject content = new JSONObject(); content.put("requests", actions); return client.postRequest("/1/indexes/" + encodedIndexName + "/batch", content.toString(), false); } catch (JSONException e) { throw new AlgoliaException(e.getMessage()); } } /** * Add several objects * * @param inputArray contains an array of objects to add. * @throws AlgoliaException */ protected JSONObject addObjects(JSONArray inputArray) throws AlgoliaException { try { JSONArray array = new JSONArray(); for (int n = 0; n < inputArray.length(); n++) { JSONObject action = new JSONObject(); action.put("action", "addObject"); action.put("body", inputArray.getJSONObject(n)); array.put(action); } return batch(array); } catch (JSONException e) { throw new AlgoliaException(e.getMessage()); } } /** * Get an object from this index * * @param objectID the unique identifier of the object to retrieve * @throws AlgoliaException */ protected JSONObject getObject(String objectID) throws AlgoliaException { try { return client.getRequest("/1/indexes/" + encodedIndexName + "/" + URLEncoder.encode(objectID, "UTF-8"), false); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } /** * Get an object from this index * * @param objectID the unique identifier of the object to retrieve * @param attributesToRetrieve contains the list of attributes to retrieve. * @throws AlgoliaException */ protected JSONObject getObject(String objectID, List<String> attributesToRetrieve) throws AlgoliaException { try { StringBuilder params = new StringBuilder(); params.append("?attributes="); for (int i = 0; i < attributesToRetrieve.size(); ++i) { if (i > 0) { params.append(","); } params.append(URLEncoder.encode(attributesToRetrieve.get(i), "UTF-8")); } return client.getRequest("/1/indexes/" + encodedIndexName + "/" + URLEncoder.encode(objectID, "UTF-8") + params.toString(), false); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } /** * Get several objects from this index * * @param objectIDs the array of unique identifier of objects to retrieve * @throws AlgoliaException */ protected JSONObject getObjects(List<String> objectIDs) throws AlgoliaException { try { JSONArray requests = new JSONArray(); for (String id : objectIDs) { JSONObject request = new JSONObject(); request.put("indexName", this.indexName); request.put("objectID", id); requests.put(request); } JSONObject body = new JSONObject(); body.put("requests", requests); return client.postRequest("/1/indexes/*/objects", body.toString(), true); } catch (JSONException e) { throw new AlgoliaException(e.getMessage()); } } /** * Update partially an object (only update attributes passed in argument) * * @param partialObject the object attributes to override * @throws AlgoliaException */ protected JSONObject partialUpdateObject(JSONObject partialObject, String objectID) throws AlgoliaException { try { return client.postRequest("/1/indexes/" + encodedIndexName + "/" + URLEncoder.encode(objectID, "UTF-8") + "/partial", partialObject.toString(), false); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } /** * Partially Override the content of several objects * * @param inputArray the array of objects to update (each object must contains an objectID attribute) * @throws AlgoliaException */ protected JSONObject partialUpdateObjects(JSONArray inputArray) throws AlgoliaException { try { JSONArray array = new JSONArray(); for (int n = 0; n < inputArray.length(); n++) { JSONObject obj = inputArray.getJSONObject(n); JSONObject action = new JSONObject(); action.put("action", "partialUpdateObject"); action.put("objectID", obj.getString("objectID")); action.put("body", obj); array.put(action); } return batch(array); } catch (JSONException e) { throw new AlgoliaException(e.getMessage()); } } /** * Override the content of object * * @param object the object to save * @throws AlgoliaException */ protected JSONObject saveObject(JSONObject object, String objectID) throws AlgoliaException { try { return client.putRequest("/1/indexes/" + encodedIndexName + "/" + URLEncoder.encode(objectID, "UTF-8"), object.toString()); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } /** * Override the content of several objects * * @param inputArray contains an array of objects to update (each object must contains an objectID attribute) * @throws AlgoliaException */ protected JSONObject saveObjects(JSONArray inputArray) throws AlgoliaException { try { JSONArray array = new JSONArray(); for (int n = 0; n < inputArray.length(); n++) { JSONObject obj = inputArray.getJSONObject(n); JSONObject action = new JSONObject(); action.put("action", "updateObject"); action.put("objectID", obj.getString("objectID")); action.put("body", obj); array.put(action); } return batch(array); } catch (JSONException e) { throw new AlgoliaException(e.getMessage()); } } /** * Delete an object from the index * * @param objectID the unique identifier of object to delete * @throws AlgoliaException */ protected JSONObject deleteObject(String objectID) throws AlgoliaException { if (objectID.length() == 0) { throw new AlgoliaException("Invalid objectID"); } try { return client.deleteRequest("/1/indexes/" + encodedIndexName + "/" + URLEncoder.encode(objectID, "UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } /** * Delete several objects * * @param objects the array of objectIDs to delete * @throws AlgoliaException */ protected JSONObject deleteObjects(List<String> objects) throws AlgoliaException { try { JSONArray array = new JSONArray(); for (String id : objects) { JSONObject obj = new JSONObject(); obj.put("objectID", id); JSONObject action = new JSONObject(); action.put("action", "deleteObject"); action.put("body", obj); array.put(action); } return batch(array); } catch (JSONException e) { throw new AlgoliaException(e.getMessage()); } } /** * Delete all objects matching a query * * @param query the query string * @throws AlgoliaException */ protected void deleteByQuery(@NonNull Query query) throws AlgoliaException { try { boolean hasMore; do { // Browse index for the next batch of objects. // WARNING: Since deletion invalidates cursors, we always browse from the start. List<String> objectIDs = new ArrayList<>(1000); JSONObject content = browse(query); JSONArray hits = content.getJSONArray("hits"); for (int i = 0; i < hits.length(); ++i) { JSONObject hit = hits.getJSONObject(i); objectIDs.add(hit.getString("objectID")); } hasMore = content.optString("cursor", null) != null; // Delete objects. JSONObject task = this.deleteObjects(objectIDs); this.waitTask(task.getString("taskID")); } while (hasMore); } catch (JSONException e) { throw new AlgoliaException(e.getMessage()); } } /** * Search inside the index * * @return a JSONObject containing search results * @throws AlgoliaException */ protected JSONObject search(@NonNull Query query) throws AlgoliaException { String cacheKey = null; byte[] rawResponse = null; if (isCacheEnabled) { cacheKey = query.build(); rawResponse = searchCache.get(cacheKey); } try { if (rawResponse == null) { rawResponse = searchRaw(query); if (isCacheEnabled) { searchCache.put(cacheKey, rawResponse); } } return Client._getJSONObject(rawResponse); } catch (UnsupportedEncodingException | JSONException e) { throw new AlgoliaException(e.getMessage()); } } /** * Search inside the index * * @return a byte array containing search results * @throws AlgoliaException */ protected byte[] searchRaw(@NonNull Query query) throws AlgoliaException { try { String paramsString = query.build(); if (paramsString.length() > 0) { JSONObject body = new JSONObject(); body.put("params", paramsString); return client.postRequestRaw("/1/indexes/" + encodedIndexName + "/query", body.toString(), true); } else { return client.getRequestRaw("/1/indexes/" + encodedIndexName, true); } } catch (JSONException e) { throw new RuntimeException(e); // should never happen } } /** * Wait the publication of a task on the server. * All server task are asynchronous and you can check with this method that the task is published. * * @param taskID the id of the task returned by server * @param timeToWait time to sleep seed * @throws AlgoliaException */ protected JSONObject waitTask(String taskID, long timeToWait) throws AlgoliaException { try { while (true) { JSONObject obj = client.getRequest("/1/indexes/" + encodedIndexName + "/task/" + URLEncoder.encode(taskID, "UTF-8"), false); if (obj.getString("status").equals("published")) { return obj; } try { Thread.sleep(timeToWait >= MAX_TIME_MS_TO_WAIT ? MAX_TIME_MS_TO_WAIT : timeToWait); } catch (InterruptedException e) { continue; } timeToWait *= 2; } } catch (JSONException e) { throw new AlgoliaException(e.getMessage()); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } /** * Wait the publication of a task on the server. * All server task are asynchronous and you can check with this method that the task is published. * * @param taskID the id of the task returned by server * @throws AlgoliaException */ protected JSONObject waitTask(String taskID) throws AlgoliaException { return waitTask(taskID, MAX_TIME_MS_TO_WAIT); } /** * Get settings of this index * * @throws AlgoliaException */ protected JSONObject getSettings() throws AlgoliaException { return client.getRequest("/1/indexes/" + encodedIndexName + "/settings", false); } /** * Set settings for this index, not forwarding to slave indices. * * @param settings the settings object. * @throws AlgoliaException */ protected JSONObject setSettings(JSONObject settings) throws AlgoliaException { return setSettings(settings, false); } /** * Set settings for this index. * * @param settings the settings object. * @param forwardToSlaves if true, the new settings will be forwarded to slave indices. * @throws AlgoliaException */ protected JSONObject setSettings(JSONObject settings, boolean forwardToSlaves) throws AlgoliaException { final String url = "/1/indexes/" + encodedIndexName + "/settings" + "?forwardToSlaves=" + forwardToSlaves; return client.putRequest(url, settings.toString()); } /** * Delete the index content without removing settings and index specific API keys. * * @throws AlgoliaException */ protected JSONObject clearIndex() throws AlgoliaException { return client.postRequest("/1/indexes/" + encodedIndexName + "/clear", "", false); } /** * Filter disjunctive refinements from generic refinements and a list of disjunctive facets. * * @param disjunctiveFacets the array of disjunctive facets * @param refinements Map representing the current refinements * @return The disjunctive refinements */ private @NonNull Map<String, List<String>> computeDisjunctiveRefinements(@NonNull List<String> disjunctiveFacets, @NonNull Map<String, List<String>> refinements) { Map<String, List<String>> disjunctiveRefinements = new HashMap<>(); for (Map.Entry<String, List<String>> elt : refinements.entrySet()) { if (disjunctiveFacets.contains(elt.getKey())) { disjunctiveRefinements.put(elt.getKey(), elt.getValue()); } } return disjunctiveRefinements; } /** * Compute the queries to run to implement disjunctive faceting. * * @param query The query. * @param disjunctiveFacets List of disjunctive facets. * @param refinements The current refinements, mapping facet names to a list of values. * @return A list of queries suitable for {@link Index#multipleQueries}. */ private @NonNull List<Query> computeDisjunctiveFacetingQueries(@NonNull Query query, @NonNull List<String> disjunctiveFacets, @NonNull Map<String, List<String>> refinements) { // Retain only refinements corresponding to the disjunctive facets. Map<String, List<String>> disjunctiveRefinements = computeDisjunctiveRefinements(disjunctiveFacets, refinements); // build queries List<Query> queries = new ArrayList<>(); // hits + regular facets query JSONArray filters = new JSONArray(); for (Map.Entry<String, List<String>> elt : refinements.entrySet()) { JSONArray or = new JSONArray(); final boolean isDisjunctiveFacet = disjunctiveRefinements.containsKey(elt.getKey()); for (String val : elt.getValue()) { if (isDisjunctiveFacet) { // disjunctive refinements are ORed or.put(String.format("%s:%s", elt.getKey(), val)); } else { filters.put(String.format("%s:%s", elt.getKey(), val)); } } // Add or if (isDisjunctiveFacet) { filters.put(or); } } queries.add(new Query(query).setFacetFilters(filters)); // one query per disjunctive facet (use all refinements but the current one + hitsPerPage=1 + single facet for (String disjunctiveFacet : disjunctiveFacets) { filters = new JSONArray(); for (Map.Entry<String, List<String>> elt : refinements.entrySet()) { if (disjunctiveFacet.equals(elt.getKey())) { continue; } JSONArray or = new JSONArray(); final boolean isDisjunctiveFacet = disjunctiveRefinements.containsKey(elt.getKey()); for (String val : elt.getValue()) { if (isDisjunctiveFacet) { // disjunctive refinements are ORed or.put(String.format("%s:%s", elt.getKey(), val)); } else { filters.put(String.format("%s:%s", elt.getKey(), val)); } } // Add or if (isDisjunctiveFacet) { filters.put(or); } } String[] facets = new String[]{disjunctiveFacet}; queries.add(new Query(query).setHitsPerPage(0).setAnalytics(false) .setAttributesToRetrieve().setAttributesToHighlight().setAttributesToSnippet() .setFacets(facets).setFacetFilters(filters)); } return queries; } /** * Aggregate results from multiple queries into disjunctive faceting results. * * @param answers The response from the multiple queries. * @param disjunctiveFacets List of disjunctive facets. * @param refinements Facet refinements. * @return The aggregated results. * @throws AlgoliaException */ JSONObject aggregateDisjunctiveFacetingResults(@NonNull JSONObject answers, @NonNull List<String> disjunctiveFacets, @NonNull Map<String, List<String>> refinements) throws AlgoliaException { Map<String, List<String>> disjunctiveRefinements = computeDisjunctiveRefinements(disjunctiveFacets, refinements); // aggregate answers // first answer stores the hits + regular facets try { boolean nonExhaustiveFacetsCount = false; JSONArray results = answers.getJSONArray("results"); JSONObject aggregatedAnswer = results.getJSONObject(0); JSONObject disjunctiveFacetsJSON = new JSONObject(); for (int i = 1; i < results.length(); ++i) { if (!results.getJSONObject(i).optBoolean("exhaustiveFacetsCount")) { nonExhaustiveFacetsCount = true; } JSONObject facets = results.getJSONObject(i).getJSONObject("facets"); @SuppressWarnings("unchecked") Iterator<String> keys = facets.keys(); while (keys.hasNext()) { String key = keys.next(); // Add the facet to the disjunctive facet hash disjunctiveFacetsJSON.put(key, facets.getJSONObject(key)); // concatenate missing refinements if (!disjunctiveRefinements.containsKey(key)) { continue; } for (String refine : disjunctiveRefinements.get(key)) { if (!disjunctiveFacetsJSON.getJSONObject(key).has(refine)) { disjunctiveFacetsJSON.getJSONObject(key).put(refine, 0); } } } } aggregatedAnswer.put("disjunctiveFacets", disjunctiveFacetsJSON); if (nonExhaustiveFacetsCount) { aggregatedAnswer.put("exhaustiveFacetsCount", false); } return aggregatedAnswer; } catch (JSONException e) { throw new AlgoliaException("Failed to aggregate results", e); } } protected JSONObject browse(@NonNull Query query) throws AlgoliaException { return client.getRequest("/1/indexes/" + encodedIndexName + "/browse?" + query.build(), true); } protected JSONObject browseFrom(@NonNull String cursor) throws AlgoliaException { try { return client.getRequest("/1/indexes/" + encodedIndexName + "/browse?cursor=" + URLEncoder.encode(cursor, "UTF-8"), true); } catch (UnsupportedEncodingException e) { throw new Error(e); // Should never happen: UTF-8 is always supported. } } /** * Run multiple queries on this index with one API call. * A variant of {@link Client#multipleQueries(List, String)} where all queries target this index. * * @param queries Queries to run. * @param strategy Strategy to use. * @return The JSON results returned by the server. * @throws AlgoliaException */ protected JSONObject multipleQueries(@NonNull List<Query> queries, String strategy) throws AlgoliaException { List<IndexQuery> requests = new ArrayList<>(queries.size()); for (Query query : queries) { requests.add(new IndexQuery(this, query)); } return client.multipleQueries(requests, strategy); } }
Index: Remove self closing tag causing exception on javadoc build task
algoliasearch/src/main/java/com/algolia/search/saas/Index.java
Index: Remove self closing tag causing exception on javadoc build task
<ide><path>lgoliasearch/src/main/java/com/algolia/search/saas/Index.java <ide> <ide> /** <ide> * Set this index's settings (asynchronously). <del> * <p/> <add> * <ide> * Please refer to our <a href="https://www.algolia.com/doc/android#index-settings">API documentation</a> for the <ide> * list of supported settings. <ide> *
JavaScript
apache-2.0
1691a795bd886d6fd1824844337d7ca0451367bf
0
stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var isBuffer = require( '@stdlib/assert/is-buffer' ); var isRegExp = require( '@stdlib/assert/is-regexp' ); var RE_EOL = require( '@stdlib/regexp/eol' ); var reFromString = require( '@stdlib/utils/regexp-from-string' ); var escapeRegExp = require( '@stdlib/utils/escape-regexp-string' ); var replace = require( '@stdlib/string/replace' ); // VARIABLES // // Maximum line number at which a license header should start: var START_THRESHOLD = 4; // RegExp to test if a regular expression has a "global" flag: var RE_GLOBAL_FLAG = /\/.*\/.*g.*$/; // MAIN // /** * Lints a file blob against a specified license header. * * @param {(string|Buffer)} blob - file blob to lint * @param {(string|RegExp)} header - license header against which to lint * @throws {TypeError} first argument must be either a string or Buffer * @throws {TypeError} second argument must be either a string or regular expression * @returns {(Object|null)} lint error or null * * @example * var str = [ * '// This file is licensed under Apache-2.0.', * '', * '"use strict";', * '', * 'var x = 3.14;', * '' * ]; * str = str.join( '\n' ); * * var header = '// This file is licensed under MIT.'; * * var err = lint( str, header ); * // returns {...} */ function lint( blob, header ) { var isStr; var tmp; if ( !isString( blob ) && !isBuffer( blob ) ) { throw new TypeError( 'invalid input argument. First argument must be either a string or Buffer. Value: `' + blob + '`.' ); } isStr = isString( header ); if ( !isStr && !isRegExp( header ) ) { throw new TypeError( 'invalid input argument. Second argument must be either a string or regular expression. Value: `' + header + '`.' ); } blob = blob.toString(); if ( isStr ) { // Convert to a regular expression... header = replace( header, '/', '\\\\/' ); header = reFromString( '/'+escapeRegExp( header )+'/g' ); } else if ( RE_GLOBAL_FLAG.test( header.toString() ) === false ) { // Clone the regular expression to allow checking for multiple headers: header = reFromString( header.toString()+'g' ); } // Check for the presence of a license header: tmp = blob.match( header ); if ( tmp === null ) { return { 'error': 'malformed or missing license header.' }; } // Check for multiple headers in the same file: if ( tmp.length > 1 ) { return { 'error': 'more than 1 license header.' }; } // Check header location... tmp = blob.search( header ); tmp = blob.substring( 0, tmp ); tmp = tmp.split( RE_EOL ).length; if ( tmp > START_THRESHOLD ) { return { 'error': 'license header should appear within the first 5 lines of a file. Starting line: '+(tmp-1)+'.' }; } return null; } // end FUNCTION lint() // EXPORTS // module.exports = lint;
lib/node_modules/@stdlib/_tools/lint/license-header/lib/main.js
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var isBuffer = require( '@stdlib/assert/is-buffer' ); var isRegExp = require( '@stdlib/assert/is-regexp' ); var RE_EOL = require( '@stdlib/regexp/eol' ); var reFromString = require( '@stdlib/utils/regexp-from-string' ); var escapeRegExp = require( '@stdlib/utils/escape-regexp-string' ); var replace = require( '@stdlib/string/replace' ); // VARIABLES // // Maximum line number at which a license header should start: var START_THRESHOLD = 4; // RegExp to test if a regular expression has a "global" flag: var RE_GLOBAL_FLAG = /\/.*\/.*g.*$/; // MAIN // /** * Lints a file blob against a specified license header. * * @param {(string|Buffer)} blob - file blob to lint * @param {(string|RegExp)} header - license header against which to lint * @throws {TypeError} first argument must be either a string or Buffer * @throws {TypeError} second argument must be either a string or regular expression * @returns {(Object|null)} lint error or null * * @example * var str = [ * '// This file is licensed under Apache-2.0.', * '', * '"use strict";', * '', * 'var x = 3.14;', * '' * ]; * str = str.join( '\n' ); * * var header = '// This file is licensed under MIT.'; * * var err = lint( str, header ); * // returns {...} */ function lint( blob, header ) { var isStr; var tmp; if ( !isString( blob ) && !isBuffer( blob ) ) { throw new TypeError( 'invalid input argument. First argument must be either a string or Buffer. Value: `' + blob + '`.' ); } isStr = isString( header ); if ( !isStr && !isRegExp( header ) ) { throw new TypeError( 'invalid input argument. Second argument must be either a string or regular expression. Value: `' + header + '`.' ); } blob = blob.toString(); if ( isStr ) { // Convert to a regular expression... header = replace( header, '/', '\\\\/' ); header = reFromString( '/'+escapeRegExp( header )+'/g' ); } else if ( RE_GLOBAL_FLAG.test( header ) === false ) { // Clone the regular expression to allow checking for multiple headers: header = reFromString( header.toString()+'g' ); } // Check for the presence of a license header: tmp = blob.match( header ); if ( tmp === null ) { return { 'error': 'malformed or missing license header.' }; } // Check for multiple headers in the same file: if ( tmp.length > 1 ) { return { 'error': 'more than 1 license header.' }; } // Check header location... tmp = blob.search( header ); tmp = blob.substring( 0, tmp ); tmp = tmp.split( RE_EOL ).length; if ( tmp > START_THRESHOLD ) { return { 'error': 'license header should appear within the first 5 lines of a file. Starting line: '+(tmp-1)+'.' }; } return null; } // end FUNCTION lint() // EXPORTS // module.exports = lint;
Explicitly call `toString()`
lib/node_modules/@stdlib/_tools/lint/license-header/lib/main.js
Explicitly call `toString()`
<ide><path>ib/node_modules/@stdlib/_tools/lint/license-header/lib/main.js <ide> // Convert to a regular expression... <ide> header = replace( header, '/', '\\\\/' ); <ide> header = reFromString( '/'+escapeRegExp( header )+'/g' ); <del> } else if ( RE_GLOBAL_FLAG.test( header ) === false ) { <add> } else if ( RE_GLOBAL_FLAG.test( header.toString() ) === false ) { <ide> // Clone the regular expression to allow checking for multiple headers: <ide> header = reFromString( header.toString()+'g' ); <ide> }
Java
apache-2.0
af996e6d4fa355150b2b9bbd15882ba6bdf69754
0
dashorst/wicket,selckin/wicket,topicusonderwijs/wicket,topicusonderwijs/wicket,klopfdreh/wicket,AlienQueen/wicket,dashorst/wicket,klopfdreh/wicket,klopfdreh/wicket,mafulafunk/wicket,freiheit-com/wicket,selckin/wicket,aldaris/wicket,aldaris/wicket,bitstorm/wicket,apache/wicket,aldaris/wicket,freiheit-com/wicket,klopfdreh/wicket,zwsong/wicket,selckin/wicket,bitstorm/wicket,dashorst/wicket,aldaris/wicket,zwsong/wicket,mosoft521/wicket,AlienQueen/wicket,martin-g/wicket-osgi,topicusonderwijs/wicket,astrapi69/wicket,mosoft521/wicket,freiheit-com/wicket,bitstorm/wicket,Servoy/wicket,apache/wicket,mafulafunk/wicket,klopfdreh/wicket,martin-g/wicket-osgi,astrapi69/wicket,freiheit-com/wicket,martin-g/wicket-osgi,AlienQueen/wicket,Servoy/wicket,apache/wicket,AlienQueen/wicket,topicusonderwijs/wicket,freiheit-com/wicket,zwsong/wicket,mosoft521/wicket,selckin/wicket,Servoy/wicket,apache/wicket,bitstorm/wicket,topicusonderwijs/wicket,bitstorm/wicket,dashorst/wicket,mosoft521/wicket,apache/wicket,aldaris/wicket,mosoft521/wicket,Servoy/wicket,astrapi69/wicket,dashorst/wicket,Servoy/wicket,mafulafunk/wicket,selckin/wicket,astrapi69/wicket,AlienQueen/wicket,zwsong/wicket
/* * $Id$ $Revision: * 1.5 $ $Date$ * * ============================================================================== * 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 wicket.markup.parser.filter; import java.text.ParseException; import java.util.HashMap; import java.util.Map; import java.util.Stack; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import wicket.markup.ComponentTag; import wicket.markup.MarkupElement; import wicket.markup.MarkupException; import wicket.markup.parser.AbstractMarkupFilter; import wicket.markup.parser.IMarkupFilter; import wicket.markup.parser.XmlTag; /** * This is a markup inline filter. It identifies HTML specific issues which make * HTML not 100% xml compliant. E.g. tags like &lt;p&gt; often are missing the * corresponding close tag. * * @author Juergen Donnerstag */ public final class HtmlHandler extends AbstractMarkupFilter { /** Logging */ private static Log log = LogFactory.getLog(HtmlHandler.class); /** Remember the last tag in order to close specific tags automatically */ private ComponentTag lastTag; /** Tag stack to find balancing tags */ final private Stack stack = new Stack(); /** Map of simple tags. */ private static final Map doesNotRequireCloseTag = new HashMap(); static { // Tags which are allowed not be closed in HTML doesNotRequireCloseTag.put("p", Boolean.TRUE); doesNotRequireCloseTag.put("br", Boolean.TRUE); doesNotRequireCloseTag.put("img", Boolean.TRUE); doesNotRequireCloseTag.put("input", Boolean.TRUE); doesNotRequireCloseTag.put("hr", Boolean.TRUE); doesNotRequireCloseTag.put("link", Boolean.TRUE); doesNotRequireCloseTag.put("meta", Boolean.TRUE); } /** * Construct. * * @param parent * The next MarkupFilter in the chain */ public HtmlHandler(final IMarkupFilter parent) { super(parent); } /** * Get the next MarkupElement from the parent MarkupFilter and handle it if * the specific filter criteria are met. Depending on the filter, it may * return the MarkupElement unchanged, modified or it remove by asking the * parent handler for the next tag. * * @see wicket.markup.parser.IMarkupFilter#nextTag() * @return Return the next eligible MarkupElement */ public MarkupElement nextTag() throws ParseException { // Get the next tag. If null, no more tags are available final ComponentTag tag = (ComponentTag)getParent().nextTag(); if (tag == null) { // No more tags from the markup. // If there's still a non-simple tag left, it's an error while (stack.size() > 0) { final XmlTag top = (XmlTag)stack.peek(); if (!requiresCloseTag(top.getName())) { stack.pop(); } else { throw new ParseException("Tag " + top + " at " + top.getPos() + " did not have a close tag", top.getPos()); } } return tag; } if (log.isDebugEnabled()) { log.debug("tag: " + tag.toUserDebugString() + ", stack: " + stack); } // Check tag type if (tag.isOpen()) { // Push onto stack stack.push(tag); } else if (tag.isClose()) { // Check that there is something on the stack if (stack.size() > 0) { // Pop the top tag off the stack ComponentTag top = (ComponentTag)stack.pop(); // If the name of the current close tag does not match the // tag on the stack // then we may have a mismatched close tag boolean mismatch = !top.getName().equalsIgnoreCase(tag.getName()); if (mismatch) { // Pop any simple tags off the top of the stack while (mismatch && !requiresCloseTag(top.getName())) { // Pop simple tag top = (ComponentTag)stack.pop(); // Does new top of stack mismatch too? mismatch = !top.getName().equalsIgnoreCase(tag.getName()); } // If adjusting for simple tags did not fix the problem, // it must be a real mismatch. if (mismatch) { throw new MarkupException("Tag " + top.toUserDebugString() + " has a mismatched close tag at " + tag.toUserDebugString()); } } // Tag matches, so add pointer to matching tag tag.setOpenTag(top); } else { throw new MarkupException("Tag " + tag.toUserDebugString() + " does not have a matching open tag"); } } else if (tag.isOpenClose()) { // Tag closes itself tag.setOpenTag(tag); } return tag; } /** * Gets whether this tag does not require a closing tag. * * @param name * The tag's name, e.g. a, br, div, etc. * @return True if this tag does not require a closing tag */ public static boolean requiresCloseTag(final String name) { return doesNotRequireCloseTag.get(name) == null; } }
wicket/src/java/wicket/markup/parser/filter/HtmlHandler.java
/* * $Id$ $Revision: * 1.5 $ $Date$ * * ============================================================================== * 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 wicket.markup.parser.filter; import java.text.ParseException; import java.util.HashMap; import java.util.Map; import java.util.Stack; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import wicket.markup.ComponentTag; import wicket.markup.MarkupElement; import wicket.markup.MarkupException; import wicket.markup.parser.AbstractMarkupFilter; import wicket.markup.parser.IMarkupFilter; import wicket.markup.parser.XmlTag; /** * This is a markup inline filter. It identifies HTML specific issues which make * HTML not 100% xml compliant. E.g. tags like &lt;p&gt; often are missing the * corresponding close tag. * * @author Juergen Donnerstag */ public final class HtmlHandler extends AbstractMarkupFilter { /** Logging */ private static Log log = LogFactory.getLog(HtmlHandler.class); /** Remember the last tag in order to close specific tags automatically */ private ComponentTag lastTag; /** Tag stack to find balancing tags */ final private Stack stack = new Stack(); /** Map of simple tags. */ private static final Map doesNotRequireCloseTag = new HashMap(); static { // Tags which are allowed not be closed in HTML doesNotRequireCloseTag.put("p", Boolean.TRUE); doesNotRequireCloseTag.put("br", Boolean.TRUE); doesNotRequireCloseTag.put("img", Boolean.TRUE); doesNotRequireCloseTag.put("input", Boolean.TRUE); doesNotRequireCloseTag.put("hr", Boolean.TRUE); doesNotRequireCloseTag.put("link", Boolean.TRUE); } /** * Construct. * * @param parent * The next MarkupFilter in the chain */ public HtmlHandler(final IMarkupFilter parent) { super(parent); } /** * Get the next MarkupElement from the parent MarkupFilter and handle it if * the specific filter criteria are met. Depending on the filter, it may * return the MarkupElement unchanged, modified or it remove by asking the * parent handler for the next tag. * * @see wicket.markup.parser.IMarkupFilter#nextTag() * @return Return the next eligible MarkupElement */ public MarkupElement nextTag() throws ParseException { // Get the next tag. If null, no more tags are available final ComponentTag tag = (ComponentTag)getParent().nextTag(); if (tag == null) { // No more tags from the markup. // If there's still a non-simple tag left, it's an error while (stack.size() > 0) { final XmlTag top = (XmlTag)stack.peek(); if (!requiresCloseTag(top.getName())) { stack.pop(); } else { throw new ParseException("Tag " + top + " at " + top.getPos() + " did not have a close tag", top.getPos()); } } return tag; } if (log.isDebugEnabled()) { log.debug("tag: " + tag.toUserDebugString() + ", stack: " + stack); } // Check tag type if (tag.isOpen()) { // Push onto stack stack.push(tag); } else if (tag.isClose()) { // Check that there is something on the stack if (stack.size() > 0) { // Pop the top tag off the stack ComponentTag top = (ComponentTag)stack.pop(); // If the name of the current close tag does not match the // tag on the stack // then we may have a mismatched close tag boolean mismatch = !top.getName().equalsIgnoreCase(tag.getName()); if (mismatch) { // Pop any simple tags off the top of the stack while (mismatch && !requiresCloseTag(top.getName())) { // Pop simple tag top = (ComponentTag)stack.pop(); // Does new top of stack mismatch too? mismatch = !top.getName().equalsIgnoreCase(tag.getName()); } // If adjusting for simple tags did not fix the problem, // it must be a real mismatch. if (mismatch) { throw new MarkupException("Tag " + top.toUserDebugString() + " has a mismatched close tag at " + tag.toUserDebugString()); } } // Tag matches, so add pointer to matching tag tag.setOpenTag(top); } else { throw new MarkupException("Tag " + tag.toUserDebugString() + " does not have a matching open tag"); } } else if (tag.isOpenClose()) { // Tag closes itself tag.setOpenTag(tag); } return tag; } /** * Gets whether this tag does not require a closing tag. * * @param name * The tag's name, e.g. a, br, div, etc. * @return True if this tag does not require a closing tag */ public static boolean requiresCloseTag(final String name) { return doesNotRequireCloseTag.get(name) == null; } }
allow non closing of 'meta' tag git-svn-id: ac804e38dcddf5e42ac850d29d9218b7df6087b7@456562 13f79535-47bb-0310-9956-ffa450edef68
wicket/src/java/wicket/markup/parser/filter/HtmlHandler.java
allow non closing of 'meta' tag
<ide><path>icket/src/java/wicket/markup/parser/filter/HtmlHandler.java <ide> doesNotRequireCloseTag.put("input", Boolean.TRUE); <ide> doesNotRequireCloseTag.put("hr", Boolean.TRUE); <ide> doesNotRequireCloseTag.put("link", Boolean.TRUE); <add> doesNotRequireCloseTag.put("meta", Boolean.TRUE); <ide> } <ide> <ide> /**
Java
apache-2.0
8f142ba29fdc067b5ec445253aece75c533d80f2
0
inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service
package org.slc.sli.ingestion.landingzone.validation; import java.io.BufferedReader; import java.io.FileReader; import java.util.Map; import junit.framework.Assert; import org.codehaus.jackson.map.ObjectMapper; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.slc.sli.domain.Entity; import org.slc.sli.ingestion.NeutralRecord; import org.slc.sli.ingestion.NeutralRecordEntity; import org.slc.sli.ingestion.validation.ErrorReport; /** * Tests good and bad sample Avro schemas for Students. * * @author Tom Shewchuk <[email protected]> * */ @Ignore // TODO remove once NeutralSchemaValidator is fully operational @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "/spring/applicationContext-test.xml" }) public class AvroRecordValidatorTest { @Autowired private AvroRecordValidator validator; @SuppressWarnings("unchecked") @Test public void testValidStudent() throws Exception { BufferedReader reader = new BufferedReader(new FileReader("src/test/resources/student_fixture.json")); // Insure each record is valid. String student; int recordNumber = 0; while ((student = reader.readLine()) != null) { ObjectMapper oRead = new ObjectMapper(); Map<String, Object> obj = oRead.readValue(student, Map.class); Assert.assertTrue(mapValidation((Map<String, Object>) obj.get("body"), "student", ++recordNumber)); } } @SuppressWarnings("unchecked") @Test public void testInvalidStudent() throws Exception { BufferedReader reader = new BufferedReader(new FileReader("src/test/resources/bad_student_fixture.json")); // Insure each record is invalid. String student; int recordNumber = 0; while ((student = reader.readLine()) != null) { ObjectMapper oRead = new ObjectMapper(); Map<String, Object> obj = oRead.readValue(student, Map.class); Assert.assertFalse(mapValidation((Map<String, Object>) obj.get("body"), "student", ++recordNumber)); } } private boolean mapValidation(Map<String, Object> obj, String schemaName, int recordNumber) { boolean returnVal; ErrorReport errorReport = new TestErrorReport(); NeutralRecord neutralRecord = new NeutralRecord(); neutralRecord.setAttributes(obj); neutralRecord.setRecordType(schemaName); Entity entity = new NeutralRecordEntity(neutralRecord, recordNumber); returnVal = validator.isValid(entity, errorReport); // Insure each error message is as expected. if (returnVal) { // Record is valid; insure there are no messages. Assert.assertFalse(((TestErrorReport) errorReport).hasErrors()); } else { // Record is invalid; insure messages are as expected. Assert.assertTrue(((TestErrorReport) errorReport).hasErrors()); switch (recordNumber) { case 1: Assert.assertEquals(2, ((TestErrorReport) errorReport).getMessages().size()); Assert.assertEquals("Record 1: Missing or empty field <name.lastSurname>.", ((TestErrorReport) errorReport).getMessages().toArray()[0]); Assert.assertEquals("Record 1: Unknown field <name.lastSurename>.", ((TestErrorReport) errorReport) .getMessages().toArray()[1]); break; case 2: Assert.assertEquals(1, ((TestErrorReport) errorReport).getMessages().size()); Assert.assertEquals( "Record 2: Enumeration mismatch for field <sex> (legal values are [Female, Male]).", ((TestErrorReport) errorReport).getMessages().toArray()[0]); break; case 3: Assert.assertEquals(1, ((TestErrorReport) errorReport).getMessages().size()); Assert.assertEquals("Record 3: Invalid data type for field <name.firstName> (expected String).", ((TestErrorReport) errorReport).getMessages().toArray()[0]); break; default: Assert.fail(); } } return returnVal; } }
sli/ingestion/src/test/java/org/slc/sli/ingestion/landingzone/validation/AvroRecordValidatorTest.java
package org.slc.sli.ingestion.landingzone.validation; import java.io.BufferedReader; import java.io.FileReader; import java.util.Map; import junit.framework.Assert; import org.codehaus.jackson.map.ObjectMapper; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.slc.sli.domain.Entity; import org.slc.sli.ingestion.NeutralRecord; import org.slc.sli.ingestion.NeutralRecordEntity; import org.slc.sli.ingestion.validation.ErrorReport; /** * Tests good and bad sample Avro schemas for Students. * * @author Tom Shewchuk <[email protected]> * */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "/spring/applicationContext-test.xml" }) public class AvroRecordValidatorTest { @Autowired private AvroRecordValidator validator; @SuppressWarnings("unchecked") @Test public void testValidStudent() throws Exception { BufferedReader reader = new BufferedReader(new FileReader("src/test/resources/student_fixture.json")); // Insure each record is valid. String student; int recordNumber = 0; while ((student = reader.readLine()) != null) { ObjectMapper oRead = new ObjectMapper(); Map<String, Object> obj = oRead.readValue(student, Map.class); Assert.assertTrue(mapValidation((Map<String, Object>) obj.get("body"), "student", ++recordNumber)); } } @SuppressWarnings("unchecked") @Test public void testInvalidStudent() throws Exception { BufferedReader reader = new BufferedReader(new FileReader("src/test/resources/bad_student_fixture.json")); // Insure each record is invalid. String student; int recordNumber = 0; while ((student = reader.readLine()) != null) { ObjectMapper oRead = new ObjectMapper(); Map<String, Object> obj = oRead.readValue(student, Map.class); Assert.assertFalse(mapValidation((Map<String, Object>) obj.get("body"), "student", ++recordNumber)); } } private boolean mapValidation(Map<String, Object> obj, String schemaName, int recordNumber) { boolean returnVal; ErrorReport errorReport = new TestErrorReport(); NeutralRecord neutralRecord = new NeutralRecord(); neutralRecord.setAttributes(obj); neutralRecord.setRecordType(schemaName); Entity entity = new NeutralRecordEntity(neutralRecord, recordNumber); returnVal = validator.isValid(entity, errorReport); // Insure each error message is as expected. if (returnVal) { // Record is valid; insure there are no messages. Assert.assertFalse(((TestErrorReport) errorReport).hasErrors()); } else { // Record is invalid; insure messages are as expected. Assert.assertTrue(((TestErrorReport) errorReport).hasErrors()); switch (recordNumber) { case 1: Assert.assertEquals(2, ((TestErrorReport) errorReport).getMessages().size()); Assert.assertEquals("Record 1: Missing or empty field <name.lastSurname>.", ((TestErrorReport) errorReport).getMessages().toArray()[0]); Assert.assertEquals("Record 1: Unknown field <name.lastSurename>.", ((TestErrorReport) errorReport) .getMessages().toArray()[1]); break; case 2: Assert.assertEquals(1, ((TestErrorReport) errorReport).getMessages().size()); Assert.assertEquals( "Record 2: Enumeration mismatch for field <sex> (legal values are [Female, Male]).", ((TestErrorReport) errorReport).getMessages().toArray()[0]); break; case 3: Assert.assertEquals(1, ((TestErrorReport) errorReport).getMessages().size()); Assert.assertEquals("Record 3: Invalid data type for field <name.firstName> (expected String).", ((TestErrorReport) errorReport).getMessages().toArray()[0]); break; default: Assert.fail(); } } return returnVal; } }
temporarily ignore these tests until NeutralSchemaValidator is fully operational
sli/ingestion/src/test/java/org/slc/sli/ingestion/landingzone/validation/AvroRecordValidatorTest.java
temporarily ignore these tests until NeutralSchemaValidator is fully operational
<ide><path>li/ingestion/src/test/java/org/slc/sli/ingestion/landingzone/validation/AvroRecordValidatorTest.java <ide> import junit.framework.Assert; <ide> <ide> import org.codehaus.jackson.map.ObjectMapper; <add>import org.junit.Ignore; <ide> import org.junit.Test; <ide> import org.junit.runner.RunWith; <ide> import org.springframework.beans.factory.annotation.Autowired; <ide> * <ide> */ <ide> <add>@Ignore // TODO remove once NeutralSchemaValidator is fully operational <ide> @RunWith(SpringJUnit4ClassRunner.class) <ide> @ContextConfiguration(locations = { "/spring/applicationContext-test.xml" }) <ide> public class AvroRecordValidatorTest {
JavaScript
bsd-2-clause
f991c7d8f65fd6bf6b5666e83e6b7e85e1ead40e
0
nishant8BITS/node-supervisor,itegebo/node-supervisor,mikemaccana/node-supervisor,komola/node-supervisor,dhm116/node-supervisor,boblauer/node-supervisor,petruisfan/node-supervisor,DocuSignDev/node-supervisor,KamilSzot/node-supervisor,tempbottle/node-supervisor,FokkeZB/node-supervisor,Getahun/node-supervisor,farodin91/node-supervisor,ktmud/node-supervisor,kediacorporation/node-supervisor,duffytilleman/node-supervisor,isaacs/node-supervisor,igoralekseev/node-supervisor,mathieumg/node-supervisor,mx1700/node-supervisor,philpill/node-supervisor
var util = require("util"); var fs = require("fs"); var spawn = require("child_process").spawn; var fileExtensionPattern; var startChildProcess; var noRestartOn = null; var debug = true; exports.run = run; function run (args) { var arg, next, watch, program, programArgs, extensions, executor, poll_interval; while (arg = args.shift()) { if (arg === "--help" || arg === "-h" || arg === "-?") { return help(); } else if (arg === "--quiet" || arg === "-q") { debug = false; util.debug = function(){}; util.puts = function(){}; } else if (arg === "--watch" || arg === "-w") { watch = args.shift(); } else if (arg === "--poll-interval" || arg === "-p") { poll_interval = parseInt(args.shift()); } else if (arg === "--extensions" || arg === "-e") { extensions = args.shift(); } else if (arg === "--exec" || arg === "-x") { executor = args.shift(); } else if (arg === "--no-restart-on" || arg === "-n") { noRestartOn = args.shift(); } else if (arg === "--") { program = args; break; } else if (arg.indexOf("-") && !args.length) { // Assume last arg is the program program = [arg]; } } if (!program) { return help(); } if (!watch) { watch = "."; } if (!poll_interval) { poll_interval = 100; } var programExt = program.join(" ").match(/.*\.(\S*)/); programExt = programExt && programExt[1]; if (!extensions) { // If no extensions passed try to guess from the program extensions = "node|js"; if (programExt && extensions.indexOf(programExt) == -1) extensions += "|" + programExt; } extensions = extensions.replace(/,/g, "|"); fileExtensionPattern = new RegExp("^.*\.(" + extensions + ")$"); if (!executor) { executor = (programExt === "coffee") ? "coffee" : "node"; } util.puts("") util.debug("Running node-supervisor with"); util.debug(" program '" + program.join(" ") + "'"); util.debug(" --watch '" + watch + "'"); util.debug(" --extensions '" + extensions + "'"); util.debug(" --exec '" + executor + "'"); util.puts(""); // store the call to startProgramm in startChildProcess // in order to call it later startChildProcess = function() { startProgram(program, executor, programArgs); }; // if we have a program, then run it, and restart when it crashes. // if we have a watch folder, then watch the folder for changes and restart the prog startChildProcess(); var watchItems = watch.split(','); watchItems.forEach(function (watchItem) { if (!watchItem.match(/^\/.*/)) { // watch is not an absolute path // convert watch item to absolute path watchItem = process.cwd() + '/' + watchItem; } util.debug("Watching directory '" + watchItem + "' for changes."); findAllWatchFiles(watchItem, function(f) { watchGivenFile( f, poll_interval ); }); }); }; function print (m, n) { util.print(m+(!n?"\n":"")); return print; } function help () { print ("") ("Node Supervisor is used to restart programs when they crash.") ("It can also be used to restart programs when a *.js file changes.") ("") ("Usage:") (" supervisor [options] <program>") (" supervisor [options] -- <program> [args ...]") ("") ("Required:") (" <program>") (" The program to run.") ("") ("Options:") (" -w|--watch <watchItems>") (" A comma-delimited list of folders or js files to watch for changes.") (" When a change to a js file occurs, reload the program") (" Default is '.'") ("") (" -p|--poll-interval <milliseconds>") (" How often to poll watched files for changes.") (" Defaults to Node default.") ("") (" -e|--extensions <extensions>") (" Specific file extensions to watch in addition to defaults.") (" Used when --watch option includes folders") (" Default is 'node|js'") ("") (" -x|--exec <executable>") (" The executable that runs the specified program.") (" Default is 'node'") ("") (" -n|--no-restart-on error|exit") (" Don't automatically restart the supervised program if it ends.") (" Supervisor will wait for a change in the source files.") (" If \"error\", an exit code of 0 will still restart.") (" If \"exit\", no restart regardless of exit code.") ("") (" -h|--help|-?") (" Display these usage instructions.") ("") (" -q|--quiet") (" Suppress DEBUG messages") ("") ("Examples:") (" supervisor myapp.js") (" supervisor myapp.coffee") (" supervisor -w scripts -e myext -x myrunner myapp") (" supervisor -- server.js -h host -p port") (""); }; function startProgram (prog, exec) { util.debug("Starting child process with '" + exec + " " + prog.join(" ") + "'"); crash_queued = false; var child = exports.child = spawn(exec, prog); child.stdout.addListener("data", function (chunk) { chunk && util.print(chunk); }); child.stderr.addListener("data", function (chunk) { chunk && util.debug(chunk); }); child.addListener("exit", function (code) { if (!crash_queued) { util.debug("Program " + exec + " " + prog.join(" ") + " exited with code " + code + "\n"); exports.child = null; if (noRestartOn == "exit" || noRestartOn == "error" && code !== 0) return; } startProgram(prog, exec); }); } var timer = null, mtime = null; crash_queued = false; function crash () { if (crash_queued) return; crash_queued = true; var child = exports.child; setTimeout(function() { if (child) { util.debug("crashing child"); process.kill(child.pid); } else { util.debug("restarting child"); startChildProcess(); } }, 50); } function crashWin (event) { if( event === 'change' ) crash(); } function crashOther (oldStat, newStat) { // we only care about modification time, not access time. if ( newStat.mtime.getTime() !== oldStat.mtime.getTime() ) crash(); } var isWindows = process.platform === 'win32'; function watchGivenFile (watch, poll_interval) { if (isWindows) fs.watch(watch, { persistent: true, interval: poll_interval }, crashWin); else fs.watchFile(watch, { persistent: true, interval: poll_interval }, crashOther); } var findAllWatchFiles = function(path, callback) { fs.stat(path, function(err, stats){ if (err) { util.error('Error retrieving stats for file: ' + path); } else if (isWindows) { callback(path); } else { if (stats.isDirectory()) { fs.readdir(path, function(err, fileNames) { if(err) { util.error('Error reading path: ' + path); } else { fileNames.forEach(function (fileName) { findAllWatchFiles(path + '/' + fileName, callback); }); } }); } else { if (path.match(fileExtensionPattern)) { callback(path); } } } }); };
lib/supervisor.js
var util = require("util"); var fs = require("fs"); var spawn = require("child_process").spawn; var fileExtensionPattern; var startChildProcess; var noRestartOn = null; var debug = true; exports.run = run; function run (args) { var arg, next, watch, program, programArgs, extensions, executor, poll_interval; while (arg = args.shift()) { if (arg === "--help" || arg === "-h" || arg === "-?") { return help(); } else if (arg === "--quiet" || arg === "-q") { debug = false; util.debug = function(){}; util.puts = function(){}; } else if (arg === "--watch" || arg === "-w") { watch = args.shift(); } else if (arg === "--poll-interval" || arg === "-p") { poll_interval = parseInt(args.shift()); } else if (arg === "--extensions" || arg === "-e") { extensions = args.shift(); } else if (arg === "--exec" || arg === "-x") { executor = args.shift(); } else if (arg === "--no-restart-on" || arg === "-n") { noRestartOn = args.shift(); } else if (arg === "--") { program = args; break; } else if (arg.indexOf("-") && !args.length) { // Assume last arg is the program program = [arg]; } } if (!program) { return help(); } if (!watch) { watch = "."; } if (!poll_interval) { poll_interval = 100; } var programExt = program.join(" ").match(/.*\.(.*)/); programExt = programExt && programExt[1]; if (!extensions) { // If no extensions passed try to guess from the program extensions = "node|js"; if (programExt && extensions.indexOf(programExt) == -1) extensions += "|" + programExt; } extensions = extensions.replace(/,/g, "|"); fileExtensionPattern = new RegExp("^.*\.(" + extensions + ")$"); if (!executor) { executor = (programExt === "coffee") ? "coffee" : "node"; } util.puts("") util.debug("Running node-supervisor with"); util.debug(" program '" + program.join(" ") + "'"); util.debug(" --watch '" + watch + "'"); util.debug(" --extensions '" + extensions + "'"); util.debug(" --exec '" + executor + "'"); util.puts(""); // store the call to startProgramm in startChildProcess // in order to call it later startChildProcess = function() { startProgram(program, executor, programArgs); }; // if we have a program, then run it, and restart when it crashes. // if we have a watch folder, then watch the folder for changes and restart the prog startChildProcess(); var watchItems = watch.split(','); watchItems.forEach(function (watchItem) { if (!watchItem.match(/^\/.*/)) { // watch is not an absolute path // convert watch item to absolute path watchItem = process.cwd() + '/' + watchItem; } util.debug("Watching directory '" + watchItem + "' for changes."); findAllWatchFiles(watchItem, function(f) { watchGivenFile( f, poll_interval ); }); }); }; function print (m, n) { util.print(m+(!n?"\n":"")); return print; } function help () { print ("") ("Node Supervisor is used to restart programs when they crash.") ("It can also be used to restart programs when a *.js file changes.") ("") ("Usage:") (" supervisor [options] <program>") (" supervisor [options] -- <program> [args ...]") ("") ("Required:") (" <program>") (" The program to run.") ("") ("Options:") (" -w|--watch <watchItems>") (" A comma-delimited list of folders or js files to watch for changes.") (" When a change to a js file occurs, reload the program") (" Default is '.'") ("") (" -p|--poll-interval <milliseconds>") (" How often to poll watched files for changes.") (" Defaults to Node default.") ("") (" -e|--extensions <extensions>") (" Specific file extensions to watch in addition to defaults.") (" Used when --watch option includes folders") (" Default is 'node|js'") ("") (" -x|--exec <executable>") (" The executable that runs the specified program.") (" Default is 'node'") ("") (" -n|--no-restart-on error|exit") (" Don't automatically restart the supervised program if it ends.") (" Supervisor will wait for a change in the source files.") (" If \"error\", an exit code of 0 will still restart.") (" If \"exit\", no restart regardless of exit code.") ("") (" -h|--help|-?") (" Display these usage instructions.") ("") (" -q|--quiet") (" Suppress DEBUG messages") ("") ("Examples:") (" supervisor myapp.js") (" supervisor myapp.coffee") (" supervisor -w scripts -e myext -x myrunner myapp") (" supervisor -- server.js -h host -p port") (""); }; function startProgram (prog, exec) { util.debug("Starting child process with '" + exec + " " + prog.join(" ") + "'"); crash_queued = false; var child = exports.child = spawn(exec, prog); child.stdout.addListener("data", function (chunk) { chunk && util.print(chunk); }); child.stderr.addListener("data", function (chunk) { chunk && util.debug(chunk); }); child.addListener("exit", function (code) { if (!crash_queued) { util.debug("Program " + exec + " " + prog.join(" ") + " exited with code " + code + "\n"); exports.child = null; if (noRestartOn == "exit" || noRestartOn == "error" && code !== 0) return; } startProgram(prog, exec); }); } var timer = null, mtime = null; crash_queued = false; function crash () { if (crash_queued) return; crash_queued = true; var child = exports.child; setTimeout(function() { if (child) { util.debug("crashing child"); process.kill(child.pid); } else { util.debug("restarting child"); startChildProcess(); } }, 50); } function crashWin (event) { if( event === 'change' ) crash(); } function crashOther (oldStat, newStat) { // we only care about modification time, not access time. if ( newStat.mtime.getTime() !== oldStat.mtime.getTime() ) crash(); } var isWindows = process.platform === 'win32'; function watchGivenFile (watch, poll_interval) { if (isWindows) fs.watch(watch, { persistent: true, interval: poll_interval }, crashWin); else fs.watchFile(watch, { persistent: true, interval: poll_interval }, crashOther); } var findAllWatchFiles = function(path, callback) { fs.stat(path, function(err, stats){ if (err) { util.error('Error retrieving stats for file: ' + path); } else if (isWindows) { callback(path); } else { if (stats.isDirectory()) { fs.readdir(path, function(err, fileNames) { if(err) { util.error('Error reading path: ' + path); } else { fileNames.forEach(function (fileName) { findAllWatchFiles(path + '/' + fileName, callback); }); } }); } else { if (path.match(fileExtensionPattern)) { callback(path); } } } }); };
Tighten up file extension regexp
lib/supervisor.js
Tighten up file extension regexp
<ide><path>ib/supervisor.js <ide> poll_interval = 100; <ide> } <ide> <del> var programExt = program.join(" ").match(/.*\.(.*)/); <add> var programExt = program.join(" ").match(/.*\.(\S*)/); <ide> programExt = programExt && programExt[1]; <ide> <ide> if (!extensions) {
Java
apache-2.0
767d8a49e43155f764fa855bdd4f091b746e27cc
0
jaferreiro/gora-indra,jaferreiro/gora-indra,jaferreiro/gora-indra
package org.apache.gora.pig; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import org.apache.avro.Schema; import org.apache.avro.Schema.Field; import org.apache.avro.Schema.Type; import org.apache.avro.generic.GenericData; import org.apache.avro.generic.GenericData.Array; import org.apache.gora.mapreduce.GoraInputFormat; import org.apache.gora.mapreduce.GoraInputFormatFactory; import org.apache.gora.mapreduce.GoraMapReduceUtils; import org.apache.gora.mapreduce.GoraOutputFormat; import org.apache.gora.mapreduce.GoraOutputFormatFactory; import org.apache.gora.mapreduce.GoraRecordReader; import org.apache.gora.mapreduce.GoraRecordWriter; import org.apache.gora.persistency.impl.PersistentBase; import org.apache.gora.query.Query; import org.apache.gora.store.DataStore; import org.apache.gora.store.DataStoreFactory; import org.apache.gora.util.AvroUtils; import org.apache.gora.util.GoraException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapreduce.InputFormat; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.OutputFormat; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.RecordWriter; import org.apache.pig.Expression; import org.apache.pig.LoadCaster; import org.apache.pig.LoadFunc; import org.apache.pig.LoadMetadata; import org.apache.pig.ResourceSchema; import org.apache.pig.ResourceSchema.ResourceFieldSchema; import org.apache.pig.ResourceStatistics; import org.apache.pig.StoreFuncInterface; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSplit; import org.apache.pig.builtin.Utf8StorageConverter; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.util.UDFContext; import org.apache.pig.impl.util.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class GoraStorage extends LoadFunc implements StoreFuncInterface, LoadMetadata { public static final Logger LOG = LoggerFactory.getLogger(GoraStorage.class); /** * Key in UDFContext properties that marks config is set (set at backend nodes) */ private static final String GORA_CONFIG_SET = "gorastorage.config.set" ; private static final String GORA_STORE_SCHEMA = "gorastorage.pig.store.schema" ; protected Job job; protected JobConf localJobConf ; protected String udfcSignature = null ; protected String keyClassName ; protected String persistentClassName ; protected Class<?> keyClass; protected Class<? extends PersistentBase> persistentClass; protected Schema persistentSchema ; private DataStore<?, ? extends PersistentBase> dataStore ; protected GoraInputFormat<?,? extends PersistentBase> inputFormat ; protected GoraRecordReader<?,? extends PersistentBase> reader ; protected PigGoraOutputFormat<?,? extends PersistentBase> outputFormat ; protected GoraRecordWriter<?,? extends PersistentBase> writer ; protected PigSplit split ; protected ResourceSchema readResourceSchema ; protected ResourceSchema writeResourceSchema ; private Map<String, ResourceFieldSchemaWithIndex> writeResourceFieldSchemaMap ; /** Fields to load as Query - same as {@link loadSaveFields} but without 'key' */ protected String[] loadQueryFields ; /** Setted to 'true' if location is '*'. All fields will be loaded into a tuple when reading, * and all tuple fields will be copied to the persistent instance when saving. */ protected boolean loadSaveAllFields = false ; /** * Creates a new GoraStorage with implicit "*" fields to load/save. * @param keyClassName * @param persistentClassName * @throws IllegalAccessException * @throws InstantiationException */ public GoraStorage(String keyClassName, String persistentClassName) throws InstantiationException, IllegalAccessException { this(keyClassName, persistentClassName, "*") ; } /** * Creates a new GoraStorage and set the keyClass from the key class name. * @param keyClassName key class. Full name with package (org.apache....) * @param persistentClassName persistent class. Full name with package. * @param fields comma separated fields to load/save | '*' for all. * '*' loads all fields from the persistent class to each tuple. * '*' saves all fields of each tuple to persist (not mandatory all fields of the persistent class). * @throws IllegalAccessException * @throws InstantiationException */ public GoraStorage(String keyClassName, String persistentClassName, String csvFields) throws InstantiationException, IllegalAccessException { super(); LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage constructor() {}", this); this.keyClassName = keyClassName ; this.persistentClassName = persistentClassName ; try { this.keyClass = Class.forName(keyClassName); Class<?> persistentClazz = Class.forName(persistentClassName); this.persistentClass = persistentClazz.asSubclass(PersistentBase.class); } catch (ClassNotFoundException e) { LOG.error("Error creating instance of key and/or persistent.", e) ; throw new RuntimeException(e); } this.persistentSchema = this.persistentClass.newInstance().getSchema() ; // Populates this.loadQueryFields List<String> declaredConstructorFields = new ArrayList<String>() ; if (csvFields.contains("*")) { // Declared fields "*" this.setLoadSaveAllFields(true) ; for (Field field : this.persistentSchema.getFields()) { declaredConstructorFields.add(field.name()) ; } } else { // CSV fields declared in constructor. String[] fieldsInConstructor = csvFields.split("\\s*,\\s*") ; // splits "field, field, field, field" declaredConstructorFields.addAll(Arrays.asList(fieldsInConstructor)) ; } this.setLoadQueryFields(declaredConstructorFields.toArray(new String[0])) ; } /** * Returns the internal DataStore for <code>&lt;keyClass,persistentClass&gt;</code> * using configuration set in job (from setLocation()). * Creates one datastore at first call. * @return DataStore for &lt;keyClass,persistentClass&gt; * @throws GoraException on DataStore creation error. */ protected DataStore<?, ? extends PersistentBase> getDataStore() throws GoraException { if (this.localJobConf == null) { LOG.error("Error integrating gora-pig and Pig. Calling getDataStore(). setLocation()/setStoreLocation() must be called first!") ; throw new GoraException("Calling getDataStore(). setLocation()/setStoreLocation() must be called first!") ; } if (this.dataStore == null) { this.dataStore = DataStoreFactory.getDataStore(this.keyClass, this.persistentClass, this.localJobConf) ; } return this.dataStore ; } /** * Gets the job, initialized the localJobConf (the actual used to create a datastore) and splits from 'location' the fields to load/save * */ @Override public void setLocation(String location, Job job) throws IOException { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage setLocation() {} {}", location, this); GoraMapReduceUtils.setIOSerializations(job.getConfiguration(), true) ; // All Splits return length==0, but must not be combined (actually are not ==0) job.getConfiguration().setBoolean("pig.noSplitCombination", true); this.job = job; this.localJobConf = this.initializeLocalJobConfig(job) ; } /** * Returns UDFProperties based on <code>udfcSignature</code>, <code>keyClassName</code> and <code>persistentClassName</code>. */ private Properties getUDFProperties() { return UDFContext.getUDFContext().getUDFProperties(this.getClass(), new String[] {this.udfcSignature,this.keyClassName,this.persistentClassName}); } private JobConf initializeLocalJobConfig(Job job) { Properties udfProps = getUDFProperties(); Configuration jobConf = job.getConfiguration(); GoraMapReduceUtils.setIOSerializations(jobConf, true) ; JobConf localConf = new JobConf(jobConf); // localConf starts as a copy of jobConf if (udfProps.containsKey(GORA_CONFIG_SET)) { // Already configured (maybe from frontend to backend) for (Entry<Object, Object> entry : udfProps.entrySet()) { localConf.set((String) entry.getKey(), (String) entry.getValue()); } } else { // Not configured. We load to localConf the configuration and put it in udfProps Configuration goraConf = new Configuration(); for (Entry<String, String> entry : goraConf) { // JobConf may have some conf overriding ones in hbase-site.xml // So only copy hbase config not in job config to UDFContext // Also avoids copying core-default.xml and core-site.xml // props in hbaseConf to UDFContext which would be redundant. if (localConf.get(entry.getKey()) == null) { udfProps.setProperty(entry.getKey(), entry.getValue()); localConf.set(entry.getKey(), entry.getValue()); } } udfProps.setProperty(GORA_CONFIG_SET, "true"); } return localConf; } @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public InputFormat getInputFormat() throws IOException { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage getInputFormat() {}", this); this.inputFormat = GoraInputFormatFactory.createInstance(this.keyClass, this.persistentClass); Query query = this.getDataStore().newQuery() ; if (this.isLoadSaveAllFields() == false) { query.setFields(this.getLoadQueryFields()) ; } GoraInputFormat.setInput(this.job, query, false) ; inputFormat.setConf(this.job.getConfiguration()) ; return this.inputFormat ; } @Override public LoadCaster getLoadCaster() throws IOException { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" getLoadCaster()"); return new Utf8StorageConverter(); } @Override @SuppressWarnings({ "rawtypes" }) public void prepareToRead(RecordReader reader, PigSplit split) throws IOException { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" prepareToRead()"); this.reader = (GoraRecordReader<?, ?>) reader; this.split = split; } @Override public Tuple getNext() throws IOException { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" getNext()"); try { if (!this.reader.nextKeyValue()) { LOG.trace(" Fin de lectura (null)") ; return null; } } catch (Exception e) { LOG.error("Error retrieving next key-value.", e) ; throw new IOException(e); } PersistentBase persistentObj; Object persistentKey ; try { persistentKey = this.reader.getCurrentKey() ; LOG.trace(" key: {}", persistentKey) ; persistentObj = this.reader.getCurrentValue(); } catch (Exception e) { LOG.error("Error reading next key-value.", e) ; throw new IOException(e); } return persistent2Tuple(persistentKey, persistentObj, this.getLoadQueryFields()) ; } /** * Creates a pig tuple from a PersistentBase, given some fields in order. It adds "key" field. * The resulting tuple has fields (key, field1, field2,...) * * Internally calls persistentField2PigType(Schema, Object) for each field * * @param persistentKey Key of the PersistentBase object * @param persistentObj PersistentBase instance * @return Tuple with schemafields+1 elements (1<sup>st</sup> element is the row key) * @throws ExecException * On setting tuple field errors */ private static Tuple persistent2Tuple(Object persistentKey, PersistentBase persistentObj, String[] fields) throws ExecException { Tuple tuple = TupleFactory.getInstance().newTuple(fields.length + 1); Schema avroSchema = persistentObj.getSchema() ; tuple.set(0, persistentKey) ; int fieldIndex = 1 ; for (String fieldName : fields) { Field field = avroSchema.getField(fieldName) ; Schema fieldSchema = field.schema() ; Object fieldValue = persistentObj.get(field.pos()) ; tuple.set(fieldIndex++, persistentField2PigType(fieldSchema, fieldValue)) ; } return tuple ; } /** * Recursively converts PersistentBase fields to Pig type: Tuple | Bag | String | Long | ... * * The mapping is as follows: * null -> null * Boolean -> Boolean * Enum -> Integer * ByteBuffer -> DataByteArray * String -> String * Float -> Float * Double -> Double * Integer -> Integer * Long -> Long * Union -> X * Record -> Tuple * Array -> Bag * Map<String,b'> -> HashMap<String,Object> * * @param schema Source schema * @param data Source data: PersistentBase | String | Long,... * @return Pig type: Tuple | Bag | String | Long | ... * @throws ExecException */ @SuppressWarnings("unchecked") private static Object persistentField2PigType(Schema schema, Object data) throws ExecException { Type schemaType = schema.getType(); switch (schemaType) { case NULL: return null ; case BOOLEAN: return (Boolean)data ; case ENUM: return new Integer(((Enum<?>)data).ordinal()) ; case BYTES: return new DataByteArray(((ByteBuffer)data).array()) ; case STRING: return data.toString() ; case FLOAT: case DOUBLE: case INT: case LONG: return data ; case UNION: int unionIndex = GenericData.get().resolveUnion(schema, data) ; Schema unionTypeSchema = schema.getTypes().get(unionIndex) ; return persistentField2PigType(unionTypeSchema, data) ; case RECORD: List<Field> recordFields = schema.getFields() ; int numRecordElements = recordFields.size() ; Tuple recordTuple = TupleFactory.getInstance().newTuple(numRecordElements); for (int i=0; i<numRecordElements ; i++ ) { recordTuple.set(i, persistentField2PigType(recordFields.get(i).schema(), ((PersistentBase)data).get(i))) ; } return recordTuple ; case ARRAY: DataBag bag = BagFactory.getInstance().newDefaultBag() ; Schema arrValueSchema = schema.getElementType() ; for(Object element: (List<?>)data) { Object pigElement = persistentField2PigType(arrValueSchema, element) ; if (pigElement instanceof Tuple) { bag.add((Tuple)pigElement) ; } else { Tuple arrElemTuple = TupleFactory.getInstance().newTuple(1) ; arrElemTuple.set(0, pigElement) ; bag.add(arrElemTuple) ; } } return bag ; case MAP: HashMap<String,Object> map = new HashMap<String,Object>() ; for (Entry<CharSequence,?> e : ((Map<CharSequence,?>)data).entrySet()) { map.put(e.getKey().toString(), persistentField2PigType(schema.getValueType(), e.getValue())) ; } return map ; case FIXED: // TODO: Implement FIXED data type LOG.error("FIXED type not implemented") ; throw new RuntimeException("Fixed type not implemented") ; default: LOG.error("Unexpected schema type {}", schemaType) ; throw new RuntimeException("Unexpected schema type " + schemaType) ; } } @Override public void setUDFContextSignature(String signature) { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage setUDFContextSignature() {}", this); this.udfcSignature = signature; } @Override public String relativeToAbsolutePath(String location, Path curDir) throws IOException { // Do nothing return location ; } /** * Class created to avoid the StackoverflowException of recursive schemas when creating the * schema in #getSchema. * It holds the count of how many references to a Record schema has been created in a recursive call * to use it only once (not counting the topmost) and the third time will be returned a schemaless tuple (= avro record). */ private class RecursiveRecordSchema { Map<String,Integer> generatedSchemas = new HashMap<String,Integer>() ; public int incSchema(String schemaName) { int numReferences = 0 ; if (generatedSchemas.containsKey(schemaName)) { numReferences = generatedSchemas.get(schemaName) ; } generatedSchemas.put(schemaName, ++numReferences) ; return numReferences ; } public void decSchema(String schemaName) { if (generatedSchemas.containsKey(schemaName)) { int numReferences = generatedSchemas.get(schemaName) ; if (numReferences > 0) { generatedSchemas.put(schemaName, --numReferences) ; } } } public void clear() { generatedSchemas.clear() ; } } ; private RecursiveRecordSchema recursiveRecordSchema = new RecursiveRecordSchema() ; /** * Retrieves the Pig Schema from the declared fields in constructor and the Avro Schema * Avro Schema must begin with a record. * Pig Schema will be a Tuple (in 1st level) with $0 = "key":rowkey */ @Override public ResourceSchema getSchema(String location, Job job) throws IOException { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage getSchema() {}", this); // Reuse if already created if (this.readResourceSchema != null) return this.readResourceSchema ; ResourceFieldSchema[] resourceFieldSchemas = null ; int numFields = this.loadQueryFields.length + 1 ; resourceFieldSchemas = new ResourceFieldSchema[numFields] ; resourceFieldSchemas[0] = new ResourceFieldSchema().setType(DataType.findType(this.keyClass)).setName("key") ; for (int fieldIndex = 1; fieldIndex < numFields ; fieldIndex++) { recursiveRecordSchema.clear() ; // Initialize the recursive schema checker in each field Field field = this.persistentSchema.getField(this.loadQueryFields[fieldIndex-1]) ; resourceFieldSchemas[fieldIndex] = this.avro2ResouceFieldSchema(field.schema()).setName(field.name()) ; } ResourceSchema resourceSchema = new ResourceSchema().setFields(resourceFieldSchemas) ; // Save Pig schema inside the instance this.readResourceSchema = resourceSchema ; return this.readResourceSchema ; } private ResourceFieldSchema avro2ResouceFieldSchema(Schema schema) throws IOException { Type schemaType = schema.getType(); switch (schemaType) { case NULL: return new ResourceFieldSchema().setType(DataType.NULL) ; case BOOLEAN: return new ResourceFieldSchema().setType(DataType.BOOLEAN) ; case ENUM: return new ResourceFieldSchema().setType(DataType.INTEGER) ; case BYTES: return new ResourceFieldSchema().setType(DataType.BYTEARRAY); case STRING: return new ResourceFieldSchema().setType(DataType.CHARARRAY) ; case FLOAT: return new ResourceFieldSchema().setType(DataType.FLOAT) ; case DOUBLE: return new ResourceFieldSchema().setType(DataType.DOUBLE) ; case INT: return new ResourceFieldSchema().setType(DataType.INTEGER) ; case LONG: return new ResourceFieldSchema().setType(DataType.LONG) ; case UNION: // Returns the first not-null type if (schema.getTypes().size() != 2) { LOG.warn("Field UNION {} must be ['null','othertype']. Maybe wrong definition?") ; } for (Schema s: schema.getTypes()) { if (s.getType() != Type.NULL) return avro2ResouceFieldSchema(s) ; } LOG.error("Union with only ['null']?") ; throw new RuntimeException("Union with only ['null']?") ; case RECORD: // A record in Gora is a Tuple in Pig if (recursiveRecordSchema.incSchema(schema.getName()) > 1) { // Recursivity detected (and we are 2 levels bellow desired) recursiveRecordSchema.decSchema(schema.getName()) ; // So we can put the esquema of bother leafs // Return a tuple schema with no fields return new ResourceFieldSchema().setType(DataType.TUPLE) ; } int numRecordFields = schema.getFields().size() ; Iterator<Field> recordFields = schema.getFields().iterator(); ResourceFieldSchema returnRecordResourceFieldSchema = new ResourceFieldSchema().setType(DataType.TUPLE) ; ResourceFieldSchema[] recordFieldSchemas = new ResourceFieldSchema[numRecordFields] ; for (int fieldIndex = 0; recordFields.hasNext(); fieldIndex++) { Field schemaField = recordFields.next(); recordFieldSchemas[fieldIndex] = this.avro2ResouceFieldSchema(schemaField.schema()).setName(schemaField.name()) ; } returnRecordResourceFieldSchema.setSchema(new ResourceSchema().setFields(recordFieldSchemas)) ; return returnRecordResourceFieldSchema ; case ARRAY: // An array in Gora is a Bag in Pig // Maybe should be a Map with string(numeric) index to ensure order, but Avro and Pig data model are different :\ ResourceFieldSchema returnArrayResourceFieldSchema = new ResourceFieldSchema().setType(DataType.BAG) ; Schema arrayElementType = schema.getElementType() ; returnArrayResourceFieldSchema.setSchema( new ResourceSchema().setFields( new ResourceFieldSchema[]{ new ResourceFieldSchema().setType(DataType.TUPLE).setName("t").setSchema( new ResourceSchema().setFields( new ResourceFieldSchema[]{ avro2ResouceFieldSchema(arrayElementType) } ) ) } ) ) ; return returnArrayResourceFieldSchema ; case MAP: // A map in Gora is a Map in Pig, but in pig is only chararray=>something ResourceFieldSchema returnMapResourceFieldSchema = new ResourceFieldSchema().setType(DataType.MAP) ; Schema mapValueType = schema.getValueType(); returnMapResourceFieldSchema.setSchema( new ResourceSchema().setFields( new ResourceFieldSchema[]{ avro2ResouceFieldSchema(mapValueType) } ) ) ; return returnMapResourceFieldSchema ; case FIXED: // TODO Implement FIXED data type LOG.error("FIXED type not implemented") ; throw new RuntimeException("Fixed type not implemented") ; default: LOG.error("Unexpected schema type {}", schemaType) ; throw new RuntimeException("Unexpected schema type " + schemaType) ; } } @Override public ResourceStatistics getStatistics(String location, Job job) throws IOException { // TODO Not implemented since Pig does not use it (feb 2013) return null; } @Override /** * Disabled by now (returns null). * Later we will consider only one partition key: row key */ public String[] getPartitionKeys(String location, Job job) throws IOException { // TODO Disabled by now return null ; //return new String[] {"key"} ; } @Override /** * Ignored by now since getPartitionKeys() return null */ public void setPartitionFilter(Expression partitionFilter) throws IOException { // TODO Ignored since getPartitionsKeys() return null throw new IOException() ; } @Override public String relToAbsPathForStoreLocation(String location, Path curDir) throws IOException { // Do nothing return location ; } @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public OutputFormat getOutputFormat() throws IOException { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage getOutputFormat() {}", this); try { this.outputFormat = GoraOutputFormatFactory.createInstance(PigGoraOutputFormat.class, this.keyClass, this.persistentClass); } catch (Exception e) { LOG.error("Error creating PigGoraOutputFormat", e) ; throw new IOException(e) ; } GoraOutputFormat.setOutput(this.job, this.getDataStore(), false) ; this.outputFormat.setConf(this.job.getConfiguration()) ; return this.outputFormat ; } @Override public void setStoreLocation(String location, Job job) throws IOException { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage setStoreLocation() {}", this) ; GoraMapReduceUtils.setIOSerializations(job.getConfiguration(), true) ; this.job = job ; this.localJobConf = this.initializeLocalJobConfig(job) ; } @Override /** * Checks the pig schema using names, using the first element of the tuple as key (fieldname = 'key'). * (key:key, name:recordfield, name:recordfield, name:recordfi...) * * Sets UDFContext property GORA_STORE_SCHEMA with the schema to send it to the backend. * * Not present names for recordfields will be treated as null . */ public void checkSchema(ResourceSchema s) throws IOException { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage checkSchema() {}", this); // Expected pig schema: tuple (key, recordfield, recordfield, recordfi...) ResourceFieldSchema[] pigFieldSchemas = s.getFields(); List<String> pigFieldSchemasNames = new ArrayList<String>(Arrays.asList(s.fieldNames())) ; if ( !pigFieldSchemasNames.contains("key") ) { LOG.error("Error when checking schema. Expected a field called \"key\", but not found.") ; throw new IOException("Expected a field called \"key\", but not found.") ; } // All fields are mandatory List<String> mandatoryFieldNames = new ArrayList<String>(Arrays.asList(this.loadQueryFields)) ; if (pigFieldSchemasNames.containsAll(mandatoryFieldNames)) { for (ResourceFieldSchema pigFieldSchema: pigFieldSchemas) { LOG.trace(" Pig field {}", pigFieldSchema.getName()) ; if (mandatoryFieldNames.contains(pigFieldSchema.getName())) { Field persistentField = this.persistentSchema.getField(pigFieldSchema.getName()) ; if (persistentField == null) { LOG.error("Declared field in Pig [" + pigFieldSchema.getName() + "] to store does not exists in " + this.persistentClassName +".") ; throw new IOException("Declared field in Pig [" + pigFieldSchema.getName() + "] to store does not exists in " + this.persistentClassName +".") ; } checkEqualSchema(pigFieldSchema, this.persistentSchema.getField(pigFieldSchema.getName()).schema()) ; } } } else { LOG.error("Some fields declared in the constructor (" + Arrays.toString(this.loadQueryFields) + ") are missing in the tuples to be saved (" + Arrays.toString(s.fieldNames()) + ")" ) ; throw new IOException("Some fields declared in the constructor (" + Arrays.toString(this.loadQueryFields) + ") are missing in the tuples to be saved (" + Arrays.toString(s.fieldNames()) + ")" ) ; } // Save the schema to UDFContext to use it on backend when writing data getUDFProperties().setProperty(GoraStorage.GORA_STORE_SCHEMA, s.toString()) ; } /** * Checks a Pig field schema comparing with avro schema, based on pig field's name (for record fields). * * @param pigFieldSchema A Pig field schema * @param avroSchema Avro schema related with pig field schema. * @throws IOException */ private void checkEqualSchema(ResourceFieldSchema pigFieldSchema, Schema avroSchema) throws IOException { byte pigType = pigFieldSchema.getType() ; String fieldName = pigFieldSchema.getName() ; Type avroType = avroSchema.getType() ; //TODO Add logs before throw exception // Switch that checks if avro type matches pig type, or if avro is union and some nested type matches pig type. switch (pigType) { case DataType.BAG: // Avro Array LOG.trace(" Bag") ; if (!avroType.equals(Type.ARRAY) && !checkUnionSchema(avroSchema, pigFieldSchema)) throw new IOException("Can not convert field [" + fieldName + "] from Pig BAG with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; checkEqualSchema(pigFieldSchema.getSchema().getFields()[0].getSchema().getFields()[0], avroSchema.getElementType()) ; break ; case DataType.BOOLEAN: LOG.trace(" Boolean") ; if (!avroType.equals(Type.BOOLEAN) && !checkUnionSchema(avroSchema, pigFieldSchema)) throw new IOException("Can not convert field [" + fieldName + "] from Pig BOOLEAN with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; break ; case DataType.BYTEARRAY: LOG.trace(" Bytearray") ; if (!avroType.equals(Type.BYTES) && !checkUnionSchema(avroSchema, pigFieldSchema)) throw new IOException("Can not convert field [" + fieldName + "] from Pig BYTEARRAY with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; break ; case DataType.CHARARRAY: // String LOG.trace(" Chararray") ; if (!avroType.equals(Type.STRING) && !checkUnionSchema(avroSchema, pigFieldSchema)) throw new IOException("Can not convert field [" + fieldName + "] from Pig CHARARRAY with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; break; case DataType.DOUBLE: LOG.trace(" Double") ; if (!avroType.equals(Type.DOUBLE) && !checkUnionSchema(avroSchema, pigFieldSchema)) throw new IOException("Can not convert field [" + fieldName + "] from Pig DOUBLE with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; break ; case DataType.FLOAT: LOG.trace(" Float") ; if (!avroType.equals(Type.FLOAT) && !checkUnionSchema(avroSchema, pigFieldSchema)) throw new IOException("Can not convert field [" + fieldName + "] from Pig FLOAT with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; break ; case DataType.INTEGER: // Int or Enum LOG.trace(" Integer") ; if (!avroType.equals(Type.INT) && !avroType.equals(Type.ENUM) && !checkUnionSchema(avroSchema, pigFieldSchema)) throw new IOException("Can not convert field [" + fieldName + "] from Pig INTEGER with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; break ; case DataType.LONG: LOG.trace(" Long") ; if (!avroType.equals(Type.LONG) && !checkUnionSchema(avroSchema, pigFieldSchema)) throw new IOException("Can not convert field [" + fieldName + "] from Pig LONG with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; break ; case DataType.MAP: // Avro Map LOG.trace(" Map") ; if (!avroType.equals(Type.MAP) && !checkUnionSchema(avroSchema, pigFieldSchema)) throw new IOException("Can not convert field [" + fieldName + "] from Pig MAP with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; break ; case DataType.NULL: // Avro nullable?? LOG.trace(" Type Null") ; if(!avroType.equals(Type.NULL) && !checkUnionSchema(avroSchema, pigFieldSchema)) throw new IOException("Can not convert field [" + fieldName + "] from Pig NULL with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; break ; case DataType.TUPLE: // Avro Record LOG.trace(" Tuple") ; if (!avroType.equals(Type.RECORD) && !checkUnionSchema(avroSchema, pigFieldSchema)) throw new IOException("Can not convert field [" + fieldName + "] from Pig TUPLE(record) with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; break ; default: throw new IOException("Unexpected Pig schema type " + DataType.genTypeToNameMap().get(pigType) + " for avro schema field " + avroSchema.getName() +": " + avroType.name()) ; } } /** * Checks and tries to match a pig field schema with an avro union schema. * @param avroSchema Schema with * @param pigFieldSchema * @return true: if a match is found * false: if avro schema is not UNION * @throws IOException(message, Exception()) if avro schema is UNION but not match is found for pig field schema. */ private boolean checkUnionSchema(Schema avroSchema, ResourceFieldSchema pigFieldSchema) throws IOException { if (!avroSchema.getType().equals(Type.UNION)) return false ; for (Schema unionElementSchema: avroSchema.getTypes()) { try { LOG.trace(" Checking pig schema with avro union [{},...]", unionElementSchema.getType().getName()) ; checkEqualSchema(pigFieldSchema, unionElementSchema) ; return true ; }catch (IOException e){ // Exception from inner union, rethrow if (e.getCause() != null) { throw e ; } // else ignore } } // throws IOException(message,Exception()) to mark nested union exception. LOG.error("Expected some field defined in '"+avroSchema.getName()+"' for pig schema type '"+DataType.genTypeToNameMap().get(pigFieldSchema.getType()+"'")) ; throw new IOException("Expected some field defined in '"+avroSchema.getName()+"' for pig schema type '"+DataType.genTypeToNameMap().get(pigFieldSchema.getType()+"'")+"'", new Exception("Union not satisfied")) ; } @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public void prepareToWrite(RecordWriter writer) throws IOException { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage prepareToWrite() {}", this); this.writer = (GoraRecordWriter<?,? extends PersistentBase>) writer ; // Get the schema of data to write from UDFContext (coming from frontend checkSchema()) String strSchema = getUDFProperties().getProperty(GoraStorage.GORA_STORE_SCHEMA) ; if (strSchema == null) { LOG.error("Could not find schema in UDF context. Should have been set in checkSchema() in frontend.") ; throw new IOException("Could not find schema in UDF context. Should have been set in checkSchema() in frontend.") ; } // Parse de the schema from string stored in properties object this.writeResourceSchema = new ResourceSchema(Utils.getSchemaFromString(strSchema)) ; if (LOG.isTraceEnabled()) LOG.trace(this.writeResourceSchema.toString()) ; this.writeResourceFieldSchemaMap = new HashMap<String, ResourceFieldSchemaWithIndex>() ; int index = 0 ; for (ResourceFieldSchema fieldSchema : this.writeResourceSchema.getFields()) { this.writeResourceFieldSchemaMap.put(fieldSchema.getName(), new ResourceFieldSchemaWithIndex(fieldSchema, index++)) ; } } @SuppressWarnings("unchecked") @Override public void putNext(Tuple t) throws IOException { PersistentBase persistentObj = this.dataStore.newPersistent() ; if (LOG.isTraceEnabled()) LOG.trace("key: {}", t.get(0)) ; for (String fieldName : this.loadQueryFields) { if (LOG.isTraceEnabled()) LOG.trace(" Put fieldName: {} {}", fieldName, this.writeResourceFieldSchemaMap.get(fieldName).getResourceFieldSchema()) ; if (LOG.isTraceEnabled()) LOG.trace(" value: {} - {}",this.writeResourceFieldSchemaMap.get(fieldName).getIndex(), t.get(this.writeResourceFieldSchemaMap.get(fieldName).getIndex())) ; persistentObj.put(persistentObj.getField2IndexMapping().get(fieldName), // name -> index this.writeField(persistentSchema.getField(fieldName).schema(), this.writeResourceFieldSchemaMap.get(fieldName).getResourceFieldSchema(), t.get(this.writeResourceFieldSchemaMap.get(fieldName).getIndex()))) ; } try { ((GoraRecordWriter<Object,PersistentBase>) this.writer).write(t.get(0), (PersistentBase) persistentObj) ; } catch (InterruptedException e) { LOG.error("Error writing the tuple.", e) ; throw new IOException(e) ; } } /** * Converts one pig field data to PersistentBase Data. * * @param avroSchema PersistentBase schema used to create new nested records * @param field Pig schema of the field being converted * @param pigData Pig data relative to the schema * @return PersistentBase data * @throws IOException */ private Object writeField(Schema avroSchema, ResourceFieldSchema field, Object pigData) throws IOException { // If data is null, return null (check if avro schema is right) if (pigData == null) { if (avroSchema.getType() != Type.UNION && avroSchema.getType() != Type.NULL) { LOG.error("Tuple field " + field.getName() + " is null, but Avro Schema is not union nor null") ; throw new IOException("Tuple field " + field.getName() + " is null, but Avro Schema is not union nor null") ; } else { return null ; } } // If avroSchema is union, it will not be the null field, so select the proper one if (avroSchema.getType() == Type.UNION) { //TODO Resolve the proper schema avroSchema = avroSchema.getTypes().get(1) ; } switch(field.getType()) { case DataType.DOUBLE: case DataType.FLOAT: case DataType.LONG: case DataType.BOOLEAN: case DataType.NULL: if (LOG.isTraceEnabled()) LOG.trace(" Writing double, float, long, boolean or null.") ; return (Object)pigData ; case DataType.CHARARRAY: if (LOG.isTraceEnabled()) LOG.trace(" Writing chararray.") ; return pigData.toString() ; case DataType.INTEGER: if (LOG.isTraceEnabled()) LOG.trace(" Writing integer/enum.") ; if (avroSchema.getType() == Type.ENUM) { return AvroUtils.getEnumValue(avroSchema, (Integer)pigData); }else{ return (Integer)pigData ; } case DataType.BYTEARRAY: if (LOG.isTraceEnabled()) LOG.trace(" Writing bytearray.") ; return ByteBuffer.wrap(((DataByteArray)pigData).get()) ; case DataType.MAP: // Pig Map -> Avro Map if (LOG.isTraceEnabled()) LOG.trace(" Writing map.") ; @SuppressWarnings("unchecked") Map<String,Object> pigMap = (Map<String,Object>) pigData ; Map<String,Object> goraMap = new HashMap<String, Object>(pigMap.size()) ; for(Entry<String,Object> pigEntry : pigMap.entrySet()) { goraMap.put(pigEntry.getKey(), this.writeField(avroSchema.getValueType(), field.getSchema().getFields()[0], pigEntry.getValue())) ; } return goraMap ; case DataType.BAG: // Pig Bag -> Avro Array if (LOG.isTraceEnabled()) LOG.trace(" Writing bag.") ; Array<Object> persistentArray = new Array<Object>((int)((DataBag)pigData).size(),avroSchema) ; for (Object pigArrayElement: (DataBag)pigData) { if (avroSchema.getElementType().getType() == Type.RECORD) { // If element type is record, the mapping Persistent->PigType deletes one nested tuple: // We want the map as: map((a1,a2,a3), (b1,b2,b3),...) instead of map(((a1,a2,a3)), ((b1,b2,b3)), ...) persistentArray.add(this.writeField(avroSchema.getElementType(), field.getSchema().getFields()[0], pigArrayElement)) ; } else { // Every bag has a tuple as element type. Since this is not a record, that "tuple" container must be ignored persistentArray.add(this.writeField(avroSchema.getElementType(), field.getSchema().getFields()[0].getSchema().getFields()[0], ((Tuple)pigArrayElement).get(0))) ; } } return persistentArray ; case DataType.TUPLE: // Pig Tuple -> Avro Record if (LOG.isTraceEnabled()) LOG.trace(" Writing tuple.") ; try { PersistentBase persistentRecord = (PersistentBase) Class.forName(avroSchema.getFullName()).newInstance(); ResourceFieldSchema[] tupleFieldSchemas = field.getSchema().getFields() ; for (int i=0; i<tupleFieldSchemas.length; i++) { persistentRecord.put(persistentRecord.getField2IndexMapping().get(tupleFieldSchemas[i].getName()), this.writeField(avroSchema.getField(tupleFieldSchemas[i].getName()).schema(), tupleFieldSchemas[i], ((Tuple)pigData).get(i))) ; } return persistentRecord ; } catch (InstantiationException e) { throw new IOException(e) ; } catch (IllegalAccessException e) { throw new IOException(e) ; } catch (ClassNotFoundException e) { throw new IOException(e) ; } default: LOG.error("Unexpected field " + field.getName() +" with Pig type "+ DataType.genTypeToNameMap().get(field.getType())) ; throw new IOException("Unexpected field " + field.getName() +" with Pig type "+ DataType.genTypeToNameMap().get(field.getType())) ; } } @Override public void setStoreFuncUDFContextSignature(String signature) { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage setStoreFuncUDFContextSignature() {}", this); this.udfcSignature = signature ; } @Override public void cleanupOnFailure(String location, Job job) throws IOException { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage cleanupOnFailure() {}", this); } @Override public void cleanupOnSuccess(String location, Job job) throws IOException { if (dataStore != null) dataStore.flush() ; } public boolean isLoadSaveAllFields() { return loadSaveAllFields; } public void setLoadSaveAllFields(boolean loadSaveAllFields) { this.loadSaveAllFields = loadSaveAllFields; } public String[] getLoadQueryFields() { return loadQueryFields; } public void setLoadQueryFields(String[] loadQueryFields) { this.loadQueryFields = loadQueryFields; } }
gora-pig/src/main/java/org/apache/gora/pig/GoraStorage.java
package org.apache.gora.pig; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import org.apache.avro.Schema; import org.apache.avro.Schema.Field; import org.apache.avro.Schema.Type; import org.apache.avro.generic.GenericData; import org.apache.avro.generic.GenericData.Array; import org.apache.gora.mapreduce.GoraInputFormat; import org.apache.gora.mapreduce.GoraInputFormatFactory; import org.apache.gora.mapreduce.GoraMapReduceUtils; import org.apache.gora.mapreduce.GoraOutputFormat; import org.apache.gora.mapreduce.GoraOutputFormatFactory; import org.apache.gora.mapreduce.GoraRecordReader; import org.apache.gora.mapreduce.GoraRecordWriter; import org.apache.gora.persistency.impl.PersistentBase; import org.apache.gora.query.Query; import org.apache.gora.store.DataStore; import org.apache.gora.store.DataStoreFactory; import org.apache.gora.util.AvroUtils; import org.apache.gora.util.GoraException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapreduce.InputFormat; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.OutputFormat; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.RecordWriter; import org.apache.pig.Expression; import org.apache.pig.LoadCaster; import org.apache.pig.LoadFunc; import org.apache.pig.LoadMetadata; import org.apache.pig.ResourceSchema; import org.apache.pig.ResourceSchema.ResourceFieldSchema; import org.apache.pig.ResourceStatistics; import org.apache.pig.StoreFuncInterface; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSplit; import org.apache.pig.builtin.Utf8StorageConverter; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.util.UDFContext; import org.apache.pig.impl.util.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class GoraStorage extends LoadFunc implements StoreFuncInterface, LoadMetadata { public static final Logger LOG = LoggerFactory.getLogger(GoraStorage.class); /** * Key in UDFContext properties that marks config is set (set at backend nodes) */ private static final String GORA_CONFIG_SET = "gorastorage.config.set" ; private static final String GORA_STORE_SCHEMA = "gorastorage.pig.store.schema" ; protected Job job; protected JobConf localJobConf ; protected String udfcSignature = null ; protected String keyClassName ; protected String persistentClassName ; protected Class<?> keyClass; protected Class<? extends PersistentBase> persistentClass; protected Schema persistentSchema ; private DataStore<?, ? extends PersistentBase> dataStore ; protected GoraInputFormat<?,? extends PersistentBase> inputFormat ; protected GoraRecordReader<?,? extends PersistentBase> reader ; protected PigGoraOutputFormat<?,? extends PersistentBase> outputFormat ; protected GoraRecordWriter<?,? extends PersistentBase> writer ; protected PigSplit split ; protected ResourceSchema readResourceSchema ; protected ResourceSchema writeResourceSchema ; private Map<String, ResourceFieldSchemaWithIndex> writeResourceFieldSchemaMap ; /** Fields to load as Query - same as {@link loadSaveFields} but without 'key' */ protected String[] loadQueryFields ; /** Setted to 'true' if location is '*'. All fields will be loaded into a tuple when reading, * and all tuple fields will be copied to the persistent instance when saving. */ protected boolean loadSaveAllFields = false ; /** * Creates a new GoraStorage with implicit "*" fields to load/save. * @param keyClassName * @param persistentClassName * @throws IllegalAccessException * @throws InstantiationException */ public GoraStorage(String keyClassName, String persistentClassName) throws InstantiationException, IllegalAccessException { this(keyClassName, persistentClassName, "*") ; } /** * Creates a new GoraStorage and set the keyClass from the key class name. * @param keyClassName key class. Full name with package (org.apache....) * @param persistentClassName persistent class. Full name with package. * @param fields comma separated fields to load/save | '*' for all. * '*' loads all fields from the persistent class to each tuple. * '*' saves all fields of each tuple to persist (not mandatory all fields of the persistent class). * @throws IllegalAccessException * @throws InstantiationException */ public GoraStorage(String keyClassName, String persistentClassName, String csvFields) throws InstantiationException, IllegalAccessException { super(); LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage constructor() {}", this); this.keyClassName = keyClassName ; this.persistentClassName = persistentClassName ; try { this.keyClass = Class.forName(keyClassName); Class<?> persistentClazz = Class.forName(persistentClassName); this.persistentClass = persistentClazz.asSubclass(PersistentBase.class); } catch (ClassNotFoundException e) { LOG.error("Error creating instance of key and/or persistent.", e) ; throw new RuntimeException(e); } this.persistentSchema = this.persistentClass.newInstance().getSchema() ; // Populates this.loadQueryFields List<String> declaredConstructorFields = new ArrayList<String>() ; if (csvFields.contains("*")) { // Declared fields "*" this.setLoadSaveAllFields(true) ; for (Field field : this.persistentSchema.getFields()) { declaredConstructorFields.add(field.name()) ; } } else { // CSV fields declared in constructor. String[] fieldsInConstructor = csvFields.split("\\s*,\\s*") ; // splits "field, field, field, field" declaredConstructorFields.addAll(Arrays.asList(fieldsInConstructor)) ; } this.setLoadQueryFields(declaredConstructorFields.toArray(new String[0])) ; } /** * Returns the internal DataStore for <code>&lt;keyClass,persistentClass&gt;</code> * using configuration set in job (from setLocation()). * Creates one datastore at first call. * @return DataStore for &lt;keyClass,persistentClass&gt; * @throws GoraException on DataStore creation error. */ protected DataStore<?, ? extends PersistentBase> getDataStore() throws GoraException { if (this.localJobConf == null) { LOG.error("Error integrating gora-pig and Pig. Calling getDataStore(). setLocation()/setStoreLocation() must be called first!") ; throw new GoraException("Calling getDataStore(). setLocation()/setStoreLocation() must be called first!") ; } if (this.dataStore == null) { this.dataStore = DataStoreFactory.getDataStore(this.keyClass, this.persistentClass, this.localJobConf) ; } return this.dataStore ; } /** * Gets the job, initialized the localJobConf (the actual used to create a datastore) and splits from 'location' the fields to load/save * */ @Override public void setLocation(String location, Job job) throws IOException { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage setLocation() {} {}", location, this); GoraMapReduceUtils.setIOSerializations(job.getConfiguration(), true) ; // All Splits return length==0, but must not be combined (actually are not ==0) job.getConfiguration().setBoolean("pig.noSplitCombination", true); this.job = job; this.localJobConf = this.initializeLocalJobConfig(job) ; } /** * Returns UDFProperties based on <code>udfcSignature</code>, <code>keyClassName</code> and <code>persistentClassName</code>. */ private Properties getUDFProperties() { return UDFContext.getUDFContext().getUDFProperties(this.getClass(), new String[] {this.udfcSignature,this.keyClassName,this.persistentClassName}); } private JobConf initializeLocalJobConfig(Job job) { Properties udfProps = getUDFProperties(); Configuration jobConf = job.getConfiguration(); GoraMapReduceUtils.setIOSerializations(jobConf, true) ; JobConf localConf = new JobConf(jobConf); // localConf starts as a copy of jobConf if (udfProps.containsKey(GORA_CONFIG_SET)) { // Already configured (maybe from frontend to backend) for (Entry<Object, Object> entry : udfProps.entrySet()) { localConf.set((String) entry.getKey(), (String) entry.getValue()); } } else { // Not configured. We load to localConf the configuration and put it in udfProps Configuration goraConf = new Configuration(); for (Entry<String, String> entry : goraConf) { // JobConf may have some conf overriding ones in hbase-site.xml // So only copy hbase config not in job config to UDFContext // Also avoids copying core-default.xml and core-site.xml // props in hbaseConf to UDFContext which would be redundant. if (localConf.get(entry.getKey()) == null) { udfProps.setProperty(entry.getKey(), entry.getValue()); localConf.set(entry.getKey(), entry.getValue()); } } udfProps.setProperty(GORA_CONFIG_SET, "true"); } return localConf; } @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public InputFormat getInputFormat() throws IOException { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage getInputFormat() {}", this); this.inputFormat = GoraInputFormatFactory.createInstance(this.keyClass, this.persistentClass); Query query = this.getDataStore().newQuery() ; if (this.isLoadSaveAllFields() == false) { query.setFields(this.getLoadQueryFields()) ; } GoraInputFormat.setInput(this.job, query, false) ; inputFormat.setConf(this.job.getConfiguration()) ; return this.inputFormat ; } @Override public LoadCaster getLoadCaster() throws IOException { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" getLoadCaster()"); return new Utf8StorageConverter(); } @Override @SuppressWarnings({ "rawtypes" }) public void prepareToRead(RecordReader reader, PigSplit split) throws IOException { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" prepareToRead()"); this.reader = (GoraRecordReader<?, ?>) reader; this.split = split; } @Override public Tuple getNext() throws IOException { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" getNext()"); try { if (!this.reader.nextKeyValue()) { LOG.trace(" Fin de lectura (null)") ; return null; } } catch (Exception e) { LOG.error("Error retrieving next key-value.", e) ; throw new IOException(e); } PersistentBase persistentObj; Object persistentKey ; try { persistentKey = this.reader.getCurrentKey() ; LOG.trace(" key: {}", persistentKey) ; persistentObj = this.reader.getCurrentValue(); } catch (Exception e) { LOG.error("Error reading next key-value.", e) ; throw new IOException(e); } return persistent2Tuple(persistentKey, persistentObj, this.getLoadQueryFields()) ; } /** * Creates a pig tuple from a PersistentBase, given some fields in order. It adds "key" field. * The resulting tuple has fields (key, field1, field2,...) * * Internally calls persistentField2PigType(Schema, Object) for each field * * @param persistentKey Key of the PersistentBase object * @param persistentObj PersistentBase instance * @return Tuple with schemafields+1 elements (1<sup>st</sup> element is the row key) * @throws ExecException * On setting tuple field errors */ private static Tuple persistent2Tuple(Object persistentKey, PersistentBase persistentObj, String[] fields) throws ExecException { Tuple tuple = TupleFactory.getInstance().newTuple(fields.length + 1); Schema avroSchema = persistentObj.getSchema() ; tuple.set(0, persistentKey) ; int fieldIndex = 1 ; for (String fieldName : fields) { Field field = avroSchema.getField(fieldName) ; Schema fieldSchema = field.schema() ; Object fieldValue = persistentObj.get(field.pos()) ; tuple.set(fieldIndex++, persistentField2PigType(fieldSchema, fieldValue)) ; } return tuple ; } /** * Recursively converts PersistentBase fields to Pig type: Tuple | Bag | String | Long | ... * * The mapping is as follows: * null -> null * Boolean -> Boolean * Enum -> Integer * ByteBuffer -> DataByteArray * String -> String * Float -> Float * Double -> Double * Integer -> Integer * Long -> Long * Union -> X * Record -> Tuple * Array -> Bag * Map<String,b'> -> HashMap<String,Object> * * @param schema Source schema * @param data Source data: PersistentBase | String | Long,... * @return Pig type: Tuple | Bag | String | Long | ... * @throws ExecException */ @SuppressWarnings("unchecked") private static Object persistentField2PigType(Schema schema, Object data) throws ExecException { Type schemaType = schema.getType(); switch (schemaType) { case NULL: return null ; case BOOLEAN: return (Boolean)data ; case ENUM: return new Integer(((Enum<?>)data).ordinal()) ; case BYTES: return new DataByteArray(((ByteBuffer)data).array()) ; case STRING: return data.toString() ; case FLOAT: case DOUBLE: case INT: case LONG: return data ; case UNION: int unionIndex = GenericData.get().resolveUnion(schema, data) ; Schema unionTypeSchema = schema.getTypes().get(unionIndex) ; return persistentField2PigType(unionTypeSchema, data) ; case RECORD: List<Field> recordFields = schema.getFields() ; int numRecordElements = recordFields.size() ; Tuple recordTuple = TupleFactory.getInstance().newTuple(numRecordElements); for (int i=0; i<numRecordElements ; i++ ) { recordTuple.set(i, persistentField2PigType(recordFields.get(i).schema(), ((PersistentBase)data).get(i))) ; } return recordTuple ; case ARRAY: DataBag bag = BagFactory.getInstance().newDefaultBag() ; Schema arrValueSchema = schema.getElementType() ; for(Object element: (List<?>)data) { Object pigElement = persistentField2PigType(arrValueSchema, element) ; if (pigElement instanceof Tuple) { bag.add((Tuple)pigElement) ; } else { Tuple arrElemTuple = TupleFactory.getInstance().newTuple(1) ; arrElemTuple.set(0, pigElement) ; bag.add(arrElemTuple) ; } } return bag ; case MAP: HashMap<String,Object> map = new HashMap<String,Object>() ; for (Entry<CharSequence,?> e : ((Map<CharSequence,?>)data).entrySet()) { map.put(e.getKey().toString(), persistentField2PigType(schema.getValueType(), e.getValue())) ; } return map ; case FIXED: // TODO: Implement FIXED data type LOG.error("FIXED type not implemented") ; throw new RuntimeException("Fixed type not implemented") ; default: LOG.error("Unexpected schema type {}", schemaType) ; throw new RuntimeException("Unexpected schema type " + schemaType) ; } } @Override public void setUDFContextSignature(String signature) { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage setUDFContextSignature() {}", this); this.udfcSignature = signature; } @Override public String relativeToAbsolutePath(String location, Path curDir) throws IOException { // Do nothing return location ; } /** * Class created to avoid the StackoverflowException of recursive schemas when creating the * schema in #getSchema. * It holds the count of how many references to a Record schema has been created in a recursive call * to use it only once (not counting the topmost) and the third time will be returned a schemaless tuple (= avro record). */ private class RecursiveRecordSchema { Map<String,Integer> generatedSchemas = new HashMap<String,Integer>() ; public int incSchema(String schemaName) { int numReferences = 0 ; if (generatedSchemas.containsKey(schemaName)) { numReferences = generatedSchemas.get(schemaName) ; } generatedSchemas.put(schemaName, ++numReferences) ; return numReferences ; } public void decSchema(String schemaName) { if (generatedSchemas.containsKey(schemaName)) { int numReferences = generatedSchemas.get(schemaName) ; if (numReferences > 0) { generatedSchemas.put(schemaName, --numReferences) ; } } } public void clear() { generatedSchemas.clear() ; } } ; private RecursiveRecordSchema recursiveRecordSchema = new RecursiveRecordSchema() ; /** * Retrieves the Pig Schema from the declared fields in constructor and the Avro Schema * Avro Schema must begin with a record. * Pig Schema will be a Tuple (in 1st level) with $0 = "key":rowkey */ @Override public ResourceSchema getSchema(String location, Job job) throws IOException { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage getSchema() {}", this); // Reuse if already created if (this.readResourceSchema != null) return this.readResourceSchema ; ResourceFieldSchema[] resourceFieldSchemas = null ; int numFields = this.loadQueryFields.length + 1 ; resourceFieldSchemas = new ResourceFieldSchema[numFields] ; resourceFieldSchemas[0] = new ResourceFieldSchema().setType(DataType.findType(this.keyClass)).setName("key") ; for (int fieldIndex = 1; fieldIndex < numFields ; fieldIndex++) { recursiveRecordSchema.clear() ; // Initialize the recursive schema checker in each field Field field = this.persistentSchema.getField(this.loadQueryFields[fieldIndex-1]) ; resourceFieldSchemas[fieldIndex] = this.avro2ResouceFieldSchema(field.schema()).setName(field.name()) ; } ResourceSchema resourceSchema = new ResourceSchema().setFields(resourceFieldSchemas) ; // Save Pig schema inside the instance this.readResourceSchema = resourceSchema ; return this.readResourceSchema ; } private ResourceFieldSchema avro2ResouceFieldSchema(Schema schema) throws IOException { Type schemaType = schema.getType(); switch (schemaType) { case NULL: return new ResourceFieldSchema().setType(DataType.NULL) ; case BOOLEAN: return new ResourceFieldSchema().setType(DataType.BOOLEAN) ; case ENUM: return new ResourceFieldSchema().setType(DataType.INTEGER) ; case BYTES: return new ResourceFieldSchema().setType(DataType.BYTEARRAY); case STRING: return new ResourceFieldSchema().setType(DataType.CHARARRAY) ; case FLOAT: return new ResourceFieldSchema().setType(DataType.FLOAT) ; case DOUBLE: return new ResourceFieldSchema().setType(DataType.DOUBLE) ; case INT: return new ResourceFieldSchema().setType(DataType.INTEGER) ; case LONG: return new ResourceFieldSchema().setType(DataType.LONG) ; case UNION: // Returns the first not-null type if (schema.getTypes().size() != 2) { LOG.warn("Field UNION {} must be ['null','othertype']. Maybe wrong definition?") ; } for (Schema s: schema.getTypes()) { if (s.getType() != Type.NULL) return avro2ResouceFieldSchema(s) ; } LOG.error("Union with only ['null']?") ; throw new RuntimeException("Union with only ['null']?") ; case RECORD: // A record in Gora is a Tuple in Pig if (recursiveRecordSchema.incSchema(schema.getName()) > 1) { // Recursivity detected (and we are 2 levels bellow desired) recursiveRecordSchema.decSchema(schema.getName()) ; // So we can put the esquema of bother leafs // Return a tuple schema with no fields return new ResourceFieldSchema().setType(DataType.TUPLE) ; } int numRecordFields = schema.getFields().size() ; Iterator<Field> recordFields = schema.getFields().iterator(); ResourceFieldSchema returnRecordResourceFieldSchema = new ResourceFieldSchema().setType(DataType.TUPLE) ; ResourceFieldSchema[] recordFieldSchemas = new ResourceFieldSchema[numRecordFields] ; for (int fieldIndex = 0; recordFields.hasNext(); fieldIndex++) { Field schemaField = recordFields.next(); recordFieldSchemas[fieldIndex] = this.avro2ResouceFieldSchema(schemaField.schema()).setName(schemaField.name()) ; } returnRecordResourceFieldSchema.setSchema(new ResourceSchema().setFields(recordFieldSchemas)) ; return returnRecordResourceFieldSchema ; case ARRAY: // An array in Gora is a Bag in Pig // Maybe should be a Map with string(numeric) index to ensure order, but Avro and Pig data model are different :\ ResourceFieldSchema returnArrayResourceFieldSchema = new ResourceFieldSchema().setType(DataType.BAG) ; Schema arrayElementType = schema.getElementType() ; returnArrayResourceFieldSchema.setSchema( new ResourceSchema().setFields( new ResourceFieldSchema[]{ new ResourceFieldSchema().setType(DataType.TUPLE).setName("t").setSchema( new ResourceSchema().setFields( new ResourceFieldSchema[]{ avro2ResouceFieldSchema(arrayElementType) } ) ) } ) ) ; return returnArrayResourceFieldSchema ; case MAP: // A map in Gora is a Map in Pig, but in pig is only chararray=>something ResourceFieldSchema returnMapResourceFieldSchema = new ResourceFieldSchema().setType(DataType.MAP) ; Schema mapValueType = schema.getValueType(); returnMapResourceFieldSchema.setSchema( new ResourceSchema().setFields( new ResourceFieldSchema[]{ avro2ResouceFieldSchema(mapValueType) } ) ) ; return returnMapResourceFieldSchema ; case FIXED: // TODO Implement FIXED data type LOG.error("FIXED type not implemented") ; throw new RuntimeException("Fixed type not implemented") ; default: LOG.error("Unexpected schema type {}", schemaType) ; throw new RuntimeException("Unexpected schema type " + schemaType) ; } } @Override public ResourceStatistics getStatistics(String location, Job job) throws IOException { // TODO Not implemented since Pig does not use it (feb 2013) return null; } @Override /** * Disabled by now (returns null). * Later we will consider only one partition key: row key */ public String[] getPartitionKeys(String location, Job job) throws IOException { // TODO Disabled by now return null ; //return new String[] {"key"} ; } @Override /** * Ignored by now since getPartitionKeys() return null */ public void setPartitionFilter(Expression partitionFilter) throws IOException { // TODO Ignored since getPartitionsKeys() return null throw new IOException() ; } @Override public String relToAbsPathForStoreLocation(String location, Path curDir) throws IOException { // Do nothing return location ; } @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public OutputFormat getOutputFormat() throws IOException { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage getOutputFormat() {}", this); try { this.outputFormat = GoraOutputFormatFactory.createInstance(PigGoraOutputFormat.class, this.keyClass, this.persistentClass); } catch (Exception e) { LOG.error("Error creating PigGoraOutputFormat", e) ; throw new IOException(e) ; } GoraOutputFormat.setOutput(this.job, this.getDataStore(), false) ; this.outputFormat.setConf(this.job.getConfiguration()) ; return this.outputFormat ; } @Override public void setStoreLocation(String location, Job job) throws IOException { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage setStoreLocation() {}", this) ; GoraMapReduceUtils.setIOSerializations(job.getConfiguration(), true) ; this.job = job ; this.localJobConf = this.initializeLocalJobConfig(job) ; } @Override /** * Checks the pig schema using names, using the first element of the tuple as key (fieldname = 'key'). * (key:key, name:recordfield, name:recordfield, name:recordfi...) * * Sets UDFContext property GORA_STORE_SCHEMA with the schema to send it to the backend. * * Not present names for recordfields will be treated as null . */ public void checkSchema(ResourceSchema s) throws IOException { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage checkSchema() {}", this); // Expected pig schema: tuple (key, recordfield, recordfield, recordfi...) ResourceFieldSchema[] pigFieldSchemas = s.getFields(); List<String> pigFieldSchemasNames = new ArrayList<String>(Arrays.asList(s.fieldNames())) ; if ( !pigFieldSchemasNames.contains("key") ) { LOG.error("Error when checking schema. Expected a field called \"key\", but not found.") ; throw new IOException("Expected a field called \"key\", but not found.") ; } // All fields are mandatory List<String> mandatoryFieldNames = new ArrayList<String>(Arrays.asList(this.loadQueryFields)) ; if (pigFieldSchemasNames.containsAll(mandatoryFieldNames)) { for (ResourceFieldSchema pigFieldSchema: pigFieldSchemas) { if (mandatoryFieldNames.contains(pigFieldSchema.getName())) { Field persistentField = this.persistentSchema.getField(pigFieldSchema.getName()) ; if (persistentField == null) { LOG.error("Declared field in Pig [" + pigFieldSchema.getName() + "] to store does not exists in " + this.persistentClassName +".") ; throw new IOException("Declared field in Pig [" + pigFieldSchema.getName() + "] to store does not exists in " + this.persistentClassName +".") ; } checkEqualSchema(pigFieldSchema, this.persistentSchema.getField(pigFieldSchema.getName()).schema()) ; } } } else { LOG.error("Some fields declared in the constructor (" + Arrays.toString(this.loadQueryFields) + ") are missing in the tuples to be saved (" + Arrays.toString(s.fieldNames()) + ")" ) ; throw new IOException("Some fields declared in the constructor (" + Arrays.toString(this.loadQueryFields) + ") are missing in the tuples to be saved (" + Arrays.toString(s.fieldNames()) + ")" ) ; } // Save the schema to UDFContext to use it on backend when writing data getUDFProperties().setProperty(GoraStorage.GORA_STORE_SCHEMA, s.toString()) ; } /** * Checks a Pig field schema comparing with avro schema, based on pig field's name (for record fields). * * @param pigFieldSchema A Pig field schema * @param avroSchema Avro schema related with pig field schema. * @throws IOException */ private void checkEqualSchema(ResourceFieldSchema pigFieldSchema, Schema avroSchema) throws IOException { byte pigType = pigFieldSchema.getType() ; String fieldName = pigFieldSchema.getName() ; Type avroType = avroSchema.getType() ; //TODO Add logs before throw exception // Switch that checks if avro type matches pig type, or if avro is union and some nested type matches pig type. switch (pigType) { case DataType.BAG: // Avro Array if (!avroType.equals(Type.ARRAY) && !checkUnionSchema(avroSchema, pigFieldSchema)) throw new IOException("Can not convert field [" + fieldName + "] from Pig BAG with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; checkEqualSchema(pigFieldSchema.getSchema().getFields()[0].getSchema().getFields()[0], avroSchema.getElementType()) ; break ; case DataType.BOOLEAN: if (!avroType.equals(Type.BOOLEAN) && !checkUnionSchema(avroSchema, pigFieldSchema)) throw new IOException("Can not convert field [" + fieldName + "] from Pig BOOLEAN with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; break ; case DataType.BYTEARRAY: if (!avroType.equals(Type.BYTES) && !checkUnionSchema(avroSchema, pigFieldSchema)) throw new IOException("Can not convert field [" + fieldName + "] from Pig BYTEARRAY with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; break ; case DataType.CHARARRAY: // String if (!avroType.equals(Type.STRING) && !checkUnionSchema(avroSchema, pigFieldSchema)) throw new IOException("Can not convert field [" + fieldName + "] from Pig CHARARRAY with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; break; case DataType.DOUBLE: if (!avroType.equals(Type.DOUBLE) && !checkUnionSchema(avroSchema, pigFieldSchema)) throw new IOException("Can not convert field [" + fieldName + "] from Pig DOUBLE with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; break ; case DataType.FLOAT: if (!avroType.equals(Type.FLOAT) && !checkUnionSchema(avroSchema, pigFieldSchema)) throw new IOException("Can not convert field [" + fieldName + "] from Pig FLOAT with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; break ; case DataType.INTEGER: // Int or Enum if (!avroType.equals(Type.INT) && !avroType.equals(Type.ENUM) && !checkUnionSchema(avroSchema, pigFieldSchema)) throw new IOException("Can not convert field [" + fieldName + "] from Pig INTEGER with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; break ; case DataType.LONG: if (!avroType.equals(Type.LONG) && !checkUnionSchema(avroSchema, pigFieldSchema)) throw new IOException("Can not convert field [" + fieldName + "] from Pig LONG with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; break ; case DataType.MAP: // Avro Map if (!avroType.equals(Type.MAP) && !checkUnionSchema(avroSchema, pigFieldSchema)) throw new IOException("Can not convert field [" + fieldName + "] from Pig MAP with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; break ; case DataType.NULL: // Avro nullable?? if(!avroType.equals(Type.NULL) && !checkUnionSchema(avroSchema, pigFieldSchema)) throw new IOException("Can not convert field [" + fieldName + "] from Pig NULL with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; break ; case DataType.TUPLE: // Avro Record if (!avroType.equals(Type.RECORD) && !checkUnionSchema(avroSchema, pigFieldSchema)) throw new IOException("Can not convert field [" + fieldName + "] from Pig TUPLE(record) with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; break ; default: throw new IOException("Unexpected Pig schema type " + DataType.genTypeToNameMap().get(pigType) + " for avro schema field " + avroSchema.getName() +": " + avroType.name()) ; } } /** * Checks and tries to match a pig field schema with an avro union schema. * @param avroSchema Schema with * @param pigFieldSchema * @return true: if a match is found * false: if avro schema is not UNION * @throws IOException(message, Exception()) if avro schema is UNION but not match is found for pig field schema. */ private boolean checkUnionSchema(Schema avroSchema, ResourceFieldSchema pigFieldSchema) throws IOException { if (!avroSchema.getType().equals(Type.UNION)) return false ; for (Schema unionElementSchema: avroSchema.getTypes()) { try { checkEqualSchema(pigFieldSchema, unionElementSchema) ; return true ; }catch (IOException e){ // Exception from inner union, rethrow if (e.getCause() != null) { throw e ; } // else ignore } } // throws IOException(message,Exception()) to mark nested union exception. LOG.error("Expected some field defined in '"+avroSchema.getName()+"' for pig schema type '"+DataType.genTypeToNameMap().get(pigFieldSchema.getType()+"'")) ; throw new IOException("Expected some field defined in '"+avroSchema.getName()+"' for pig schema type '"+DataType.genTypeToNameMap().get(pigFieldSchema.getType()+"'"), new Exception("Union not satisfied")) ; } @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public void prepareToWrite(RecordWriter writer) throws IOException { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage prepareToWrite() {}", this); this.writer = (GoraRecordWriter<?,? extends PersistentBase>) writer ; // Get the schema of data to write from UDFContext (coming from frontend checkSchema()) String strSchema = getUDFProperties().getProperty(GoraStorage.GORA_STORE_SCHEMA) ; if (strSchema == null) { LOG.error("Could not find schema in UDF context. Should have been set in checkSchema() in frontend.") ; throw new IOException("Could not find schema in UDF context. Should have been set in checkSchema() in frontend.") ; } // Parse de the schema from string stored in properties object this.writeResourceSchema = new ResourceSchema(Utils.getSchemaFromString(strSchema)) ; if (LOG.isTraceEnabled()) LOG.trace(this.writeResourceSchema.toString()) ; this.writeResourceFieldSchemaMap = new HashMap<String, ResourceFieldSchemaWithIndex>() ; int index = 0 ; for (ResourceFieldSchema fieldSchema : this.writeResourceSchema.getFields()) { this.writeResourceFieldSchemaMap.put(fieldSchema.getName(), new ResourceFieldSchemaWithIndex(fieldSchema, index++)) ; } } @SuppressWarnings("unchecked") @Override public void putNext(Tuple t) throws IOException { PersistentBase persistentObj = this.dataStore.newPersistent() ; if (LOG.isTraceEnabled()) LOG.trace("key: {}", t.get(0)) ; for (String fieldName : this.loadQueryFields) { if (LOG.isTraceEnabled()) LOG.trace(" Put fieldName: {} {}", fieldName, this.writeResourceFieldSchemaMap.get(fieldName).getResourceFieldSchema()) ; if (LOG.isTraceEnabled()) LOG.trace(" value: {} - {}",this.writeResourceFieldSchemaMap.get(fieldName).getIndex(), t.get(this.writeResourceFieldSchemaMap.get(fieldName).getIndex())) ; persistentObj.put(persistentObj.getField2IndexMapping().get(fieldName), // name -> index this.writeField(persistentSchema.getField(fieldName).schema(), this.writeResourceFieldSchemaMap.get(fieldName).getResourceFieldSchema(), t.get(this.writeResourceFieldSchemaMap.get(fieldName).getIndex()))) ; } try { ((GoraRecordWriter<Object,PersistentBase>) this.writer).write(t.get(0), (PersistentBase) persistentObj) ; } catch (InterruptedException e) { LOG.error("Error writing the tuple.", e) ; throw new IOException(e) ; } } /** * Converts one pig field data to PersistentBase Data. * * @param avroSchema PersistentBase schema used to create new nested records * @param field Pig schema of the field being converted * @param pigData Pig data relative to the schema * @return PersistentBase data * @throws IOException */ private Object writeField(Schema avroSchema, ResourceFieldSchema field, Object pigData) throws IOException { // If data is null, return null (check if avro schema is right) if (pigData == null) { if (avroSchema.getType() != Type.UNION && avroSchema.getType() != Type.NULL) { LOG.error("Tuple field " + field.getName() + " is null, but Avro Schema is not union nor null") ; throw new IOException("Tuple field " + field.getName() + " is null, but Avro Schema is not union nor null") ; } else { return null ; } } // If avroSchema is union, it will not be the null field, so select the proper one if (avroSchema.getType() == Type.UNION) { //TODO Resolve the proper schema avroSchema = avroSchema.getTypes().get(1) ; } switch(field.getType()) { case DataType.DOUBLE: case DataType.FLOAT: case DataType.LONG: case DataType.BOOLEAN: case DataType.NULL: if (LOG.isTraceEnabled()) LOG.trace(" Writing double, float, long, boolean or null.") ; return (Object)pigData ; case DataType.CHARARRAY: if (LOG.isTraceEnabled()) LOG.trace(" Writing chararray.") ; return pigData.toString() ; case DataType.INTEGER: if (LOG.isTraceEnabled()) LOG.trace(" Writing integer/enum.") ; if (avroSchema.getType() == Type.ENUM) { return AvroUtils.getEnumValue(avroSchema, (Integer)pigData); }else{ return (Integer)pigData ; } case DataType.BYTEARRAY: if (LOG.isTraceEnabled()) LOG.trace(" Writing bytearray.") ; return ByteBuffer.wrap(((DataByteArray)pigData).get()) ; case DataType.MAP: // Pig Map -> Avro Map if (LOG.isTraceEnabled()) LOG.trace(" Writing map.") ; @SuppressWarnings("unchecked") Map<String,Object> pigMap = (Map<String,Object>) pigData ; Map<String,Object> goraMap = new HashMap<String, Object>(pigMap.size()) ; for(Entry<String,Object> pigEntry : pigMap.entrySet()) { goraMap.put(pigEntry.getKey(), this.writeField(avroSchema.getValueType(), field.getSchema().getFields()[0], pigEntry.getValue())) ; } return goraMap ; case DataType.BAG: // Pig Bag -> Avro Array if (LOG.isTraceEnabled()) LOG.trace(" Writing bag.") ; Array<Object> persistentArray = new Array<Object>((int)((DataBag)pigData).size(),avroSchema) ; for (Object pigArrayElement: (DataBag)pigData) { if (avroSchema.getElementType().getType() == Type.RECORD) { // If element type is record, the mapping Persistent->PigType deletes one nested tuple: // We want the map as: map((a1,a2,a3), (b1,b2,b3),...) instead of map(((a1,a2,a3)), ((b1,b2,b3)), ...) persistentArray.add(this.writeField(avroSchema.getElementType(), field.getSchema().getFields()[0], pigArrayElement)) ; } else { // Every bag has a tuple as element type. Since this is not a record, that "tuple" container must be ignored persistentArray.add(this.writeField(avroSchema.getElementType(), field.getSchema().getFields()[0].getSchema().getFields()[0], ((Tuple)pigArrayElement).get(0))) ; } } return persistentArray ; case DataType.TUPLE: // Pig Tuple -> Avro Record if (LOG.isTraceEnabled()) LOG.trace(" Writing tuple.") ; try { PersistentBase persistentRecord = (PersistentBase) Class.forName(avroSchema.getFullName()).newInstance(); ResourceFieldSchema[] tupleFieldSchemas = field.getSchema().getFields() ; for (int i=0; i<tupleFieldSchemas.length; i++) { persistentRecord.put(persistentRecord.getField2IndexMapping().get(tupleFieldSchemas[i].getName()), this.writeField(avroSchema.getField(tupleFieldSchemas[i].getName()).schema(), tupleFieldSchemas[i], ((Tuple)pigData).get(i))) ; } return persistentRecord ; } catch (InstantiationException e) { throw new IOException(e) ; } catch (IllegalAccessException e) { throw new IOException(e) ; } catch (ClassNotFoundException e) { throw new IOException(e) ; } default: LOG.error("Unexpected field " + field.getName() +" with Pig type "+ DataType.genTypeToNameMap().get(field.getType())) ; throw new IOException("Unexpected field " + field.getName() +" with Pig type "+ DataType.genTypeToNameMap().get(field.getType())) ; } } @Override public void setStoreFuncUDFContextSignature(String signature) { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage setStoreFuncUDFContextSignature() {}", this); this.udfcSignature = signature ; } @Override public void cleanupOnFailure(String location, Job job) throws IOException { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage cleanupOnFailure() {}", this); } @Override public void cleanupOnSuccess(String location, Job job) throws IOException { if (dataStore != null) dataStore.flush() ; } public boolean isLoadSaveAllFields() { return loadSaveAllFields; } public void setLoadSaveAllFields(boolean loadSaveAllFields) { this.loadSaveAllFields = loadSaveAllFields; } public String[] getLoadQueryFields() { return loadQueryFields; } public void setLoadQueryFields(String[] loadQueryFields) { this.loadQueryFields = loadQueryFields; } }
Mejorado el logging de GoraStorage.
gora-pig/src/main/java/org/apache/gora/pig/GoraStorage.java
Mejorado el logging de GoraStorage.
<ide><path>ora-pig/src/main/java/org/apache/gora/pig/GoraStorage.java <ide> List<String> mandatoryFieldNames = new ArrayList<String>(Arrays.asList(this.loadQueryFields)) ; <ide> if (pigFieldSchemasNames.containsAll(mandatoryFieldNames)) { <ide> for (ResourceFieldSchema pigFieldSchema: pigFieldSchemas) { <add> LOG.trace(" Pig field {}", pigFieldSchema.getName()) ; <ide> if (mandatoryFieldNames.contains(pigFieldSchema.getName())) { <ide> Field persistentField = this.persistentSchema.getField(pigFieldSchema.getName()) ; <ide> if (persistentField == null) { <ide> // Switch that checks if avro type matches pig type, or if avro is union and some nested type matches pig type. <ide> switch (pigType) { <ide> case DataType.BAG: // Avro Array <add> LOG.trace(" Bag") ; <ide> if (!avroType.equals(Type.ARRAY) && !checkUnionSchema(avroSchema, pigFieldSchema)) <ide> throw new IOException("Can not convert field [" + fieldName + "] from Pig BAG with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; <ide> checkEqualSchema(pigFieldSchema.getSchema().getFields()[0].getSchema().getFields()[0], avroSchema.getElementType()) ; <ide> break ; <ide> case DataType.BOOLEAN: <add> LOG.trace(" Boolean") ; <ide> if (!avroType.equals(Type.BOOLEAN) && !checkUnionSchema(avroSchema, pigFieldSchema)) <ide> throw new IOException("Can not convert field [" + fieldName + "] from Pig BOOLEAN with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; <ide> break ; <ide> case DataType.BYTEARRAY: <add> LOG.trace(" Bytearray") ; <ide> if (!avroType.equals(Type.BYTES) && !checkUnionSchema(avroSchema, pigFieldSchema)) <ide> throw new IOException("Can not convert field [" + fieldName + "] from Pig BYTEARRAY with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; <ide> break ; <ide> case DataType.CHARARRAY: // String <add> LOG.trace(" Chararray") ; <ide> if (!avroType.equals(Type.STRING) && !checkUnionSchema(avroSchema, pigFieldSchema)) <ide> throw new IOException("Can not convert field [" + fieldName + "] from Pig CHARARRAY with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; <ide> break; <ide> case DataType.DOUBLE: <add> LOG.trace(" Double") ; <ide> if (!avroType.equals(Type.DOUBLE) && !checkUnionSchema(avroSchema, pigFieldSchema)) <ide> throw new IOException("Can not convert field [" + fieldName + "] from Pig DOUBLE with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; <ide> break ; <ide> case DataType.FLOAT: <add> LOG.trace(" Float") ; <ide> if (!avroType.equals(Type.FLOAT) && !checkUnionSchema(avroSchema, pigFieldSchema)) <ide> throw new IOException("Can not convert field [" + fieldName + "] from Pig FLOAT with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; <ide> break ; <ide> case DataType.INTEGER: // Int or Enum <add> LOG.trace(" Integer") ; <ide> if (!avroType.equals(Type.INT) && !avroType.equals(Type.ENUM) && !checkUnionSchema(avroSchema, pigFieldSchema)) <ide> throw new IOException("Can not convert field [" + fieldName + "] from Pig INTEGER with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; <ide> break ; <ide> case DataType.LONG: <add> LOG.trace(" Long") ; <ide> if (!avroType.equals(Type.LONG) && !checkUnionSchema(avroSchema, pigFieldSchema)) <ide> throw new IOException("Can not convert field [" + fieldName + "] from Pig LONG with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; <ide> break ; <ide> case DataType.MAP: // Avro Map <add> LOG.trace(" Map") ; <ide> if (!avroType.equals(Type.MAP) && !checkUnionSchema(avroSchema, pigFieldSchema)) <ide> throw new IOException("Can not convert field [" + fieldName + "] from Pig MAP with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; <ide> break ; <ide> case DataType.NULL: // Avro nullable?? <add> LOG.trace(" Type Null") ; <ide> if(!avroType.equals(Type.NULL) && !checkUnionSchema(avroSchema, pigFieldSchema)) <ide> throw new IOException("Can not convert field [" + fieldName + "] from Pig NULL with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; <ide> break ; <ide> case DataType.TUPLE: // Avro Record <add> LOG.trace(" Tuple") ; <ide> if (!avroType.equals(Type.RECORD) && !checkUnionSchema(avroSchema, pigFieldSchema)) <ide> throw new IOException("Can not convert field [" + fieldName + "] from Pig TUPLE(record) with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; <ide> break ; <ide> <ide> for (Schema unionElementSchema: avroSchema.getTypes()) { <ide> try { <add> LOG.trace(" Checking pig schema with avro union [{},...]", unionElementSchema.getType().getName()) ; <ide> checkEqualSchema(pigFieldSchema, unionElementSchema) ; <ide> return true ; <ide> }catch (IOException e){ <ide> } <ide> // throws IOException(message,Exception()) to mark nested union exception. <ide> LOG.error("Expected some field defined in '"+avroSchema.getName()+"' for pig schema type '"+DataType.genTypeToNameMap().get(pigFieldSchema.getType()+"'")) ; <del> throw new IOException("Expected some field defined in '"+avroSchema.getName()+"' for pig schema type '"+DataType.genTypeToNameMap().get(pigFieldSchema.getType()+"'"), new Exception("Union not satisfied")) ; <add> throw new IOException("Expected some field defined in '"+avroSchema.getName()+"' for pig schema type '"+DataType.genTypeToNameMap().get(pigFieldSchema.getType()+"'")+"'", new Exception("Union not satisfied")) ; <ide> } <ide> <ide> @Override
JavaScript
apache-2.0
97daddb01e8291dd3dac2007752f87a479c22201
0
mark-friedman/blockly,trinketapp/blockly,joshlory/blockly,trodi/blockly,nickmain/blockly,mark-friedman/blockly,trodi/blockly,trinketapp/blockly,picklesrus/blockly,mark-friedman/blockly,nickmain/blockly,nickmain/blockly,trinketapp/blockly,groklearning/blockly,trodi/blockly,twodee/blockly,twodee/blockly,rachel-fenichel/blockly,groklearning/blockly,twodee/blockly,google/blockly,google/blockly,groklearning/blockly,rachel-fenichel/blockly,nickmain/blockly,google/blockly,trodi/blockly,rachel-fenichel/blockly,nickmain/blockly,mark-friedman/blockly,joshlory/blockly,rachel-fenichel/blockly,picklesrus/blockly,joshlory/blockly,trinketapp/blockly,google/blockly,nickmain/blockly,jstnhuang/blockly,google/blockly,mark-friedman/blockly,twodee/blockly,google/blockly,jstnhuang/blockly,mark-friedman/blockly,rachel-fenichel/blockly,rachel-fenichel/blockly,jstnhuang/blockly,groklearning/blockly,picklesrus/blockly,jstnhuang/blockly,twodee/blockly,rachel-fenichel/blockly,google/blockly,twodee/blockly
/** * @license * Blockly Demos: Block Factory * * Copyright 2016 Google Inc. * https://developers.google.com/blockly/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Javascript for the Block Exporter Controller class. Allows * users to export block definitions and generator stubs of their saved blocks * easily using a visual interface. Depends on Block Exporter View and Block * Exporter Tools classes. Interacts with Export Settings in the index.html. * * @author quachtina96 (Tina Quach) */ 'use strict'; goog.provide('BlockExporterController'); goog.require('BlocklyDevTools.Analytics'); goog.require('FactoryUtils'); goog.require('StandardCategories'); goog.require('BlockExporterView'); goog.require('BlockExporterTools'); goog.require('goog.dom.xml'); /** * BlockExporter Controller Class * @param {!BlockLibrary.Storage} blockLibStorage Block Library Storage. * @constructor */ BlockExporterController = function(blockLibStorage) { // BlockLibrary.Storage object containing user's saved blocks. this.blockLibStorage = blockLibStorage; // Utils for generating code to export. this.tools = new BlockExporterTools(); // The ID of the block selector, a div element that will be populated with the // block options. this.selectorID = 'blockSelector'; // Map of block types stored in block library to their corresponding Block // Option objects. this.blockOptions = this.tools.createBlockSelectorFromLib( this.blockLibStorage, this.selectorID); // View provides the block selector and export settings UI. this.view = new BlockExporterView(this.blockOptions); }; /** * Set the block library storage object from which exporter exports. * @param {!BlockLibraryStorage} blockLibStorage Block Library Storage object * that stores the blocks. */ BlockExporterController.prototype.setBlockLibraryStorage = function(blockLibStorage) { this.blockLibStorage = blockLibStorage; }; /** * Get the block library storage object from which exporter exports. * @return {!BlockLibraryStorage} blockLibStorage Block Library Storage object * that stores the blocks. */ BlockExporterController.prototype.getBlockLibraryStorage = function(blockLibStorage) { return this.blockLibStorage; }; /** * Get selected blocks from block selector, pulls info from the Export * Settings form in Block Exporter, and downloads code accordingly. */ BlockExporterController.prototype.export = function() { // Get selected blocks' information. var blockTypes = this.view.getSelectedBlockTypes(); var blockXmlMap = this.blockLibStorage.getBlockXmlMap(blockTypes); // Pull block definition(s) settings from the Export Settings form. var wantBlockDef = document.getElementById('blockDefCheck').checked; var definitionFormat = document.getElementById('exportFormat').value; var blockDef_filename = document.getElementById('blockDef_filename').value; // Pull block generator stub(s) settings from the Export Settings form. var wantGenStub = document.getElementById('genStubCheck').checked; var language = document.getElementById('exportLanguage').value; var generatorStub_filename = document.getElementById( 'generatorStub_filename').value; if (wantBlockDef) { // User wants to export selected blocks' definitions. if (!blockDef_filename) { // User needs to enter filename. var msg = 'Please enter a filename for your block definition(s) download.'; BlocklyDevTools.Analytics.onWarning(msg); alert(msg); } else { // Get block definition code in the selected format for the blocks. var blockDefs = this.tools.getBlockDefinitions(blockXmlMap, definitionFormat); // Download the file, using .js file ending for JSON or Javascript. FactoryUtils.createAndDownloadFile( blockDefs, blockDef_filename, 'javascript'); BlocklyDevTools.Analytics.onExport( BlocklyDevTools.Analytics.BLOCK_DEFINITIONS, { format: (definitionFormat == 'JSON' ? BlocklyDevTools.Analytics.FORMAT_JSON : BlocklyDevTools.Analytics.FORMAT_JS) }); } } if (wantGenStub) { // User wants to export selected blocks' generator stubs. if (!generatorStub_filename) { // User needs to enter filename. var msg = 'Please enter a filename for your generator stub(s) download.'; BlocklyDevTools.Analytics.onWarning(msg); alert(msg); } else { // Get generator stub code in the selected language for the blocks. var genStubs = this.tools.getGeneratorCode(blockXmlMap, language); // Download the file. FactoryUtils.createAndDownloadFile( genStubs, generatorStub_filename + '.js', 'javascript'); BlocklyDevTools.Analytics.onExport( BlocklyDevTools.Analytics.GENERATOR, { format: BlocklyDevTools.Analytics.FORMAT_JS }); } } }; /** * Update the Exporter's block selector with block options generated from blocks * stored in block library. */ BlockExporterController.prototype.updateSelector = function() { // Get previously selected block types. var oldSelectedTypes = this.view.getSelectedBlockTypes(); // Generate options from block library and assign to view. this.blockOptions = this.tools.createBlockSelectorFromLib( this.blockLibStorage, this.selectorID); this.addBlockOptionSelectHandlers(); this.view.setBlockOptions(this.blockOptions); // Select all previously selected blocks. for (var i = 0, blockType; blockType = oldSelectedTypes[i]; i++) { if (this.blockOptions[blockType]) { this.view.select(blockType); } } this.view.listSelectedBlocks(); }; /** * Tied to the 'Clear Selected Blocks' button in the Block Exporter. * Deselects all blocks in the selector and updates text accordingly. */ BlockExporterController.prototype.clearSelectedBlocks = function() { this.view.deselectAllBlocks(); this.view.listSelectedBlocks(); }; /** * Tied to the 'All Stored' button in the Block Exporter 'Select' dropdown. * Selects all blocks stored in block library for export. */ BlockExporterController.prototype.selectAllBlocks = function() { var allBlockTypes = this.blockLibStorage.getBlockTypes(); for (var i = 0, blockType; blockType = allBlockTypes[i]; i++) { this.view.select(blockType); } this.view.listSelectedBlocks(); }; /** * Returns the category XML containing all blocks in the block library. * @return {Element} XML for a category to be used in toolbox. */ BlockExporterController.prototype.getBlockLibraryCategory = function() { return this.tools.generateCategoryFromBlockLib(this.blockLibStorage); }; /** * Add select handlers to each block option to update the view and the selected * blocks accordingly. */ BlockExporterController.prototype.addBlockOptionSelectHandlers = function() { var self = this; // Click handler for a block option. Toggles whether or not it's selected and // updates helper text accordingly. var updateSelectedBlockTypes_ = function(blockOption) { // Toggle selected. blockOption.setSelected(!blockOption.isSelected()); // Show currently selected blocks in helper text. self.view.listSelectedBlocks(); }; // Returns a block option select handler. var makeBlockOptionSelectHandler_ = function(blockOption) { return function() { updateSelectedBlockTypes_(blockOption); self.updatePreview(); }; }; // Assign a click handler to each block option. for (var blockType in this.blockOptions) { var blockOption = this.blockOptions[blockType]; // Use an additional closure to correctly assign the tab callback. blockOption.dom.addEventListener( 'click', makeBlockOptionSelectHandler_(blockOption)); } }; /** * Tied to the 'All Used' button in the Block Exporter's 'Select' button. * Selects all blocks stored in block library and used in workspace factory. */ BlockExporterController.prototype.selectUsedBlocks = function() { // Deselect all blocks. this.view.deselectAllBlocks(); // Get list of block types that are in block library and used in workspace // factory. var storedBlockTypes = this.blockLibStorage.getBlockTypes(); var sharedBlockTypes = []; // Keep list of custom block types used but not in library. var unstoredCustomBlockTypes = []; for (var i = 0, blockType; blockType = this.usedBlockTypes[i]; i++) { if (storedBlockTypes.indexOf(blockType) != -1) { sharedBlockTypes.push(blockType); } else if (StandardCategories.coreBlockTypes.indexOf(blockType) == -1) { unstoredCustomBlockTypes.push(blockType); } } // Select each shared block type. for (var i = 0, blockType; blockType = sharedBlockTypes[i]; i++) { this.view.select(blockType); } this.view.listSelectedBlocks(); if (unstoredCustomBlockTypes.length > 0){ // Warn user to import block defifnitions and generator code for blocks // not in their Block Library nor Blockly's standard library. var blockTypesText = unstoredCustomBlockTypes.join(', '); var customWarning = 'Custom blocks used in workspace factory but not ' + 'stored in block library:\n ' + blockTypesText + '\n\nDon\'t forget to include block definitions and generator code ' + 'for these blocks.'; alert(customWarning); } }; /** * Set the array that holds the block types used in workspace factory. * @param {!Array.<string>} usedBlockTypes Block types used in */ BlockExporterController.prototype.setUsedBlockTypes = function(usedBlockTypes) { this.usedBlockTypes = usedBlockTypes; }; /** * Updates preview code (block definitions and generator stubs) in the exporter * preview to reflect selected blocks. */ BlockExporterController.prototype.updatePreview = function() { // Generate preview code for selected blocks. var blockDefs = this.getBlockDefinitionsOfSelected(); var genStubs = this.getGeneratorStubsOfSelected(); // Update the text areas containing the code. FactoryUtils.injectCode(blockDefs, 'blockDefs_textArea'); FactoryUtils.injectCode(genStubs, 'genStubs_textArea'); }; /** * Returns a map of each selected block's type to its corresponding XML. * @return {!Object} A map of each selected block's type (a string) to its * corresponding XML element. */ BlockExporterController.prototype.getSelectedBlockXmlMap = function() { var blockTypes = this.view.getSelectedBlockTypes(); return this.blockLibStorage.getBlockXmlMap(blockTypes); }; /** * Get block definition code in the selected format for selected blocks. * @return {string} The concatenation of each selected block's language code * in the format specified in export settings. */ BlockExporterController.prototype.getBlockDefinitionsOfSelected = function() { // Get selected blocks' information. var blockXmlMap = this.getSelectedBlockXmlMap(); // Get block definition code in the selected format for the blocks. var definitionFormat = document.getElementById('exportFormat').value; return this.tools.getBlockDefinitions(blockXmlMap, definitionFormat); }; /** * Get generator stubs in the selected language for selected blocks. * @return {string} The concatenation of each selected block's generator stub * in the language specified in export settings. */ BlockExporterController.prototype.getGeneratorStubsOfSelected = function() { // Get selected blocks' information. var blockXmlMap = this.getSelectedBlockXmlMap(); // Get generator stub code in the selected language for the blocks. var language = document.getElementById('exportLanguage').value; return this.tools.getGeneratorCode(blockXmlMap, language); };
demos/blockfactory/block_exporter_controller.js
/** * @license * Blockly Demos: Block Factory * * Copyright 2016 Google Inc. * https://developers.google.com/blockly/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Javascript for the Block Exporter Controller class. Allows * users to export block definitions and generator stubs of their saved blocks * easily using a visual interface. Depends on Block Exporter View and Block * Exporter Tools classes. Interacts with Export Settings in the index.html. * * @author quachtina96 (Tina Quach) */ 'use strict'; goog.provide('BlockExporterController'); goog.require('BlocklyDevTools.Analytics'); goog.require('FactoryUtils'); goog.require('StandardCategories'); goog.require('BlockExporterView'); goog.require('BlockExporterTools'); goog.require('goog.dom.xml'); /** * BlockExporter Controller Class * @param {!BlockLibrary.Storage} blockLibStorage Block Library Storage. * @constructor */ BlockExporterController = function(blockLibStorage) { // BlockLibrary.Storage object containing user's saved blocks. this.blockLibStorage = blockLibStorage; // Utils for generating code to export. this.tools = new BlockExporterTools(); // The ID of the block selector, a div element that will be populated with the // block options. this.selectorID = 'blockSelector'; // Map of block types stored in block library to their corresponding Block // Option objects. this.blockOptions = this.tools.createBlockSelectorFromLib( this.blockLibStorage, this.selectorID); // View provides the block selector and export settings UI. this.view = new BlockExporterView(this.blockOptions); }; /** * Set the block library storage object from which exporter exports. * @param {!BlockLibraryStorage} blockLibStorage Block Library Storage object * that stores the blocks. */ BlockExporterController.prototype.setBlockLibraryStorage = function(blockLibStorage) { this.blockLibStorage = blockLibStorage; }; /** * Get the block library storage object from which exporter exports. * @return {!BlockLibraryStorage} blockLibStorage Block Library Storage object * that stores the blocks. */ BlockExporterController.prototype.getBlockLibraryStorage = function(blockLibStorage) { return this.blockLibStorage; }; /** * Get selected blocks from block selector, pulls info from the Export * Settings form in Block Exporter, and downloads code accordingly. */ BlockExporterController.prototype.export = function() { // Get selected blocks' information. var blockTypes = this.view.getSelectedBlockTypes(); var blockXmlMap = this.blockLibStorage.getBlockXmlMap(blockTypes); // Pull block definition(s) settings from the Export Settings form. var wantBlockDef = document.getElementById('blockDefCheck').checked; var definitionFormat = document.getElementById('exportFormat').value; var blockDef_filename = document.getElementById('blockDef_filename').value; // Pull block generator stub(s) settings from the Export Settings form. var wantGenStub = document.getElementById('genStubCheck').checked; var language = document.getElementById('exportLanguage').value; var generatorStub_filename = document.getElementById( 'generatorStub_filename').value; if (wantBlockDef) { // User wants to export selected blocks' definitions. if (!blockDef_filename) { // User needs to enter filename. var msg = 'Please enter a filename for your block definition(s) download.'; BlocklyDevTools.Analytics.onWarning(msg); alert(msg); } else { // Get block definition code in the selected format for the blocks. var blockDefs = this.tools.getBlockDefinitions(blockXmlMap, definitionFormat); // Download the file, using .js file ending for JSON or Javascript. FactoryUtils.createAndDownloadFile( blockDefs, blockDef_filename, 'javascript'); BlocklyDevTools.Analytics.onExport( BlocklyDevTools.Analytics.BLOCK_DEFINITIONS, { format: (definitionFormat == 'JSON' ? BlocklyDevTools.Analytics.FORMAT_JSON : BlocklyDevTools.Analytics.FORMAT_JS) }); } } if (wantGenStub) { // User wants to export selected blocks' generator stubs. if (!generatorStub_filename) { // User needs to enter filename. var msg = 'Please enter a filename for your generator stub(s) download.'; BlocklyDevTools.Analytics.onWarning(msg); alert(msg); } else { // Get generator stub code in the selected language for the blocks. var genStubs = this.tools.getGeneratorCode(blockXmlMap, language); // Get the correct file extension. var fileType = (language == 'JavaScript') ? 'javascript' : 'plain'; // Download the file. FactoryUtils.createAndDownloadFile( genStubs, generatorStub_filename + '.js', fileType); BlocklyDevTools.Analytics.onExport( BlocklyDevTools.Analytics.GENERATOR, (fileType == 'javascript' ? { format: BlocklyDevTools.Analytics.FORMAT_JS } : undefined)); } } }; /** * Update the Exporter's block selector with block options generated from blocks * stored in block library. */ BlockExporterController.prototype.updateSelector = function() { // Get previously selected block types. var oldSelectedTypes = this.view.getSelectedBlockTypes(); // Generate options from block library and assign to view. this.blockOptions = this.tools.createBlockSelectorFromLib( this.blockLibStorage, this.selectorID); this.addBlockOptionSelectHandlers(); this.view.setBlockOptions(this.blockOptions); // Select all previously selected blocks. for (var i = 0, blockType; blockType = oldSelectedTypes[i]; i++) { if (this.blockOptions[blockType]) { this.view.select(blockType); } } this.view.listSelectedBlocks(); }; /** * Tied to the 'Clear Selected Blocks' button in the Block Exporter. * Deselects all blocks in the selector and updates text accordingly. */ BlockExporterController.prototype.clearSelectedBlocks = function() { this.view.deselectAllBlocks(); this.view.listSelectedBlocks(); }; /** * Tied to the 'All Stored' button in the Block Exporter 'Select' dropdown. * Selects all blocks stored in block library for export. */ BlockExporterController.prototype.selectAllBlocks = function() { var allBlockTypes = this.blockLibStorage.getBlockTypes(); for (var i = 0, blockType; blockType = allBlockTypes[i]; i++) { this.view.select(blockType); } this.view.listSelectedBlocks(); }; /** * Returns the category XML containing all blocks in the block library. * @return {Element} XML for a category to be used in toolbox. */ BlockExporterController.prototype.getBlockLibraryCategory = function() { return this.tools.generateCategoryFromBlockLib(this.blockLibStorage); }; /** * Add select handlers to each block option to update the view and the selected * blocks accordingly. */ BlockExporterController.prototype.addBlockOptionSelectHandlers = function() { var self = this; // Click handler for a block option. Toggles whether or not it's selected and // updates helper text accordingly. var updateSelectedBlockTypes_ = function(blockOption) { // Toggle selected. blockOption.setSelected(!blockOption.isSelected()); // Show currently selected blocks in helper text. self.view.listSelectedBlocks(); }; // Returns a block option select handler. var makeBlockOptionSelectHandler_ = function(blockOption) { return function() { updateSelectedBlockTypes_(blockOption); self.updatePreview(); }; }; // Assign a click handler to each block option. for (var blockType in this.blockOptions) { var blockOption = this.blockOptions[blockType]; // Use an additional closure to correctly assign the tab callback. blockOption.dom.addEventListener( 'click', makeBlockOptionSelectHandler_(blockOption)); } }; /** * Tied to the 'All Used' button in the Block Exporter's 'Select' button. * Selects all blocks stored in block library and used in workspace factory. */ BlockExporterController.prototype.selectUsedBlocks = function() { // Deselect all blocks. this.view.deselectAllBlocks(); // Get list of block types that are in block library and used in workspace // factory. var storedBlockTypes = this.blockLibStorage.getBlockTypes(); var sharedBlockTypes = []; // Keep list of custom block types used but not in library. var unstoredCustomBlockTypes = []; for (var i = 0, blockType; blockType = this.usedBlockTypes[i]; i++) { if (storedBlockTypes.indexOf(blockType) != -1) { sharedBlockTypes.push(blockType); } else if (StandardCategories.coreBlockTypes.indexOf(blockType) == -1) { unstoredCustomBlockTypes.push(blockType); } } // Select each shared block type. for (var i = 0, blockType; blockType = sharedBlockTypes[i]; i++) { this.view.select(blockType); } this.view.listSelectedBlocks(); if (unstoredCustomBlockTypes.length > 0){ // Warn user to import block defifnitions and generator code for blocks // not in their Block Library nor Blockly's standard library. var blockTypesText = unstoredCustomBlockTypes.join(', '); var customWarning = 'Custom blocks used in workspace factory but not ' + 'stored in block library:\n ' + blockTypesText + '\n\nDon\'t forget to include block definitions and generator code ' + 'for these blocks.'; alert(customWarning); } }; /** * Set the array that holds the block types used in workspace factory. * @param {!Array.<string>} usedBlockTypes Block types used in */ BlockExporterController.prototype.setUsedBlockTypes = function(usedBlockTypes) { this.usedBlockTypes = usedBlockTypes; }; /** * Updates preview code (block definitions and generator stubs) in the exporter * preview to reflect selected blocks. */ BlockExporterController.prototype.updatePreview = function() { // Generate preview code for selected blocks. var blockDefs = this.getBlockDefinitionsOfSelected(); var genStubs = this.getGeneratorStubsOfSelected(); // Update the text areas containing the code. FactoryUtils.injectCode(blockDefs, 'blockDefs_textArea'); FactoryUtils.injectCode(genStubs, 'genStubs_textArea'); }; /** * Returns a map of each selected block's type to its corresponding XML. * @return {!Object} A map of each selected block's type (a string) to its * corresponding XML element. */ BlockExporterController.prototype.getSelectedBlockXmlMap = function() { var blockTypes = this.view.getSelectedBlockTypes(); return this.blockLibStorage.getBlockXmlMap(blockTypes); }; /** * Get block definition code in the selected format for selected blocks. * @return {string} The concatenation of each selected block's language code * in the format specified in export settings. */ BlockExporterController.prototype.getBlockDefinitionsOfSelected = function() { // Get selected blocks' information. var blockXmlMap = this.getSelectedBlockXmlMap(); // Get block definition code in the selected format for the blocks. var definitionFormat = document.getElementById('exportFormat').value; return this.tools.getBlockDefinitions(blockXmlMap, definitionFormat); }; /** * Get generator stubs in the selected language for selected blocks. * @return {string} The concatenation of each selected block's generator stub * in the language specified in export settings. */ BlockExporterController.prototype.getGeneratorStubsOfSelected = function() { // Get selected blocks' information. var blockXmlMap = this.getSelectedBlockXmlMap(); // Get generator stub code in the selected language for the blocks. var language = document.getElementById('exportLanguage').value; return this.tools.getGeneratorCode(blockXmlMap, language); };
Update block_exporter_controller.js Generator stub file type is set to javascript; unnecesarry conditions removed.
demos/blockfactory/block_exporter_controller.js
Update block_exporter_controller.js
<ide><path>emos/blockfactory/block_exporter_controller.js <ide> BlocklyDevTools.Analytics.onWarning(msg); <ide> alert(msg); <ide> } else { <add> <ide> // Get generator stub code in the selected language for the blocks. <ide> var genStubs = this.tools.getGeneratorCode(blockXmlMap, <ide> language); <del> // Get the correct file extension. <del> var fileType = (language == 'JavaScript') ? 'javascript' : 'plain'; <add> <ide> // Download the file. <ide> FactoryUtils.createAndDownloadFile( <del> genStubs, generatorStub_filename + '.js', fileType); <add> genStubs, generatorStub_filename + '.js', 'javascript'); <ide> BlocklyDevTools.Analytics.onExport( <del> BlocklyDevTools.Analytics.GENERATOR, <del> (fileType == 'javascript' ? <del> { format: BlocklyDevTools.Analytics.FORMAT_JS } : undefined)); <add> BlocklyDevTools.Analytics.GENERATOR, { format: BlocklyDevTools.Analytics.FORMAT_JS }); <ide> } <ide> } <ide>
Java
apache-2.0
cf30047a1fffb5c36330a563e307cc65b5965ba7
0
dbrant/apps-android-wikipedia,wikimedia/apps-android-wikipedia,wikimedia/apps-android-wikipedia,wikimedia/apps-android-wikipedia,dbrant/apps-android-wikipedia,dbrant/apps-android-wikipedia,dbrant/apps-android-wikipedia,dbrant/apps-android-wikipedia,wikimedia/apps-android-wikipedia
package org.wikipedia.random; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.TextView; import org.wikipedia.R; import org.wikipedia.WikipediaApp; import org.wikipedia.dataclient.restbase.page.RbPageSummary; import org.wikipedia.page.PageTitle; import org.wikipedia.util.log.L; import org.wikipedia.views.FaceAndColorDetectImageView; import org.wikipedia.views.GoneIfEmptyTextView; import org.wikipedia.views.WikiErrorView; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import retrofit2.Call; public class RandomItemFragment extends Fragment { @BindView(R.id.random_item_container) ViewGroup containerView; @BindView(R.id.random_item_progress) View progressBar; @BindView(R.id.view_featured_article_card_image) FaceAndColorDetectImageView imageView; @BindView(R.id.view_featured_article_card_article_title) TextView articleTitleView; @BindView(R.id.view_featured_article_card_article_subtitle) GoneIfEmptyTextView articleSubtitleView; @BindView(R.id.view_featured_article_card_extract) TextView extractView; @BindView(R.id.random_item_error_view) WikiErrorView errorView; @Nullable private RbPageSummary summary; private int pagerPosition = -1; @NonNull public static RandomItemFragment newInstance() { return new RandomItemFragment(); } public void setPagerPosition(int position) { pagerPosition = position; } public int getPagerPosition() { return pagerPosition; } public boolean isLoadComplete() { return summary != null; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.fragment_random_item, container, false); ButterKnife.bind(this, view); imageView.setLegacyVisibilityHandlingEnabled(true); errorView.setBackClickListener(v -> getActivity().finish()); errorView.setRetryClickListener(v -> { progressBar.setVisibility(View.VISIBLE); getRandomPage(); }); updateContents(); if (summary == null) { getRandomPage(); } return view; } private void getRandomPage() { new RandomSummaryClient().request(WikipediaApp.getInstance().getWikiSite(), new RandomSummaryClient.Callback() { @Override public void onSuccess(@NonNull Call<RbPageSummary> call, @NonNull RbPageSummary pageSummary) { summary = pageSummary; if (!isAdded()) { return; } updateContents(); parent().onChildLoaded(); } @Override public void onError(@NonNull Call<RbPageSummary> call, @NonNull Throwable t) { if (!isAdded()) { return; } setErrorState(t); } }); } private void setErrorState(@NonNull Throwable t) { L.e(t); errorView.setError(t); errorView.setVisibility(View.VISIBLE); progressBar.setVisibility(View.GONE); containerView.setVisibility(View.GONE); } @OnClick(R.id.view_featured_article_card_text_container) void onClick(View v) { if (getTitle() != null) { parent().onSelectPage(getTitle()); } } public void updateContents() { errorView.setVisibility(View.GONE); containerView.setVisibility(summary == null ? View.GONE : View.VISIBLE); progressBar.setVisibility(summary == null ? View.VISIBLE : View.GONE); if (summary == null) { return; } articleTitleView.setText(summary.getNormalizedTitle()); articleSubtitleView.setText(null); //summary.getDescription()); extractView.setText(summary.getExtract()); ViewTreeObserver observer = extractView.getViewTreeObserver(); observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (!isAdded() || extractView == null) { return; } int maxLines = extractView.getHeight() / extractView.getLineHeight() - 1; final int minLines = 3; extractView.setMaxLines(Math.max(maxLines, minLines)); extractView.getViewTreeObserver().removeOnGlobalLayoutListener(this); } }); imageView.loadImage(TextUtils.isEmpty(summary.getThumbnailUrl()) ? null : Uri.parse(summary.getThumbnailUrl())); } @Nullable public PageTitle getTitle() { return summary == null ? null : new PageTitle(summary.getTitle(), WikipediaApp.getInstance().getWikiSite()); } private RandomFragment parent() { return (RandomFragment) getActivity().getSupportFragmentManager().getFragments().get(0); } }
app/src/main/java/org/wikipedia/random/RandomItemFragment.java
package org.wikipedia.random; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.TextView; import org.wikipedia.R; import org.wikipedia.WikipediaApp; import org.wikipedia.dataclient.restbase.page.RbPageSummary; import org.wikipedia.page.PageTitle; import org.wikipedia.util.log.L; import org.wikipedia.views.FaceAndColorDetectImageView; import org.wikipedia.views.GoneIfEmptyTextView; import org.wikipedia.views.WikiErrorView; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import retrofit2.Call; public class RandomItemFragment extends Fragment { @BindView(R.id.random_item_container) ViewGroup containerView; @BindView(R.id.random_item_progress) View progressBar; @BindView(R.id.view_featured_article_card_image) FaceAndColorDetectImageView imageView; @BindView(R.id.view_featured_article_card_article_title) TextView articleTitleView; @BindView(R.id.view_featured_article_card_article_subtitle) GoneIfEmptyTextView articleSubtitleView; @BindView(R.id.view_featured_article_card_extract) TextView extractView; @BindView(R.id.random_item_error_view) WikiErrorView errorView; @Nullable private RbPageSummary summary; private int pagerPosition = -1; private View view; private boolean loadComplete; @NonNull public static RandomItemFragment newInstance() { return new RandomItemFragment(); } public void setPagerPosition(int position) { pagerPosition = position; } public int getPagerPosition() { return pagerPosition; } public boolean isLoadComplete() { return loadComplete; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); if (view == null || !containsData()) { view = inflater.inflate(R.layout.fragment_random_item, container, false); ButterKnife.bind(this, view); imageView.setLegacyVisibilityHandlingEnabled(true); setContents(null); errorView.setBackClickListener(v -> getActivity().finish()); errorView.setRetryClickListener(v -> { progressBar.setVisibility(View.VISIBLE); getRandomPage(); }); getRandomPage(); } return view; } private boolean containsData() { return !(TextUtils.isEmpty(articleTitleView.getText().toString()) || TextUtils.isEmpty(extractView.getText().toString())); } private void getRandomPage() { new RandomSummaryClient().request(WikipediaApp.getInstance().getWikiSite(), new RandomSummaryClient.Callback() { @Override public void onSuccess(@NonNull Call<RbPageSummary> call, @NonNull RbPageSummary pageSummary) { loadComplete = true; if (!isAdded()) { return; } setContents(pageSummary); parent().onChildLoaded(); } @Override public void onError(@NonNull Call<RbPageSummary> call, @NonNull Throwable t) { if (!isAdded()) { return; } setErrorState(t); } }); } private void setErrorState(@NonNull Throwable t) { L.e(t); errorView.setError(t); errorView.setVisibility(View.VISIBLE); progressBar.setVisibility(View.GONE); containerView.setVisibility(View.GONE); } @OnClick(R.id.view_featured_article_card_text_container) void onClick(View v) { if (getTitle() != null) { parent().onSelectPage(getTitle()); } } public void setContents(@Nullable RbPageSummary pageSummary) { errorView.setVisibility(View.GONE); containerView.setVisibility(pageSummary == null ? View.GONE : View.VISIBLE); progressBar.setVisibility(pageSummary == null ? View.VISIBLE : View.GONE); if (summary == pageSummary) { return; } summary = pageSummary; if (summary == null) { return; } articleTitleView.setText(summary.getNormalizedTitle()); articleSubtitleView.setText(null); //summary.getDescription()); extractView.setText(summary.getExtract()); ViewTreeObserver observer = extractView.getViewTreeObserver(); observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (!isAdded() || extractView == null) { return; } int maxLines = extractView.getHeight() / extractView.getLineHeight() - 1; final int minLines = 3; extractView.setMaxLines(Math.max(maxLines, minLines)); extractView.getViewTreeObserver().removeOnGlobalLayoutListener(this); } }); imageView.loadImage(TextUtils.isEmpty(summary.getThumbnailUrl()) ? null : Uri.parse(summary.getThumbnailUrl())); } @Nullable public PageTitle getTitle() { return summary == null ? null : new PageTitle(summary.getTitle(), WikipediaApp.getInstance().getWikiSite()); } private RandomFragment parent() { return (RandomFragment) getActivity().getSupportFragmentManager().getFragments().get(0); } }
Follow-up: simplify some logic in RandomItemFragment. Change-Id: I265fa9d8258af7b419a1d24b5e098e70b94582fc
app/src/main/java/org/wikipedia/random/RandomItemFragment.java
Follow-up: simplify some logic in RandomItemFragment.
<ide><path>pp/src/main/java/org/wikipedia/random/RandomItemFragment.java <ide> @BindView(R.id.view_featured_article_card_extract) TextView extractView; <ide> @BindView(R.id.random_item_error_view) WikiErrorView errorView; <ide> <del> <ide> @Nullable private RbPageSummary summary; <ide> private int pagerPosition = -1; <del> private View view; <del> private boolean loadComplete; <ide> <ide> @NonNull <ide> public static RandomItemFragment newInstance() { <ide> } <ide> <ide> public boolean isLoadComplete() { <del> return loadComplete; <add> return summary != null; <ide> } <ide> <ide> @Override <ide> @Override <ide> public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { <ide> super.onCreateView(inflater, container, savedInstanceState); <del> <del> if (view == null || !containsData()) { <del> view = inflater.inflate(R.layout.fragment_random_item, container, false); <del> ButterKnife.bind(this, view); <del> imageView.setLegacyVisibilityHandlingEnabled(true); <del> setContents(null); <del> errorView.setBackClickListener(v -> getActivity().finish()); <del> errorView.setRetryClickListener(v -> { <del> progressBar.setVisibility(View.VISIBLE); <del> getRandomPage(); <del> }); <add> View view = inflater.inflate(R.layout.fragment_random_item, container, false); <add> ButterKnife.bind(this, view); <add> imageView.setLegacyVisibilityHandlingEnabled(true); <add> errorView.setBackClickListener(v -> getActivity().finish()); <add> errorView.setRetryClickListener(v -> { <add> progressBar.setVisibility(View.VISIBLE); <add> getRandomPage(); <add> }); <add> updateContents(); <add> if (summary == null) { <ide> getRandomPage(); <ide> } <ide> return view; <del> } <del> <del> private boolean containsData() { <del> return !(TextUtils.isEmpty(articleTitleView.getText().toString()) || TextUtils.isEmpty(extractView.getText().toString())); <ide> } <ide> <ide> private void getRandomPage() { <ide> new RandomSummaryClient().request(WikipediaApp.getInstance().getWikiSite(), new RandomSummaryClient.Callback() { <ide> @Override <ide> public void onSuccess(@NonNull Call<RbPageSummary> call, @NonNull RbPageSummary pageSummary) { <del> loadComplete = true; <add> summary = pageSummary; <ide> if (!isAdded()) { <ide> return; <ide> } <del> setContents(pageSummary); <add> updateContents(); <ide> parent().onChildLoaded(); <ide> } <ide> <ide> } <ide> } <ide> <del> public void setContents(@Nullable RbPageSummary pageSummary) { <add> public void updateContents() { <ide> errorView.setVisibility(View.GONE); <del> containerView.setVisibility(pageSummary == null ? View.GONE : View.VISIBLE); <del> progressBar.setVisibility(pageSummary == null ? View.VISIBLE : View.GONE); <del> if (summary == pageSummary) { <del> return; <del> } <del> summary = pageSummary; <add> containerView.setVisibility(summary == null ? View.GONE : View.VISIBLE); <add> progressBar.setVisibility(summary == null ? View.VISIBLE : View.GONE); <ide> if (summary == null) { <ide> return; <ide> }
JavaScript
mit
7f8398ab89229c57b07e4829a70ac727a7a3019f
0
fastauction/auction-site,fastauction/auction-site,fastauction/auction-site,fastauction/auction-site
$(function(){ url = "http://rss.autoweek.com/?page=n-55998"; $.ajax({ type: "GET", url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q=' + encodeURIComponent(url), dataType: 'json', error: function(){ console.alert('autoweek rss feed not loaded'); }, success: function(xml){ values = xml.responseData.feed.entries; console.info("Current Autoweek RSS feed: ",values); console.info(values[0].title); console.info(values[0].contentSnippet); $(".rss-feed").append("<span>" + values[0].title + " --- " + values[0].contentSnippet + " --- " + values[1].title + " --- "+ values[1].contentSnippet + " --- " + values[2].title + " --- " + values[2].title + " --- " + values[3].title + " --- " + values[3].contentSnippet + " --- " + values[4].title + " --- "+ values[4].contentSnippet + " --- " + values[5].title + " --- " + values[5].title + "</span>"); } }); });
js/auction-project/rss-feed.js
$(function(){ url = "http://rss.autoweek.com/?page=n-55998"; $.ajax({ type: "GET", url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q=' + encodeURIComponent(url), dataType: 'json', error: function(){ console.alert('autoweek rss feed not loaded'); }, success: function(xml){ values = xml.responseData.feed.entries; console.info("Current Autoweek RSS feed: ",values); console.info(values[0].title); console.info(values[0].contentSnippet); $(".rss-feed").append("<span>" + values[0].title + " --- " + values[0].contentSnippet + " --- " + values[1].title + " --- "+ values[1].contentSnippet + " --- " + values[2].title + " --- " + values[2].title + "</span>"); } }); });
add more items to rss feed
js/auction-project/rss-feed.js
add more items to rss feed
<ide><path>s/auction-project/rss-feed.js <ide> console.info("Current Autoweek RSS feed: ",values); <ide> console.info(values[0].title); <ide> console.info(values[0].contentSnippet); <del> $(".rss-feed").append("<span>" + values[0].title + " --- " + values[0].contentSnippet + " --- " + values[1].title + " --- "+ values[1].contentSnippet + " --- " + values[2].title + " --- " + values[2].title + "</span>"); <add> $(".rss-feed").append("<span>" + values[0].title + " --- " + values[0].contentSnippet + " --- " + values[1].title + " --- "+ values[1].contentSnippet + " --- " + values[2].title + " --- " + values[2].title + " --- " + values[3].title + " --- " + values[3].contentSnippet + " --- " + values[4].title + " --- "+ values[4].contentSnippet + " --- " + values[5].title + " --- " + values[5].title + "</span>"); <ide> } <ide> }); <ide> });
Java
apache-2.0
efd948c4bcab8ec6cf842d2dba5e9479e06af135
0
pwoodworth/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,caot/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,supersven/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,semonte/intellij-community,signed/intellij-community,kdwink/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,allotria/intellij-community,supersven/intellij-community,semonte/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,ernestp/consulo,salguarnieri/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,consulo/consulo,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,caot/intellij-community,retomerz/intellij-community,samthor/intellij-community,jagguli/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,ryano144/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,diorcety/intellij-community,signed/intellij-community,asedunov/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,xfournet/intellij-community,caot/intellij-community,fitermay/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,ahb0327/intellij-community,caot/intellij-community,xfournet/intellij-community,izonder/intellij-community,kdwink/intellij-community,xfournet/intellij-community,hurricup/intellij-community,fnouama/intellij-community,supersven/intellij-community,retomerz/intellij-community,apixandru/intellij-community,jagguli/intellij-community,ernestp/consulo,ol-loginov/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,supersven/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,allotria/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,signed/intellij-community,da1z/intellij-community,izonder/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,petteyg/intellij-community,vladmm/intellij-community,slisson/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,allotria/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,izonder/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,diorcety/intellij-community,robovm/robovm-studio,allotria/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,FHannes/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,semonte/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,kool79/intellij-community,FHannes/intellij-community,samthor/intellij-community,fitermay/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,ernestp/consulo,adedayo/intellij-community,supersven/intellij-community,fnouama/intellij-community,asedunov/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,fitermay/intellij-community,dslomov/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,da1z/intellij-community,amith01994/intellij-community,vladmm/intellij-community,supersven/intellij-community,holmes/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,slisson/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,caot/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,Lekanich/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,amith01994/intellij-community,fnouama/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,holmes/intellij-community,robovm/robovm-studio,vladmm/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,FHannes/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,izonder/intellij-community,Lekanich/intellij-community,semonte/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,izonder/intellij-community,allotria/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,blademainer/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,da1z/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,caot/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,kdwink/intellij-community,adedayo/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,kool79/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,petteyg/intellij-community,holmes/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,asedunov/intellij-community,adedayo/intellij-community,fnouama/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,asedunov/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,signed/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,consulo/consulo,kdwink/intellij-community,retomerz/intellij-community,holmes/intellij-community,da1z/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,holmes/intellij-community,supersven/intellij-community,blademainer/intellij-community,dslomov/intellij-community,ibinti/intellij-community,signed/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,da1z/intellij-community,semonte/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,blademainer/intellij-community,robovm/robovm-studio,semonte/intellij-community,signed/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,caot/intellij-community,blademainer/intellij-community,hurricup/intellij-community,kdwink/intellij-community,semonte/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,retomerz/intellij-community,asedunov/intellij-community,ernestp/consulo,nicolargo/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,signed/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,kool79/intellij-community,supersven/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,tmpgit/intellij-community,samthor/intellij-community,supersven/intellij-community,allotria/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,caot/intellij-community,Lekanich/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,retomerz/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,adedayo/intellij-community,ryano144/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,da1z/intellij-community,diorcety/intellij-community,asedunov/intellij-community,slisson/intellij-community,da1z/intellij-community,consulo/consulo,dslomov/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,amith01994/intellij-community,consulo/consulo,apixandru/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,fnouama/intellij-community,ryano144/intellij-community,holmes/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,dslomov/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,caot/intellij-community,semonte/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,signed/intellij-community,diorcety/intellij-community,holmes/intellij-community,semonte/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,allotria/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,tmpgit/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,apixandru/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,holmes/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,ernestp/consulo,caot/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,kool79/intellij-community,petteyg/intellij-community,robovm/robovm-studio,FHannes/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,da1z/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,holmes/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,allotria/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,dslomov/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,slisson/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,samthor/intellij-community,xfournet/intellij-community,fitermay/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,consulo/consulo,suncycheng/intellij-community,semonte/intellij-community,blademainer/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,caot/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,hurricup/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,slisson/intellij-community,ibinti/intellij-community,consulo/consulo,ftomassetti/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,samthor/intellij-community,hurricup/intellij-community,amith01994/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,slisson/intellij-community,Lekanich/intellij-community,samthor/intellij-community,hurricup/intellij-community,vladmm/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,fitermay/intellij-community,kdwink/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,izonder/intellij-community,asedunov/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,ernestp/consulo,amith01994/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,slisson/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,kool79/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,kool79/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,gnuhub/intellij-community
/* * Copyright 2000-2009 JetBrains s.r.o. * * 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.intellij.codeInsight.hint; import com.intellij.codeInsight.lookup.Lookup; import com.intellij.codeInsight.lookup.LookupManager; import com.intellij.codeInsight.lookup.impl.LookupImpl; import com.intellij.lang.parameterInfo.*; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.RangeMarker; import com.intellij.openapi.editor.ScrollType; import com.intellij.openapi.editor.event.*; import com.intellij.openapi.editor.impl.EditorImpl; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Pair; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiUtilBase; import com.intellij.ui.LightweightHint; import com.intellij.util.Alarm; import com.intellij.util.ArrayUtil; import com.intellij.util.text.CharArrayUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.List; public class ParameterInfoController { private final Project myProject; @NotNull private final Editor myEditor; private final String myParameterCloseChars; private final RangeMarker myLbraceMarker; private final LightweightHint myHint; private final ParameterInfoComponent myComponent; private final CaretListener myEditorCaretListener; private final DocumentListener myEditorDocumentListener; private final PropertyChangeListener myLookupListener; @NotNull private final ParameterInfoHandler<Object, Object> myHandler; private final ShowParameterInfoHandler.BestLocationPointProvider myProvider; private final Alarm myAlarm = new Alarm(); private static final int DELAY = 200; private boolean myDisposed = false; /** * Keeps Vector of ParameterInfoController's in Editor */ private static final Key<ArrayList<ParameterInfoController>> ALL_CONTROLLERS_KEY = Key.create("ParameterInfoController.ALL_CONTROLLERS_KEY"); public static ParameterInfoController findControllerAtOffset(Editor editor, int offset) { ArrayList<ParameterInfoController> allControllers = getAllControllers(editor); for (int i = 0; i < allControllers.size(); ++i) { ParameterInfoController controller = allControllers.get(i); if (controller.myLbraceMarker.getStartOffset() == offset) { if (controller.myHint.isVisible()) return controller; controller.dispose(); --i; } } return null; } public Object[] getSelectedElements() { ParameterInfoContext context = new ParameterInfoContext() { @Override public Project getProject() { return myProject; } @Override public PsiFile getFile() { return myComponent.getParameterOwner().getContainingFile(); } @Override public int getOffset() { return myEditor.getCaretModel().getOffset(); } @Override @NotNull public Editor getEditor() { return myEditor; } }; if (!myHandler.tracksParameterIndex()) { return myHandler.getParametersForDocumentation(myComponent.getObjects()[0],context); } final Object[] objects = myComponent.getObjects(); int selectedParameterIndex = myComponent.getCurrentParameterIndex(); List<Object> params = new ArrayList<Object>(objects.length); final Object highlighted = myComponent.getHighlighted(); for(Object o:objects) { if (highlighted != null && !o.equals(highlighted)) continue; collectParams(context, selectedParameterIndex, params, o); } //choose anything when highlighted is not applicable if (highlighted != null && params.isEmpty()) { for (Object o : objects) { collectParams(context, selectedParameterIndex, params, o); } } return ArrayUtil.toObjectArray(params); } private void collectParams(ParameterInfoContext context, int selectedParameterIndex, List<Object> params, Object o) { final Object[] availableParams = myHandler.getParametersForDocumentation(o, context); if (availableParams != null && selectedParameterIndex < availableParams.length && selectedParameterIndex >= 0 ) { params.add(availableParams[selectedParameterIndex]); } } private static ArrayList<ParameterInfoController> getAllControllers(@NotNull Editor editor) { ArrayList<ParameterInfoController> array = editor.getUserData(ALL_CONTROLLERS_KEY); if (array == null){ array = new ArrayList<ParameterInfoController>(); editor.putUserData(ALL_CONTROLLERS_KEY, array); } return array; } public static boolean isAlreadyShown(Editor editor, int lbraceOffset) { return findControllerAtOffset(editor, lbraceOffset) != null; } public ParameterInfoController(@NotNull Project project, @NotNull Editor editor, int lbraceOffset, @NotNull LightweightHint hint, @NotNull ParameterInfoHandler handler, @NotNull ShowParameterInfoHandler.BestLocationPointProvider provider) { myProject = project; myEditor = editor; myHandler = handler; myProvider = provider; myParameterCloseChars = handler.getParameterCloseChars(); myLbraceMarker = editor.getDocument().createRangeMarker(lbraceOffset, lbraceOffset); myHint = hint; myComponent = (ParameterInfoComponent)myHint.getComponent(); ArrayList<ParameterInfoController> allControllers = getAllControllers(myEditor); allControllers.add(this); myEditorCaretListener = new CaretListener(){ @Override public void caretPositionChanged(CaretEvent e) { if (!myHandler.tracksParameterIndex()) { myAlarm.cancelAllRequests(); addAlarmRequest(); return; } int oldOffset = e.getEditor().logicalPositionToOffset(e.getOldPosition()); int newOffset = e.getEditor().logicalPositionToOffset(e.getNewPosition()); if (newOffset <= myLbraceMarker.getStartOffset()){ myAlarm.cancelAllRequests(); addAlarmRequest(); return; } int offset1 = Math.min(oldOffset, newOffset); int offset2 = Math.max(oldOffset, newOffset); CharSequence chars = e.getEditor().getDocument().getCharsSequence(); int offset = CharArrayUtil.shiftForwardUntil(chars, offset1, myParameterCloseChars); if (offset < offset2){ myAlarm.cancelAllRequests(); addAlarmRequest(); } else{ if (myAlarm.cancelAllRequests() > 0){ addAlarmRequest(); } } } }; myEditor.getCaretModel().addCaretListener(myEditorCaretListener); myEditorDocumentListener = new DocumentAdapter(){ @Override public void documentChanged(DocumentEvent e) { if (!myHandler.tracksParameterIndex()) { myAlarm.cancelAllRequests(); addAlarmRequest(); return; } CharSequence oldS = e.getOldFragment(); if (CharArrayUtil.shiftForwardUntil(oldS, 0, myParameterCloseChars) < oldS.length()){ myAlarm.cancelAllRequests(); addAlarmRequest(); return; } CharSequence newS = e.getNewFragment(); if (CharArrayUtil.shiftForwardUntil(newS, 0, myParameterCloseChars) < newS.length()){ myAlarm.cancelAllRequests(); addAlarmRequest(); return; } if (myAlarm.cancelAllRequests() > 0){ addAlarmRequest(); } } }; myEditor.getDocument().addDocumentListener(myEditorDocumentListener); myLookupListener = new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if (LookupManager.PROP_ACTIVE_LOOKUP.equals(evt.getPropertyName())){ final LookupImpl lookup = (LookupImpl)evt.getNewValue(); if (lookup != null && lookup.isShown()){ adjustPositionForLookup(lookup); } } } }; LookupManager.getInstance(project).addPropertyChangeListener(myLookupListener); updateComponent(); if (myEditor instanceof EditorImpl) { Disposer.register(((EditorImpl)myEditor).getDisposable(), new Disposable() { @Override public void dispose() { ParameterInfoController.this.dispose(); } }); } } private void dispose(){ if (myDisposed) return; myDisposed = true; ArrayList<ParameterInfoController> allControllers = getAllControllers(myEditor); allControllers.remove(this); myEditor.getCaretModel().removeCaretListener(myEditorCaretListener); myEditor.getDocument().removeDocumentListener(myEditorDocumentListener); LookupManager.getInstance(myProject).removePropertyChangeListener(myLookupListener); } private void adjustPositionForLookup(@NotNull Lookup lookup) { if (!myHint.isVisible() || myEditor.isDisposed()) { dispose(); return; } HintManagerImpl hintManager = HintManagerImpl.getInstanceImpl(); short constraint = lookup.isPositionedAboveCaret() ? HintManager.UNDER : HintManager.ABOVE; Point p = hintManager.getHintPosition(myHint, myEditor, constraint); //Dimension hintSize = myHint.getComponent().getPreferredSize(); //JLayeredPane layeredPane = myEditor.getComponent().getRootPane().getLayeredPane(); //p.x = Math.min(p.x, layeredPane.getWidth() - hintSize.width); //p.x = Math.max(p.x, 0); myHint.updateBounds(p.x, p.y); } private void addAlarmRequest(){ Runnable request = new Runnable(){ @Override public void run(){ if (!myDisposed && !myProject.isDisposed()) updateComponent(); } }; myAlarm.addRequest(request, DELAY, ModalityState.stateForComponent(myEditor.getComponent())); } private void updateComponent(){ if (!myHint.isVisible()){ dispose(); return; } PsiDocumentManager.getInstance(myProject).commitAllDocuments(); final PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument()); CharSequence chars = myEditor.getDocument().getCharsSequence(); final int offset = CharArrayUtil.shiftBackward(chars, myEditor.getCaretModel().getOffset() - 1, " \t") + 1; final UpdateParameterInfoContext context = new MyUpdateParameterInfoContext(offset, file); final Object elementForUpdating = myHandler.findElementForUpdatingParameterInfo(context); if (elementForUpdating != null) { myHandler.updateParameterInfo(elementForUpdating, context); if (myHint.isVisible() && myEditor.getComponent().getRootPane() != null) { myComponent.update(); Pair<Point,Short> pos = myProvider.getBestPointPosition(myHint, (PsiElement)elementForUpdating, offset, true, HintManager.UNDER); HintManagerImpl.adjustEditorHintPosition(myHint, myEditor, pos.getFirst(), pos.getSecond()); } } else { context.removeHint(); } } public static void nextParameter (Editor editor, int lbraceOffset) { final ParameterInfoController controller = findControllerAtOffset(editor, lbraceOffset); if (controller != null) controller.prevOrNextParameter(true, (ParameterInfoHandlerWithTabActionSupport)controller.myHandler); } public static void prevParameter (Editor editor, int lbraceOffset) { final ParameterInfoController parameterInfoController = findControllerAtOffset(editor, lbraceOffset); if (parameterInfoController != null) parameterInfoController.prevOrNextParameter(false, (ParameterInfoHandlerWithTabActionSupport)parameterInfoController.myHandler); } private void prevOrNextParameter(boolean isNext, ParameterInfoHandlerWithTabActionSupport handler) { final PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument()); CharSequence chars = myEditor.getDocument().getCharsSequence(); int offset = CharArrayUtil.shiftBackward(chars, myEditor.getCaretModel().getOffset() - 1, " \t") + 1; int lbraceOffset = myLbraceMarker.getStartOffset(); if (lbraceOffset < offset) { PsiElement argList = findArgumentList(file, offset, lbraceOffset); if (argList != null) { int currentParameterIndex = ParameterInfoUtils.getCurrentParameterIndex(argList.getNode(), offset, handler.getActualParameterDelimiterType()); PsiElement currentParameter = null; if (currentParameterIndex > 0 && !isNext) { currentParameter = handler.getActualParameters(argList)[currentParameterIndex - 1]; } else if (currentParameterIndex < handler.getActualParameters(argList).length - 1 && isNext) { currentParameter = handler.getActualParameters(argList)[currentParameterIndex + 1]; } if (currentParameter != null) { offset = currentParameter.getTextRange().getStartOffset(); myEditor.getCaretModel().moveToOffset(offset); myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); myEditor.getSelectionModel().removeSelection(); handler.updateParameterInfo(argList, new MyUpdateParameterInfoContext(offset, file)); } } } } @Nullable public static <E extends PsiElement> E findArgumentList(PsiFile file, int offset, int lbraceOffset){ if (file == null) return null; ParameterInfoHandler[] handlers = ShowParameterInfoHandler.getHandlers(file.getProject(), PsiUtilBase.getLanguageAtOffset(file, offset), file.getViewProvider().getBaseLanguage()); if (handlers != null) { for(ParameterInfoHandler handler:handlers) { if (handler instanceof ParameterInfoHandlerWithTabActionSupport) { final ParameterInfoHandlerWithTabActionSupport parameterInfoHandler2 = (ParameterInfoHandlerWithTabActionSupport)handler; final E e = (E)ParameterInfoUtils.findArgumentList(file, offset, lbraceOffset, parameterInfoHandler2); if (e != null) return e; } } } return null; } private class MyUpdateParameterInfoContext implements UpdateParameterInfoContext { private final int myOffset; private final PsiFile myFile; public MyUpdateParameterInfoContext(final int offset, final PsiFile file) { myOffset = offset; myFile = file; } @Override public int getParameterListStart() { return myLbraceMarker.getStartOffset(); } @Override public int getOffset() { return myOffset; } @Override public Project getProject() { return myProject; } @Override public PsiFile getFile() { return myFile; } @Override @NotNull public Editor getEditor() { return myEditor; } @Override public void removeHint() { myHint.hide(); dispose(); } @Override public void setParameterOwner(final PsiElement o) { myComponent.setParameterOwner(o); } @Override public PsiElement getParameterOwner() { return myComponent.getParameterOwner(); } @Override public void setHighlightedParameter(final Object method) { myComponent.setHighlightedParameter(method); } @Override public void setCurrentParameter(final int index) { myComponent.setCurrentParameterIndex(index); } @Override public boolean isUIComponentEnabled(int index) { return myComponent.isEnabled(index); } @Override public void setUIComponentEnabled(int index, boolean b) { myComponent.setEnabled(index, b); } @Override public Object[] getObjectsToView() { return myComponent.getObjects(); } } }
platform/lang-impl/src/com/intellij/codeInsight/hint/ParameterInfoController.java
/* * Copyright 2000-2009 JetBrains s.r.o. * * 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.intellij.codeInsight.hint; import com.intellij.codeInsight.lookup.Lookup; import com.intellij.codeInsight.lookup.LookupManager; import com.intellij.codeInsight.lookup.impl.LookupImpl; import com.intellij.lang.parameterInfo.*; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.RangeMarker; import com.intellij.openapi.editor.ScrollType; import com.intellij.openapi.editor.event.*; import com.intellij.openapi.editor.impl.EditorImpl; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Pair; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiUtilBase; import com.intellij.ui.LightweightHint; import com.intellij.util.Alarm; import com.intellij.util.ArrayUtil; import com.intellij.util.text.CharArrayUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.List; public class ParameterInfoController { private final Project myProject; @NotNull private final Editor myEditor; private final String myParameterCloseChars; private final RangeMarker myLbraceMarker; private final LightweightHint myHint; private final ParameterInfoComponent myComponent; private final CaretListener myEditorCaretListener; private final DocumentListener myEditorDocumentListener; private final PropertyChangeListener myLookupListener; @NotNull private final ParameterInfoHandler<Object, Object> myHandler; private final ShowParameterInfoHandler.BestLocationPointProvider myProvider; private final Alarm myAlarm = new Alarm(); private static final int DELAY = 200; private boolean myDisposed = false; /** * Keeps Vector of ParameterInfoController's in Editor */ private static final Key<ArrayList<ParameterInfoController>> ALL_CONTROLLERS_KEY = Key.create("ParameterInfoController.ALL_CONTROLLERS_KEY"); public static ParameterInfoController findControllerAtOffset(Editor editor, int offset) { ArrayList<ParameterInfoController> allControllers = getAllControllers(editor); for (int i = 0; i < allControllers.size(); ++i) { ParameterInfoController controller = allControllers.get(i); if (controller.myLbraceMarker.getStartOffset() == offset) { if (controller.myHint.isVisible()) return controller; controller.dispose(); --i; } } return null; } public Object[] getSelectedElements() { ParameterInfoContext context = new ParameterInfoContext() { @Override public Project getProject() { return myProject; } @Override public PsiFile getFile() { return myComponent.getParameterOwner().getContainingFile(); } @Override public int getOffset() { return myEditor.getCaretModel().getOffset(); } @Override @NotNull public Editor getEditor() { return myEditor; } }; if (!myHandler.tracksParameterIndex()) { return myHandler.getParametersForDocumentation(myComponent.getObjects()[0],context); } final Object[] objects = myComponent.getObjects(); int selectedParameterIndex = myComponent.getCurrentParameterIndex(); List<Object> params = new ArrayList<Object>(objects.length); final Object highlighted = myComponent.getHighlighted(); for(Object o:objects) { if (highlighted != null && !o.equals(highlighted)) continue; collectParams(context, selectedParameterIndex, params, o); } //choose anything when highlighted is not applicable if (highlighted != null && params.isEmpty()) { for (Object o : objects) { collectParams(context, selectedParameterIndex, params, o); } } return ArrayUtil.toObjectArray(params); } private void collectParams(ParameterInfoContext context, int selectedParameterIndex, List<Object> params, Object o) { final Object[] availableParams = myHandler.getParametersForDocumentation(o, context); if (availableParams != null && selectedParameterIndex < availableParams.length && selectedParameterIndex >= 0 ) { params.add(availableParams[selectedParameterIndex]); } } private static ArrayList<ParameterInfoController> getAllControllers(@NotNull Editor editor) { ArrayList<ParameterInfoController> array = editor.getUserData(ALL_CONTROLLERS_KEY); if (array == null){ array = new ArrayList<ParameterInfoController>(); editor.putUserData(ALL_CONTROLLERS_KEY, array); } return array; } public static boolean isAlreadyShown(Editor editor, int lbraceOffset) { return findControllerAtOffset(editor, lbraceOffset) != null; } public ParameterInfoController(@NotNull Project project, @NotNull Editor editor, int lbraceOffset, @NotNull LightweightHint hint, @NotNull ParameterInfoHandler handler, @NotNull ShowParameterInfoHandler.BestLocationPointProvider provider) { myProject = project; myEditor = editor; myHandler = handler; myProvider = provider; myParameterCloseChars = handler.getParameterCloseChars(); myLbraceMarker = editor.getDocument().createRangeMarker(lbraceOffset, lbraceOffset); myHint = hint; myComponent = (ParameterInfoComponent)myHint.getComponent(); ArrayList<ParameterInfoController> allControllers = getAllControllers(myEditor); allControllers.add(this); myEditorCaretListener = new CaretListener(){ @Override public void caretPositionChanged(CaretEvent e) { if (!myHandler.tracksParameterIndex()) { myAlarm.cancelAllRequests(); addAlarmRequest(); return; } int oldOffset = e.getEditor().logicalPositionToOffset(e.getOldPosition()); int newOffset = e.getEditor().logicalPositionToOffset(e.getNewPosition()); if (newOffset <= myLbraceMarker.getStartOffset()){ myAlarm.cancelAllRequests(); addAlarmRequest(); return; } int offset1 = Math.min(oldOffset, newOffset); int offset2 = Math.max(oldOffset, newOffset); CharSequence chars = e.getEditor().getDocument().getCharsSequence(); int offset = CharArrayUtil.shiftForwardUntil(chars, offset1, myParameterCloseChars); if (offset < offset2){ myAlarm.cancelAllRequests(); addAlarmRequest(); } else{ if (myAlarm.cancelAllRequests() > 0){ addAlarmRequest(); } } } }; myEditor.getCaretModel().addCaretListener(myEditorCaretListener); myEditorDocumentListener = new DocumentAdapter(){ @Override public void documentChanged(DocumentEvent e) { if (!myHandler.tracksParameterIndex()) { myAlarm.cancelAllRequests(); addAlarmRequest(); return; } CharSequence oldS = e.getOldFragment(); if (CharArrayUtil.shiftForwardUntil(oldS, 0, myParameterCloseChars) < oldS.length()){ myAlarm.cancelAllRequests(); addAlarmRequest(); return; } CharSequence newS = e.getNewFragment(); if (CharArrayUtil.shiftForwardUntil(newS, 0, myParameterCloseChars) < newS.length()){ myAlarm.cancelAllRequests(); addAlarmRequest(); return; } if (myAlarm.cancelAllRequests() > 0){ addAlarmRequest(); } } }; myEditor.getDocument().addDocumentListener(myEditorDocumentListener); myLookupListener = new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if (LookupManager.PROP_ACTIVE_LOOKUP.equals(evt.getPropertyName())){ final LookupImpl lookup = (LookupImpl)evt.getNewValue(); if (lookup != null && lookup.isShown()){ adjustPositionForLookup(lookup); } } } }; LookupManager.getInstance(project).addPropertyChangeListener(myLookupListener); updateComponent(); Disposer.register(((EditorImpl)myEditor).getDisposable(), new Disposable() { @Override public void dispose() { ParameterInfoController.this.dispose(); } }); } private void dispose(){ if (myDisposed) return; myDisposed = true; ArrayList<ParameterInfoController> allControllers = getAllControllers(myEditor); allControllers.remove(this); myEditor.getCaretModel().removeCaretListener(myEditorCaretListener); myEditor.getDocument().removeDocumentListener(myEditorDocumentListener); LookupManager.getInstance(myProject).removePropertyChangeListener(myLookupListener); } private void adjustPositionForLookup(@NotNull Lookup lookup) { if (!myHint.isVisible() || myEditor.isDisposed()) { dispose(); return; } HintManagerImpl hintManager = HintManagerImpl.getInstanceImpl(); short constraint = lookup.isPositionedAboveCaret() ? HintManager.UNDER : HintManager.ABOVE; Point p = hintManager.getHintPosition(myHint, myEditor, constraint); //Dimension hintSize = myHint.getComponent().getPreferredSize(); //JLayeredPane layeredPane = myEditor.getComponent().getRootPane().getLayeredPane(); //p.x = Math.min(p.x, layeredPane.getWidth() - hintSize.width); //p.x = Math.max(p.x, 0); myHint.updateBounds(p.x, p.y); } private void addAlarmRequest(){ Runnable request = new Runnable(){ @Override public void run(){ if (!myDisposed && !myProject.isDisposed()) updateComponent(); } }; myAlarm.addRequest(request, DELAY, ModalityState.stateForComponent(myEditor.getComponent())); } private void updateComponent(){ if (!myHint.isVisible()){ dispose(); return; } PsiDocumentManager.getInstance(myProject).commitAllDocuments(); final PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument()); CharSequence chars = myEditor.getDocument().getCharsSequence(); final int offset = CharArrayUtil.shiftBackward(chars, myEditor.getCaretModel().getOffset() - 1, " \t") + 1; final UpdateParameterInfoContext context = new MyUpdateParameterInfoContext(offset, file); final Object elementForUpdating = myHandler.findElementForUpdatingParameterInfo(context); if (elementForUpdating != null) { myHandler.updateParameterInfo(elementForUpdating, context); if (myHint.isVisible() && myEditor.getComponent().getRootPane() != null) { myComponent.update(); Pair<Point,Short> pos = myProvider.getBestPointPosition(myHint, (PsiElement)elementForUpdating, offset, true, HintManager.UNDER); HintManagerImpl.adjustEditorHintPosition(myHint, myEditor, pos.getFirst(), pos.getSecond()); } } else { context.removeHint(); } } public static void nextParameter (Editor editor, int lbraceOffset) { final ParameterInfoController controller = findControllerAtOffset(editor, lbraceOffset); if (controller != null) controller.prevOrNextParameter(true, (ParameterInfoHandlerWithTabActionSupport)controller.myHandler); } public static void prevParameter (Editor editor, int lbraceOffset) { final ParameterInfoController parameterInfoController = findControllerAtOffset(editor, lbraceOffset); if (parameterInfoController != null) parameterInfoController.prevOrNextParameter(false, (ParameterInfoHandlerWithTabActionSupport)parameterInfoController.myHandler); } private void prevOrNextParameter(boolean isNext, ParameterInfoHandlerWithTabActionSupport handler) { final PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument()); CharSequence chars = myEditor.getDocument().getCharsSequence(); int offset = CharArrayUtil.shiftBackward(chars, myEditor.getCaretModel().getOffset() - 1, " \t") + 1; int lbraceOffset = myLbraceMarker.getStartOffset(); if (lbraceOffset < offset) { PsiElement argList = findArgumentList(file, offset, lbraceOffset); if (argList != null) { int currentParameterIndex = ParameterInfoUtils.getCurrentParameterIndex(argList.getNode(), offset, handler.getActualParameterDelimiterType()); PsiElement currentParameter = null; if (currentParameterIndex > 0 && !isNext) { currentParameter = handler.getActualParameters(argList)[currentParameterIndex - 1]; } else if (currentParameterIndex < handler.getActualParameters(argList).length - 1 && isNext) { currentParameter = handler.getActualParameters(argList)[currentParameterIndex + 1]; } if (currentParameter != null) { offset = currentParameter.getTextRange().getStartOffset(); myEditor.getCaretModel().moveToOffset(offset); myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); myEditor.getSelectionModel().removeSelection(); handler.updateParameterInfo(argList, new MyUpdateParameterInfoContext(offset, file)); } } } } @Nullable public static <E extends PsiElement> E findArgumentList(PsiFile file, int offset, int lbraceOffset){ if (file == null) return null; ParameterInfoHandler[] handlers = ShowParameterInfoHandler.getHandlers(file.getProject(), PsiUtilBase.getLanguageAtOffset(file, offset), file.getViewProvider().getBaseLanguage()); if (handlers != null) { for(ParameterInfoHandler handler:handlers) { if (handler instanceof ParameterInfoHandlerWithTabActionSupport) { final ParameterInfoHandlerWithTabActionSupport parameterInfoHandler2 = (ParameterInfoHandlerWithTabActionSupport)handler; final E e = (E)ParameterInfoUtils.findArgumentList(file, offset, lbraceOffset, parameterInfoHandler2); if (e != null) return e; } } } return null; } private class MyUpdateParameterInfoContext implements UpdateParameterInfoContext { private final int myOffset; private final PsiFile myFile; public MyUpdateParameterInfoContext(final int offset, final PsiFile file) { myOffset = offset; myFile = file; } @Override public int getParameterListStart() { return myLbraceMarker.getStartOffset(); } @Override public int getOffset() { return myOffset; } @Override public Project getProject() { return myProject; } @Override public PsiFile getFile() { return myFile; } @Override @NotNull public Editor getEditor() { return myEditor; } @Override public void removeHint() { myHint.hide(); dispose(); } @Override public void setParameterOwner(final PsiElement o) { myComponent.setParameterOwner(o); } @Override public PsiElement getParameterOwner() { return myComponent.getParameterOwner(); } @Override public void setHighlightedParameter(final Object method) { myComponent.setHighlightedParameter(method); } @Override public void setCurrentParameter(final int index) { myComponent.setCurrentParameterIndex(index); } @Override public boolean isUIComponentEnabled(int index) { return myComponent.isEnabled(index); } @Override public void setUIComponentEnabled(int index, boolean b) { myComponent.setEnabled(index, b); } @Override public Object[] getObjectsToView() { return myComponent.getObjects(); } } }
make new dispose code available only for EditorImpl
platform/lang-impl/src/com/intellij/codeInsight/hint/ParameterInfoController.java
make new dispose code available only for EditorImpl
<ide><path>latform/lang-impl/src/com/intellij/codeInsight/hint/ParameterInfoController.java <ide> LookupManager.getInstance(project).addPropertyChangeListener(myLookupListener); <ide> <ide> updateComponent(); <del> Disposer.register(((EditorImpl)myEditor).getDisposable(), new Disposable() { <del> @Override <del> public void dispose() { <del> ParameterInfoController.this.dispose(); <del> } <del> }); <add> if (myEditor instanceof EditorImpl) { <add> Disposer.register(((EditorImpl)myEditor).getDisposable(), new Disposable() { <add> @Override <add> public void dispose() { <add> ParameterInfoController.this.dispose(); <add> } <add> }); <add> } <ide> } <ide> <ide> private void dispose(){
JavaScript
agpl-3.0
cc0e2acf62c16b0a0629b48aad02e69273a90e00
0
ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs
/* * (c) Copyright Ascensio System SIA 2010-2019 * * This program is a free software product. You can redistribute it and/or * modify it under the terms of the GNU Affero General Public License (AGPL) * version 3 as published by the Free Software Foundation. In accordance with * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect * that Ascensio System SIA expressly excludes the warranty of non-infringement * of any third-party rights. * * This program is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html * * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha * street, Riga, Latvia, EU, LV-1050. * * The interactive user interfaces in modified source and object code versions * of the Program must display Appropriate Legal Notices, as required under * Section 5 of the GNU AGPL version 3. * * Pursuant to Section 7(b) of the License you must retain the original Product * logo when distributing the program. Pursuant to Section 7(e) we decline to * grant you any rights under trademark law for use of our trademarks. * * All the Product's GUI elements, including illustrations and icon sets, as * well as technical writing content are licensed under the terms of the * Creative Commons Attribution-ShareAlike 4.0 International. See the License * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode * */ "use strict"; (/** * @param {Window} window * @param {undefined} undefined */ function(window, undefined) { /* * Import * ----------------------------------------------------------------------------- */ var c_oAscFormatPainterState = AscCommon.c_oAscFormatPainterState; var AscBrowser = AscCommon.AscBrowser; var CColor = AscCommon.CColor; var cBoolLocal = AscCommon.cBoolLocal; var History = AscCommon.History; var asc = window["Asc"]; var asc_applyFunction = AscCommonExcel.applyFunction; var asc_round = asc.round; var asc_typeof = asc.typeOf; var asc_CMM = AscCommonExcel.asc_CMouseMoveData; var asc_CPrintPagesData = AscCommonExcel.CPrintPagesData; var c_oTargetType = AscCommonExcel.c_oTargetType; var c_oAscError = asc.c_oAscError; var c_oAscCleanOptions = asc.c_oAscCleanOptions; var c_oAscSelectionDialogType = asc.c_oAscSelectionDialogType; var c_oAscMouseMoveType = asc.c_oAscMouseMoveType; var c_oAscPopUpSelectorType = asc.c_oAscPopUpSelectorType; var c_oAscAsyncAction = asc.c_oAscAsyncAction; var c_oAscFontRenderingModeType = asc.c_oAscFontRenderingModeType; var c_oAscAsyncActionType = asc.c_oAscAsyncActionType; var g_clipboardExcel = AscCommonExcel.g_clipboardExcel; function WorkbookCommentsModel(handlers, aComments) { this.workbook = {handlers: handlers}; this.aComments = aComments; } WorkbookCommentsModel.prototype.getId = function() { return null; }; WorkbookCommentsModel.prototype.getMergedByCell = function() { return null; }; function WorksheetViewSettings() { this.header = { style: [// Header colors { // kHeaderDefault background: new CColor(241, 241, 241), border: new CColor(213, 213, 213), color: new CColor(54, 54, 54) }, { // kHeaderActive background: new CColor(193, 193, 193), border: new CColor(146, 146, 146), color: new CColor(54, 54, 54) }, { // kHeaderHighlighted background: new CColor(223, 223, 223), border: new CColor(175, 175, 175), color: new CColor(101, 106, 112) }, { // kHeaderSelected background: new CColor(170, 170, 170), border: new CColor(117, 119, 122), color: new CColor(54, 54, 54) }], cornerColor: new CColor(193, 193, 193) }; this.cells = { defaultState: { background: new CColor(255, 255, 255), border: new CColor(202, 202, 202) }, padding: -1 /*px horizontal padding*/ }; this.activeCellBorderColor = new CColor(72, 121, 92); this.activeCellBorderColor2 = new CColor(255, 255, 255, 1); this.findFillColor = new CColor(255, 238, 128, 1); // Цвет закрепленных областей this.frozenColor = new CColor(105, 119, 62, 1); // Число знаков для математической информации this.mathMaxDigCount = 9; var cnv = document.createElement("canvas"); cnv.width = 2; cnv.height = 2; var ctx = cnv.getContext("2d"); ctx.clearRect(0, 0, 2, 2); ctx.fillStyle = "#000"; ctx.fillRect(0, 0, 1, 1); ctx.fillRect(1, 1, 1, 1); this.ptrnLineDotted1 = ctx.createPattern(cnv, "repeat"); this.halfSelection = false; return this; } /** * Widget for displaying and editing Workbook object * ----------------------------------------------------------------------------- * @param {AscCommonExcel.Workbook} model Workbook * @param {AscCommonExcel.asc_CEventsController} controller Events controller * @param {HandlersList} handlers Events handlers for WorkbookView events * @param {Element} elem Container element * @param {Element} inputElem Input element for top line editor * @param {Object} Api * @param {CCollaborativeEditing} collaborativeEditing * @param {c_oAscFontRenderingModeType} fontRenderingMode * * @constructor * @memberOf Asc */ function WorkbookView(model, controller, handlers, elem, inputElem, Api, collaborativeEditing, fontRenderingMode) { this.defaults = { scroll: { widthPx: 14, heightPx: 14 }, worksheetView: new WorksheetViewSettings() }; this.model = model; this.enableKeyEvents = true; this.controller = controller; this.handlers = handlers; this.wsViewHandlers = null; this.element = elem; this.input = inputElem; this.Api = Api; this.collaborativeEditing = collaborativeEditing; this.lastSendInfoRange = null; this.oSelectionInfo = null; this.canUpdateAfterShiftUp = false; // Нужно ли обновлять информацию после отпускания Shift this.keepType = false; this.timerId = null; this.timerEnd = false; //----- declaration ----- this.isInit = false; this.canvas = undefined; this.canvasOverlay = undefined; this.canvasGraphic = undefined; this.canvasGraphicOverlay = undefined; this.wsActive = -1; this.wsMustDraw = false; // Означает, что мы выставили активный, но не отрисовали его this.wsViews = []; this.cellEditor = undefined; this.fontRenderingMode = null; this.lockDraw = false; // Lock отрисовки на некоторое время this.isCellEditMode = false; this.isShowComments = true; this.isShowSolved = true; this.formulasList = []; // Список всех формул this.lastFPos = -1; // Последняя позиция формулы this.lastFNameLength = ''; // Последний кусок формулы this.skipHelpSelector = false; // Пока true - не показываем окно подсказки // Константы для подстановке формулы (что не нужно добавлять скобки) this.arrExcludeFormulas = []; this.fReplaceCallback = null; // Callback для замены текста // Фонт, который выставлен в DrawingContext, он должен быть один на все DrawingContext-ы this.m_oFont = AscCommonExcel.g_oDefaultFormat.Font.clone(); // Теперь у нас 2 FontManager-а на весь документ + 1 для автофигур (а не на каждом листе свой) this.fmgrGraphics = []; // FontManager for draw (1 для обычного + 1 для поворотного текста) this.fmgrGraphics.push(new AscFonts.CFontManager({mode:"cell"})); // Для обычного this.fmgrGraphics.push(new AscFonts.CFontManager({mode:"cell"})); // Для поворотного this.fmgrGraphics.push(new AscFonts.CFontManager()); // Для автофигур this.fmgrGraphics.push(new AscFonts.CFontManager({mode:"cell"})); // Для измерений this.fmgrGraphics[0].Initialize(true); // IE memory enable this.fmgrGraphics[1].Initialize(true); // IE memory enable this.fmgrGraphics[2].Initialize(true); // IE memory enable this.fmgrGraphics[3].Initialize(true); // IE memory enable this.buffers = {}; this.drawingCtx = undefined; this.overlayCtx = undefined; this.drawingGraphicCtx = undefined; this.overlayGraphicCtx = undefined; this.shapeCtx = null; this.shapeOverlayCtx = null; this.mainGraphics = undefined; this.stringRender = undefined; this.trackOverlay = null; this.autoShapeTrack = null; this.stateFormatPainter = c_oAscFormatPainterState.kOff; this.rangeFormatPainter = null; this.selectionDialogType = c_oAscSelectionDialogType.None; this.copyActiveSheet = -1; // Комментарии для всего документа this.cellCommentator = null; // Флаг о подписке на эвенты о смене позиции документа (скролл) для меню this.isDocumentPlaceChangedEnabled = false; // Максимальная ширина числа из 0,1,2...,9, померенная в нормальном шрифте(дефалтовый для книги) в px(целое) // Ecma-376 Office Open XML Part 1, пункт 18.3.1.13 this.maxDigitWidth = 0; //----------------------- this.MobileTouchManager = null; this.defNameAllowCreate = true; this._init(fontRenderingMode); this.autoCorrectStore = null;//объект для хранения параметров иконки авторазвертывания таблиц this.cutIdSheet = null; return this; } WorkbookView.prototype._init = function(fontRenderingMode) { var self = this; // Init font managers rendering // Изначально мы инициализируем c_oAscFontRenderingModeType.hintingAndSubpixeling this.setFontRenderingMode(fontRenderingMode, /*isInit*/true); // add style var _head = document.getElementsByTagName('head')[0]; var style0 = document.createElement('style'); style0.type = 'text/css'; style0.innerHTML = ".block_elem { position:absolute;padding:0;margin:0; }"; _head.appendChild(style0); // create canvas if (null != this.element) { this.element.innerHTML = '<div id="ws-canvas-outer">\ <canvas id="ws-canvas"></canvas>\ <canvas id="ws-canvas-overlay"></canvas>\ <canvas id="ws-canvas-graphic"></canvas>\ <canvas id="ws-canvas-graphic-overlay"></canvas>\ <canvas id="id_target_cursor" class="block_elem" width="1" height="1"\ style="width:2px;height:13px;display:none;z-index:9;"></canvas>\ </div>'; this.canvas = document.getElementById("ws-canvas"); this.canvasOverlay = document.getElementById("ws-canvas-overlay"); this.canvasGraphic = document.getElementById("ws-canvas-graphic"); this.canvasGraphicOverlay = document.getElementById("ws-canvas-graphic-overlay"); } this.buffers.main = new asc.DrawingContext({ canvas: this.canvas, units: 0/*px*/, fmgrGraphics: this.fmgrGraphics, font: this.m_oFont }); this.buffers.overlay = new asc.DrawingContext({ canvas: this.canvasOverlay, units: 0/*px*/, fmgrGraphics: this.fmgrGraphics, font: this.m_oFont }); this.buffers.mainGraphic = new asc.DrawingContext({ canvas: this.canvasGraphic, units: 0/*px*/, fmgrGraphics: this.fmgrGraphics, font: this.m_oFont }); this.buffers.overlayGraphic = new asc.DrawingContext({ canvas: this.canvasGraphicOverlay, units: 0/*px*/, fmgrGraphics: this.fmgrGraphics, font: this.m_oFont }); this.drawingCtx = this.buffers.main; this.overlayCtx = this.buffers.overlay; this.drawingGraphicCtx = this.buffers.mainGraphic; this.overlayGraphicCtx = this.buffers.overlayGraphic; this.shapeCtx = new AscCommon.CGraphics(); this.shapeOverlayCtx = new AscCommon.CGraphics(); this.mainGraphics = new AscCommon.CGraphics(); this.trackOverlay = new AscCommon.COverlay(); this.trackOverlay.IsCellEditor = true; this.autoShapeTrack = new AscCommon.CAutoshapeTrack(); this.shapeCtx.m_oAutoShapesTrack = this.autoShapeTrack; this.shapeCtx.m_oFontManager = this.fmgrGraphics[2]; this.shapeOverlayCtx.m_oFontManager = this.fmgrGraphics[2]; this.mainGraphics.m_oFontManager = this.fmgrGraphics[0]; // Обновляем размеры (чуть ниже, потому что должны быть проинициализированы ctx) this._canResize(); this.stringRender = new AscCommonExcel.StringRender(this.buffers.main); // Мерить нужно только со 100% и один раз для всего документа this._calcMaxDigitWidth(); if (!window["NATIVE_EDITOR_ENJINE"]) { // initialize events controller this.controller.init(this, this.element, /*this.canvasOverlay*/ this.canvasGraphicOverlay, /*handlers*/{ "resize": function () { self.resize.apply(self, arguments); }, "initRowsCount": function () { self._onInitRowsCount.apply(self, arguments); }, "initColsCount": function () { self._onInitColsCount.apply(self, arguments); }, "scrollY": function () { self._onScrollY.apply(self, arguments); }, "scrollX": function () { self._onScrollX.apply(self, arguments); }, "changeSelection": function () { self._onChangeSelection.apply(self, arguments); }, "changeSelectionDone": function () { self._onChangeSelectionDone.apply(self, arguments); }, "changeSelectionRightClick": function () { self._onChangeSelectionRightClick.apply(self, arguments); }, "selectionActivePointChanged": function () { self._onSelectionActivePointChanged.apply(self, arguments); }, "updateWorksheet": function () { self._onUpdateWorksheet.apply(self, arguments); }, "resizeElement": function () { self._onResizeElement.apply(self, arguments); }, "resizeElementDone": function () { self._onResizeElementDone.apply(self, arguments); }, "changeFillHandle": function () { self._onChangeFillHandle.apply(self, arguments); }, "changeFillHandleDone": function () { self._onChangeFillHandleDone.apply(self, arguments); }, "moveRangeHandle": function () { self._onMoveRangeHandle.apply(self, arguments); }, "moveRangeHandleDone": function () { self._onMoveRangeHandleDone.apply(self, arguments); }, "moveResizeRangeHandle": function () { self._onMoveResizeRangeHandle.apply(self, arguments); }, "moveResizeRangeHandleDone": function () { self._onMoveResizeRangeHandleDone.apply(self, arguments); }, "editCell": function () { self._onEditCell.apply(self, arguments); }, "stopCellEditing": function () { return self._onStopCellEditing.apply(self, arguments); }, "getCellEditMode": function () { return self.isCellEditMode; }, "canEdit": function () { return self.Api.canEdit(); }, "isRestrictionComments": function () { return self.Api.isRestrictionComments(); }, "empty": function () { self._onEmpty.apply(self, arguments); }, "canEnterCellRange": function () { self.cellEditor.setFocus(false); var ret = self.cellEditor.canEnterCellRange(); ret ? self.cellEditor.activateCellRange() : true; return ret; }, "enterCellRange": function () { self.lockDraw = true; self.skipHelpSelector = true; self.cellEditor.setFocus(false); self.getWorksheet().enterCellRange(self.cellEditor); self.skipHelpSelector = false; self.lockDraw = false; }, "undo": function () { self.undo.apply(self, arguments); }, "redo": function () { self.redo.apply(self, arguments); }, "mouseDblClick": function () { self._onMouseDblClick.apply(self, arguments); }, "showNextPrevWorksheet": function () { self._onShowNextPrevWorksheet.apply(self, arguments); }, "setFontAttributes": function () { self._onSetFontAttributes.apply(self, arguments); }, "setCellFormat": function () { self._onSetCellFormat.apply(self, arguments); }, "selectColumnsByRange": function () { self._onSelectColumnsByRange.apply(self, arguments); }, "selectRowsByRange": function () { self._onSelectRowsByRange.apply(self, arguments); }, "save": function () { self.Api.asc_Save(); }, "showCellEditorCursor": function () { self._onShowCellEditorCursor.apply(self, arguments); }, "print": function () { self.Api.onPrint(); }, "addFunction": function () { self.insertFormulaInEditor.apply(self, arguments); }, "canvasClick": function () { self.enableKeyEventsHandler(true); }, "autoFiltersClick": function () { self._onAutoFiltersClick.apply(self, arguments); }, "commentCellClick": function () { self._onCommentCellClick.apply(self, arguments); }, "isGlobalLockEditCell": function () { return self.collaborativeEditing.getGlobalLockEditCell(); }, "updateSelectionName": function () { self._onUpdateSelectionName.apply(self, arguments); }, "stopFormatPainter": function () { self._onStopFormatPainter.apply(self, arguments); }, "groupRowClick": function () { return self._onGroupRowClick.apply(self, arguments); }, // Shapes "graphicObjectMouseDown": function () { self._onGraphicObjectMouseDown.apply(self, arguments); }, "graphicObjectMouseMove": function () { self._onGraphicObjectMouseMove.apply(self, arguments); }, "graphicObjectMouseUp": function () { self._onGraphicObjectMouseUp.apply(self, arguments); }, "graphicObjectMouseUpEx": function () { self._onGraphicObjectMouseUpEx.apply(self, arguments); }, "graphicObjectWindowKeyDown": function () { return self._onGraphicObjectWindowKeyDown.apply(self, arguments); }, "graphicObjectWindowKeyPress": function () { return self._onGraphicObjectWindowKeyPress.apply(self, arguments); }, "getGraphicsInfo": function () { return self._onGetGraphicsInfo.apply(self, arguments); }, "updateSelectionShape": function () { return self._onUpdateSelectionShape.apply(self, arguments); }, "canReceiveKeyPress": function () { return self.getWorksheet().objectRender.controller.canReceiveKeyPress(); }, "stopAddShape": function () { self.getWorksheet().objectRender.controller.checkEndAddShape(); }, // Frozen anchor "moveFrozenAnchorHandle": function () { self._onMoveFrozenAnchorHandle.apply(self, arguments); }, "moveFrozenAnchorHandleDone": function () { self._onMoveFrozenAnchorHandleDone.apply(self, arguments); }, // AutoComplete "showAutoComplete": function () { self.showAutoComplete.apply(self, arguments); }, "onContextMenu": function (event) { self.handlers.trigger("asc_onContextMenu", event); }, // DataValidation "onDataValidation": function () { if (self.oSelectionInfo && self.oSelectionInfo.dataValidation) { self.handlers.trigger("asc_onValidationListMenu", self.oSelectionInfo.dataValidation.getListValues(self.model.getActiveWs())); } }, // FormatPainter 'isFormatPainter': function () { return self.stateFormatPainter; }, //calculate 'calculate': function () { self.calculate.apply(self, arguments); }, 'changeFormatTableInfo': function () { var table = self.getSelectionInfo().formatTableInfo; return table && self.changeFormatTableInfo(table.tableName, Asc.c_oAscChangeTableStyleInfo.rowTotal, !table.lastRow); }, //special paste "hideSpecialPasteOptions": function () { self.handlers.trigger("hideSpecialPasteOptions"); } }); if (this.input && this.input.addEventListener) { this.input.addEventListener("focus", function () { self.input.isFocused = true; if (!self.Api.canEdit()) { return; } self._onStopFormatPainter(); self.controller.setStrictClose(true); self.cellEditor.callTopLineMouseup = true; if (!self.getCellEditMode() && !self.controller.isFillHandleMode) { self._onEditCell(/*isFocus*/true); } }, false); this.input.addEventListener('keydown', function (event) { if (self.isCellEditMode) { self.handlers.trigger('asc_onInputKeyDown', event); if (!event.defaultPrevented) { self.cellEditor._onWindowKeyDown(event, true); } } }, false); } this.Api.onKeyDown = function (event) { self.controller._onWindowKeyDown(event); if (self.isCellEditMode) { self.cellEditor._onWindowKeyDown(event, false); } }; this.Api.onKeyPress = function (event) { self.controller._onWindowKeyPress(event); if (self.isCellEditMode) { self.cellEditor._onWindowKeyPress(event); } }; this.Api.onKeyUp = function (event) { self.controller._onWindowKeyUp(event); if (self.isCellEditMode) { self.cellEditor._onWindowKeyUp(event); } }; this.Api.Begin_CompositeInput = function () { var oWSView = self.getWorksheet(); if (oWSView && oWSView.isSelectOnShape) { if (oWSView.objectRender) { oWSView.objectRender.Begin_CompositeInput(); } return; } if (!self.isCellEditMode) { self._onEditCell(false, true, undefined, true, function () { self.cellEditor.Begin_CompositeInput(); }); } else { self.cellEditor.Begin_CompositeInput(); } }; this.Api.Replace_CompositeText = function (arrCharCodes) { var oWSView = self.getWorksheet(); if(oWSView && oWSView.isSelectOnShape){ if(oWSView.objectRender){ oWSView.objectRender.Replace_CompositeText(arrCharCodes); } return; } if (self.isCellEditMode) { self.cellEditor.Replace_CompositeText(arrCharCodes); } }; this.Api.End_CompositeInput = function () { var oWSView = self.getWorksheet(); if(oWSView && oWSView.isSelectOnShape){ if(oWSView.objectRender){ oWSView.objectRender.End_CompositeInput(); } return; } if (self.isCellEditMode) { self.cellEditor.End_CompositeInput(); } }; this.Api.Set_CursorPosInCompositeText = function (nPos) { var oWSView = self.getWorksheet(); if(oWSView && oWSView.isSelectOnShape){ if(oWSView.objectRender){ oWSView.objectRender.Set_CursorPosInCompositeText(nPos); } return; } if (self.isCellEditMode) { self.cellEditor.Set_CursorPosInCompositeText(nPos); } }; this.Api.Get_CursorPosInCompositeText = function () { var res = 0; var oWSView = self.getWorksheet(); if(oWSView && oWSView.isSelectOnShape){ if(oWSView.objectRender){ res = oWSView.objectRender.Get_CursorPosInCompositeText(); } } else if (self.isCellEditMode) { res = self.cellEditor.Get_CursorPosInCompositeText(); } return res; }; this.Api.Get_MaxCursorPosInCompositeText = function () { var res = 0; var oWSView = self.getWorksheet(); if(oWSView && oWSView.isSelectOnShape){ if(oWSView.objectRender){ res = oWSView.objectRender.Get_CursorPosInCompositeText(); } } else if (self.isCellEditMode) { res = self.cellEditor.Get_MaxCursorPosInCompositeText(); } return res; }; this.Api.AddTextWithPr = function (familyName, arrCharCodes) { var ws = self.getWorksheet(); if (ws && ws.isSelectOnShape) { var textPr = new CTextPr(); textPr.RFonts = new CRFonts(); textPr.RFonts.Set_All(familyName, -1); ws.objectRender.controller.addTextWithPr(new AscCommon.CUnicodeStringEmulator(arrCharCodes), textPr, true); return; } if (!self.isCellEditMode) { self._onEditCell(undefined, undefined, undefined, false, function () { self.cellEditor.setTextStyle('fn', familyName); self.cellEditor._addCharCodes(arrCharCodes); }); } else { self.cellEditor.setTextStyle('fn', familyName); self.cellEditor._addCharCodes(arrCharCodes); } }; this.Api.beginInlineDropTarget = function (event) { if (!self.controller.isMoveRangeMode) { self.controller.isMoveRangeMode = true; self.getWorksheet().dragAndDropRange = new Asc.Range(0, 0, 0, 0); } self.controller._onMouseMove(event); }; this.Api.endInlineDropTarget = function (event) { self.controller.isMoveRangeMode = false; var ws = self.getWorksheet(); var newSelection = ws.activeMoveRange.clone(); ws._cleanSelectionMoveRange(); ws.dragAndDropRange = null; self._onSetSelection(newSelection); }; this.Api.isEnabledDropTarget = function () { return !self.isCellEditMode; }; AscCommon.InitBrowserInputContext(this.Api, "id_target_cursor"); this.model.dependencyFormulas.calcTree(); } this.cellEditor = new AscCommonExcel.CellEditor(this.element, this.input, this.fmgrGraphics, this.m_oFont, /*handlers*/{ "closed": function () { self._onCloseCellEditor.apply(self, arguments); }, "updated": function () { self.Api.checkLastWork(); self._onUpdateCellEditor.apply(self, arguments); }, "gotFocus": function (hasFocus) { self.controller.setFocus(!hasFocus); }, "updateFormulaEditMod": function () { self.controller.setFormulaEditMode.apply(self.controller, arguments); var ws = self.getWorksheet(); if (ws) { if (!self.lockDraw) { ws.cleanSelection(); } for (var i in self.wsViews) { self.wsViews[i].cleanFormulaRanges(); } // ws.cleanFormulaRanges(); ws.setFormulaEditMode.apply(ws, arguments); } }, "updateEditorState": function (state) { self.handlers.trigger("asc_onEditCell", state); }, "isGlobalLockEditCell": function () { return self.collaborativeEditing.getGlobalLockEditCell(); }, "updateFormulaEditModEnd": function () { if (!self.lockDraw) { self.getWorksheet().updateSelection(); } }, "newRange": function (range, ws) { if (!ws) { self.getWorksheet().addFormulaRange(range); } else { self.getWorksheet(self.model.getWorksheetIndexByName(ws)).addFormulaRange(range); } }, "existedRange": function (range, ws) { var editRangeSheet = ws ? self.model.getWorksheetIndexByName(ws) : self.copyActiveSheet; if (-1 === editRangeSheet || editRangeSheet === self.wsActive) { self.getWorksheet().activeFormulaRange(range); } else { self.getWorksheet(editRangeSheet).removeFormulaRange(range); self.getWorksheet().addFormulaRange(range); } }, "updateUndoRedoChanged": function (bCanUndo, bCanRedo) { self.handlers.trigger("asc_onCanUndoChanged", bCanUndo); self.handlers.trigger("asc_onCanRedoChanged", bCanRedo); }, "applyCloseEvent": function () { self.controller._onWindowKeyDown.apply(self.controller, arguments); }, "canEdit": function () { return self.Api.canEdit(); }, "getFormulaRanges": function () { return (self.cellFormulaEnterWSOpen || self.getWorksheet()).getFormulaRanges(); }, "getCellFormulaEnterWSOpen": function () { return self.cellFormulaEnterWSOpen; }, "getActiveWS": function () { return self.getWorksheet().model; }, "setStrictClose": function (val) { self.controller.setStrictClose(val); }, "updateEditorSelectionInfo": function (info) { self.handlers.trigger("asc_onEditorSelectionChanged", info); }, "onContextMenu": function (event) { self.handlers.trigger("asc_onContextMenu", event); }, "updatedEditableFunction": function (fName) { self.handlers.trigger("asc_onFormulaInfo", fName); } }, this.defaults.worksheetView.cells.padding); this.wsViewHandlers = new AscCommonExcel.asc_CHandlersList(/*handlers*/{ "canEdit": function () { return self.Api.canEdit(); }, "getViewMode": function () { return self.Api.getViewMode(); }, "isRestrictionComments": function () { return self.Api.isRestrictionComments(); }, "reinitializeScroll": function (type) { self._onScrollReinitialize(type); }, "selectionChanged": function () { self._onWSSelectionChanged(); }, "selectionNameChanged": function () { self._onSelectionNameChanged.apply(self, arguments); }, "selectionMathInfoChanged": function () { self._onSelectionMathInfoChanged.apply(self, arguments); }, 'onFilterInfo': function (countFilter, countRecords) { self.handlers.trigger("asc_onFilterInfo", countFilter, countRecords); }, "onErrorEvent": function (errorId, level) { self.handlers.trigger("asc_onError", errorId, level); }, "slowOperation": function (isStart) { (isStart ? self.Api.sync_StartAction : self.Api.sync_EndAction).call(self.Api, c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.SlowOperation); }, "setAutoFiltersDialog": function (arrVal) { self.handlers.trigger("asc_onSetAFDialog", arrVal); }, "selectionRangeChanged": function (val) { self.handlers.trigger("asc_onSelectionRangeChanged", val); }, "onRenameCellTextEnd": function (countFind, countReplace) { self.handlers.trigger("asc_onRenameCellTextEnd", countFind, countReplace); }, 'onStopFormatPainter': function () { self._onStopFormatPainter(); }, 'getRangeFormatPainter': function () { return self.rangeFormatPainter; }, "onDocumentPlaceChanged": function () { self._onDocumentPlaceChanged(); }, "updateSheetViewSettings": function () { self.handlers.trigger("asc_onUpdateSheetViewSettings"); }, "onScroll": function (d) { self.controller.scroll(d); }, "getLockDefNameManagerStatus": function () { return self.defNameAllowCreate; }, 'isActive': function () { return (-1 === self.copyActiveSheet || self.wsActive === self.copyActiveSheet); }, "getCellEditMode": function () { return self.isCellEditMode; }, "drawMobileSelection": function (color) { if (self.MobileTouchManager) { self.MobileTouchManager.CheckSelect(self.trackOverlay, color); } }, "showSpecialPasteOptions": function (val) { self.handlers.trigger("asc_onShowSpecialPasteOptions", val); if (!window['AscCommon'].g_specialPasteHelper.showSpecialPasteButton) { window['AscCommon'].g_specialPasteHelper.showSpecialPasteButton = true; } }, 'checkLastWork': function () { self.Api.checkLastWork(); }, "toggleAutoCorrectOptions": function (bIsShow, val) { self.toggleAutoCorrectOptions(bIsShow, val); }, "selectSearchingResults": function () { return self.Api.selectSearchingResults; }, "getMainGraphics": function () { return self.mainGraphics; }, "cleanCutData": function (bDrawSelection, bCleanBuffer) { self.cleanCutData(bDrawSelection, bCleanBuffer); } }); this.model.handlers.add("cleanCellCache", function(wsId, oRanges, skipHeight) { var ws = self.getWorksheetById(wsId, true); if (ws) { ws.updateRanges(oRanges, skipHeight); } }); this.model.handlers.add("changeWorksheetUpdate", function(wsId, val) { var ws = self.getWorksheetById(wsId); if (ws) { ws.changeWorksheet("update", val); } }); this.model.handlers.add("showWorksheet", function(wsId) { var wsModel = self.model.getWorksheetById(wsId), index; if (wsModel) { index = wsModel.getIndex(); self.showWorksheet(index, true); } }); this.model.handlers.add("setSelection", function() { self._onSetSelection.apply(self, arguments); }); this.model.handlers.add("getSelectionState", function() { return self._onGetSelectionState.apply(self); }); this.model.handlers.add("setSelectionState", function() { self._onSetSelectionState.apply(self, arguments); }); this.model.handlers.add("reInit", function() { self.reInit.apply(self, arguments); }); this.model.handlers.add("drawWS", function() { self.drawWS.apply(self, arguments); }); this.model.handlers.add("showDrawingObjects", function() { self.onShowDrawingObjects.apply(self, arguments); }); this.model.handlers.add("setCanUndo", function(bCanUndo) { self.handlers.trigger("asc_onCanUndoChanged", bCanUndo); }); this.model.handlers.add("setCanRedo", function(bCanRedo) { self.handlers.trigger("asc_onCanRedoChanged", bCanRedo); }); this.model.handlers.add("setDocumentModified", function(bIsModified) { self.Api.onUpdateDocumentModified(bIsModified); }); this.model.handlers.add("updateWorksheetByModel", function() { self.updateWorksheetByModel.apply(self, arguments); }); this.model.handlers.add("undoRedoAddRemoveRowCols", function(sheetId, type, range, bUndo) { if (true === bUndo) { if (AscCH.historyitem_Worksheet_AddRows === type) { self.collaborativeEditing.removeRowsRange(sheetId, range.clone(true)); self.collaborativeEditing.undoRows(sheetId, range.r2 - range.r1 + 1); } else if (AscCH.historyitem_Worksheet_RemoveRows === type) { self.collaborativeEditing.addRowsRange(sheetId, range.clone(true)); self.collaborativeEditing.undoRows(sheetId, range.r2 - range.r1 + 1); } else if (AscCH.historyitem_Worksheet_AddCols === type) { self.collaborativeEditing.removeColsRange(sheetId, range.clone(true)); self.collaborativeEditing.undoCols(sheetId, range.c2 - range.c1 + 1); } else if (AscCH.historyitem_Worksheet_RemoveCols === type) { self.collaborativeEditing.addColsRange(sheetId, range.clone(true)); self.collaborativeEditing.undoCols(sheetId, range.c2 - range.c1 + 1); } } else { if (AscCH.historyitem_Worksheet_AddRows === type) { self.collaborativeEditing.addRowsRange(sheetId, range.clone(true)); self.collaborativeEditing.addRows(sheetId, range.r1, range.r2 - range.r1 + 1); } else if (AscCH.historyitem_Worksheet_RemoveRows === type) { self.collaborativeEditing.removeRowsRange(sheetId, range.clone(true)); self.collaborativeEditing.removeRows(sheetId, range.r1, range.r2 - range.r1 + 1); } else if (AscCH.historyitem_Worksheet_AddCols === type) { self.collaborativeEditing.addColsRange(sheetId, range.clone(true)); self.collaborativeEditing.addCols(sheetId, range.c1, range.c2 - range.c1 + 1); } else if (AscCH.historyitem_Worksheet_RemoveCols === type) { self.collaborativeEditing.removeColsRange(sheetId, range.clone(true)); self.collaborativeEditing.removeCols(sheetId, range.c1, range.c2 - range.c1 + 1); } } }); this.model.handlers.add("undoRedoHideSheet", function(sheetId) { self.showWorksheet(sheetId); // Посылаем callback об изменении списка листов self.Api.sheetsChanged(); }); this.model.handlers.add("updateSelection", function () { if (!self.lockDraw) { self.getWorksheet().updateSelection(); } }); this.handlers.add("asc_onLockDefNameManager", function(reason) { self.defNameAllowCreate = !(reason == Asc.c_oAscDefinedNameReason.LockDefNameManager); }); this.handlers.add('addComment', function (id, data) { self._onWSSelectionChanged(); self.handlers.trigger('asc_onAddComment', id, data); }); this.handlers.add('removeComment', function (id) { self._onWSSelectionChanged(); self.handlers.trigger('asc_onRemoveComment', id); }); this.handlers.add('hiddenComments', function () { return !self.isShowComments; }); this.handlers.add('showSolved', function () { return self.isShowSolved; }); this.model.handlers.add("hideSpecialPasteOptions", function() { self.handlers.trigger("asc_onHideSpecialPasteOptions"); }); this.model.handlers.add("toggleAutoCorrectOptions", function(bIsShow, val) { self.toggleAutoCorrectOptions(bIsShow, val); }); this.model.handlers.add("cleanCutData", function(bDrawSelection, bCleanBuffer) { self.cleanCutData(bDrawSelection, bCleanBuffer); }); this.model.handlers.add("updateGroupData", function() { self.updateGroupData(); }); this.cellCommentator = new AscCommonExcel.CCellCommentator({ model: new WorkbookCommentsModel(this.handlers, this.model.aComments), collaborativeEditing: this.collaborativeEditing, draw: function() { }, handlers: { trigger: function() { return false; } } }); if (0 < this.model.aComments.length) { this.handlers.trigger("asc_onAddComments", this.model.aComments); } this.initFormulasList(); this.fReplaceCallback = function() { self._replaceCellTextCallback.apply(self, arguments); }; return this; }; WorkbookView.prototype.destroy = function() { this.controller.destroy(); this.cellEditor.destroy(); return this; }; WorkbookView.prototype._createWorksheetView = function(wsModel) { return new AscCommonExcel.WorksheetView(this, wsModel, this.wsViewHandlers, this.buffers, this.stringRender, this.maxDigitWidth, this.collaborativeEditing, this.defaults.worksheetView); }; WorkbookView.prototype._onSelectionNameChanged = function(name) { this.handlers.trigger("asc_onSelectionNameChanged", name); }; WorkbookView.prototype._onSelectionMathInfoChanged = function(info) { this.handlers.trigger("asc_onSelectionMathChanged", info); }; // Проверяет, сменили ли мы диапазон (для того, чтобы не отправлять одинаковую информацию о диапазоне) WorkbookView.prototype._isEqualRange = function(range, isSelectOnShape) { if (null === this.lastSendInfoRange) { return false; } return this.lastSendInfoRange.isEqual(range) && this.lastSendInfoRangeIsSelectOnShape === isSelectOnShape; }; WorkbookView.prototype._updateSelectionInfo = function () { var ws = this.cellFormulaEnterWSOpen ? this.cellFormulaEnterWSOpen : this.getWorksheet(); this.oSelectionInfo = ws.getSelectionInfo(); this.lastSendInfoRange = ws.model.selectionRange.clone(); this.lastSendInfoRangeIsSelectOnShape = ws.getSelectionShape(); }; WorkbookView.prototype._onWSSelectionChanged = function(isSaving) { this._updateSelectionInfo(); // При редактировании ячейки не нужно пересылать изменения if (this.input && false === this.getCellEditMode() && c_oAscSelectionDialogType.None === this.selectionDialogType) { // Сами запретим заходить в строку формул, когда выделен shape if (this.lastSendInfoRangeIsSelectOnShape) { this.input.disabled = true; this.input.value = ''; } else { this.input.disabled = false; this.input.value = this.oSelectionInfo.text; } } this.handlers.trigger("asc_onSelectionChanged", this.oSelectionInfo); this.handlers.trigger("asc_onSelectionEnd"); this._onInputMessage(); if (!isSaving) { this.Api.cleanSpelling(); } }; WorkbookView.prototype._onInputMessage = function () { var title = null, message = null; var dataValidation = this.oSelectionInfo && this.oSelectionInfo.dataValidation; if (dataValidation && dataValidation.showInputMessage && !this.model.getActiveWs().getDisablePrompts()) { title = dataValidation.promptTitle; message = dataValidation.promt; } this.handlers.trigger("asc_onInputMessage", title, message); }; WorkbookView.prototype._onScrollReinitialize = function (type) { if (window["NATIVE_EDITOR_ENJINE"] || !type) { return; } var ws = this.getWorksheet(); if (AscCommonExcel.c_oAscScrollType.ScrollHorizontal & type) { this.controller.reinitScrollX(ws.getFirstVisibleCol(true), ws.getHorizontalScrollRange(), ws.getHorizontalScrollMax()); } if (AscCommonExcel.c_oAscScrollType.ScrollVertical & type) { this.controller.reinitScrollY(ws.getFirstVisibleRow(true), ws.getVerticalScrollRange(), ws.getVerticalScrollMax()); } if (this.Api.isMobileVersion) { this.MobileTouchManager.Resize(); } }; WorkbookView.prototype._onInitRowsCount = function () { var ws = this.getWorksheet(); if (ws._initRowsCount()) { this._onScrollReinitialize(AscCommonExcel.c_oAscScrollType.ScrollVertical); } }; WorkbookView.prototype._onInitColsCount = function () { var ws = this.getWorksheet(); if (ws._initColsCount()) { this._onScrollReinitialize(AscCommonExcel.c_oAscScrollType.ScrollHorizontal); } }; WorkbookView.prototype._onScrollY = function(pos, initRowsCount) { var ws = this.getWorksheet(); var delta = asc_round(pos - ws.getFirstVisibleRow(true)); if (delta !== 0) { ws.scrollVertical(delta, this.cellEditor, initRowsCount); } }; WorkbookView.prototype._onScrollX = function(pos, initColsCount) { var ws = this.getWorksheet(); var delta = asc_round(pos - ws.getFirstVisibleCol(true)); if (delta !== 0) { ws.scrollHorizontal(delta, this.cellEditor, initColsCount); } }; WorkbookView.prototype._onSetSelection = function(range) { var ws = this.getWorksheet(); ws._endSelectionShape(); ws.setSelection(range); }; WorkbookView.prototype._onGetSelectionState = function() { var res = null; var ws = this.getWorksheet(null, true); if (ws && AscCommon.isRealObject(ws.objectRender) && AscCommon.isRealObject(ws.objectRender.controller)) { res = ws.objectRender.controller.getSelectionState(); } return (res && res[0] && res[0].focus) ? res : null; }; WorkbookView.prototype._onSetSelectionState = function(state) { if (null !== state) { var ws = this.getWorksheetById(state[0].worksheetId); if (ws && ws.objectRender && ws.objectRender.controller) { ws.objectRender.controller.setSelectionState(state); ws.setSelectionShape(true); ws._scrollToRange(ws.objectRender.getSelectedDrawingsRange()); ws.objectRender.showDrawingObjectsEx(true); ws.objectRender.controller.updateOverlay(); ws.objectRender.controller.updateSelectionState(); } // Селектим после выставления состояния } }; WorkbookView.prototype._onChangeSelection = function (isStartPoint, dc, dr, isCoord, isCtrl, callback) { var ws = this.getWorksheet(); var t = this; var d = isStartPoint ? ws.changeSelectionStartPoint(dc, dr, isCoord, isCtrl) : ws.changeSelectionEndPoint(dc, dr, isCoord, isCoord && this.keepType); if (!isCoord && !isStartPoint) { // Выделение с зажатым shift this.canUpdateAfterShiftUp = true; } this.keepType = isCoord; if (isCoord && !this.timerEnd && this.timerId === null) { this.timerId = setTimeout(function () { var arrClose = []; arrClose.push(new asc_CMM({type: c_oAscMouseMoveType.None})); t.handlers.trigger("asc_onMouseMove", arrClose); t._onUpdateCursor(AscCommonExcel.kCurCells); t.timerId = null; t.timerEnd = true; },1000); } asc_applyFunction(callback, d); }; // Окончание выделения WorkbookView.prototype._onChangeSelectionDone = function(x, y, event) { if (this.timerId !== null) { clearTimeout(this.timerId); this.timerId = null; } this.keepType = false; if (c_oAscSelectionDialogType.None !== this.selectionDialogType) { return; } var ws = this.getWorksheet(); ws.changeSelectionDone(); this._onSelectionNameChanged(ws.getSelectionName(/*bRangeText*/false)); // Проверим, нужно ли отсылать информацию о ячейке var ar = ws.model.selectionRange.getLast(); var isSelectOnShape = ws.getSelectionShape(); if (!this._isEqualRange(ws.model.selectionRange, isSelectOnShape)) { this._onWSSelectionChanged(); this._onSelectionMathInfoChanged(ws.getSelectionMathInfo()); } // Нужно очистить поиск this.model.cleanFindResults(); var ct = ws.getCursorTypeFromXY(x, y); if (c_oTargetType.Hyperlink === ct.target && !this.controller.isFormulaEditMode) { // Проверим замерженность var isHyperlinkClick = false; if(isSelectOnShape) { var button = 0; if(event) { button = AscCommon.getMouseButton(event); } if(button === 0) { isHyperlinkClick = true; } } else if(ar.isOneCell()) { isHyperlinkClick = true; } else { var mergedRange = ws.model.getMergedByCell(ar.r1, ar.c1); if (mergedRange && ar.isEqual(mergedRange)) { isHyperlinkClick = true; } } if (isHyperlinkClick && !this.timerEnd) { if (false === ct.hyperlink.hyperlinkModel.getVisited() && !isSelectOnShape) { ct.hyperlink.hyperlinkModel.setVisited(true); if (ct.hyperlink.hyperlinkModel.Ref) { ws._updateRange(ct.hyperlink.hyperlinkModel.Ref.getBBox0()); ws.draw(); } } switch (ct.hyperlink.asc_getType()) { case Asc.c_oAscHyperlinkType.WebLink: this.handlers.trigger("asc_onHyperlinkClick", ct.hyperlink.asc_getHyperlinkUrl()); break; case Asc.c_oAscHyperlinkType.RangeLink: // ToDo надо поправить отрисовку комментария для данной ячейки (с которой уходим) this.handlers.trigger("asc_onHideComment"); this.Api._asc_setWorksheetRange(ct.hyperlink); break; } } } this.timerEnd = false; }; // Обработка нажатия правой кнопки мыши WorkbookView.prototype._onChangeSelectionRightClick = function(dc, dr, target) { var ws = this.getWorksheet(); ws.changeSelectionStartPointRightClick(dc, dr, target); }; // Обработка движения в выделенной области WorkbookView.prototype._onSelectionActivePointChanged = function(dc, dr, callback) { var ws = this.getWorksheet(); var d = ws.changeSelectionActivePoint(dc, dr); asc_applyFunction(callback, d); }; WorkbookView.prototype._onUpdateWorksheet = function(x, y, ctrlKey, callback) { var ws = this.getWorksheet(), ct = undefined; var arrMouseMoveObjects = []; // Теперь это массив из объектов, над которыми курсор var t = this; //ToDo: включить определение target, если находимся в режиме редактирования ячейки. if (x === undefined && y === undefined) { ws.cleanHighlightedHeaders(); if (this.timerId === null) { this.timerId = setTimeout(function () { var arrClose = []; arrClose.push(new asc_CMM({type: c_oAscMouseMoveType.None})); t.handlers.trigger("asc_onMouseMove", arrClose); t.timerId = null; }, 1000); } } else { ct = ws.getCursorTypeFromXY(x, y); ct.coordX = x; ct.coordY = y; if (this.timerId !== null) { clearTimeout(this.timerId); this.timerId = null; } // Отправление эвента об удалении всего листа (именно удалении, т.к. если просто залочен, то не рисуем рамку вокруг) if (undefined !== ct.userIdAllSheet) { arrMouseMoveObjects.push(new asc_CMM({ type: c_oAscMouseMoveType.LockedObject, x: AscCommon.AscBrowser.convertToRetinaValue(ct.lockAllPosLeft), y: AscCommon.AscBrowser.convertToRetinaValue(ct.lockAllPosTop), userId: ct.userIdAllSheet, lockedObjectType: Asc.c_oAscMouseMoveLockedObjectType.Sheet })); } else { // Отправление эвента о залоченности свойств всего листа (только если не удален весь лист) if (undefined !== ct.userIdAllProps) { arrMouseMoveObjects.push(new asc_CMM({ type: c_oAscMouseMoveType.LockedObject, x: AscCommon.AscBrowser.convertToRetinaValue(ct.lockAllPosLeft), y: AscCommon.AscBrowser.convertToRetinaValue(ct.lockAllPosTop), userId: ct.userIdAllProps, lockedObjectType: Asc.c_oAscMouseMoveLockedObjectType.TableProperties })); } } // Отправление эвента о наведении на залоченный объект if (undefined !== ct.userId) { arrMouseMoveObjects.push(new asc_CMM({ type: c_oAscMouseMoveType.LockedObject, x: AscCommon.AscBrowser.convertToRetinaValue(ct.lockRangePosLeft), y: AscCommon.AscBrowser.convertToRetinaValue(ct.lockRangePosTop), userId: ct.userId, lockedObjectType: Asc.c_oAscMouseMoveLockedObjectType.Range })); } // Проверяем комментарии ячейки if (ct.commentIndexes) { arrMouseMoveObjects.push(new asc_CMM({ type: c_oAscMouseMoveType.Comment, x: ct.commentCoords.dLeftPX, reverseX: ct.commentCoords.dReverseLeftPX, y: ct.commentCoords.dTopPX, aCommentIndexes: ct.commentIndexes })); } // Проверяем гиперссылку if (ct.target === c_oTargetType.Hyperlink) { if (!ctrlKey) { arrMouseMoveObjects.push(new asc_CMM({ type: c_oAscMouseMoveType.Hyperlink, x: AscCommon.AscBrowser.convertToRetinaValue(x), y: AscCommon.AscBrowser.convertToRetinaValue(y), hyperlink: ct.hyperlink })); } else { ct.cursor = AscCommonExcel.kCurCells; } } // проверяем фильтр if (ct.target === c_oTargetType.FilterObject) { if (ct.isPivot) { //необходимо сгенерировать объект AutoFiltersOptions } else { var filterObj = ws.af_setDialogProp(ct.idFilter, true); if(filterObj) { arrMouseMoveObjects.push(new asc_CMM({ type: c_oAscMouseMoveType.Filter, x: AscCommon.AscBrowser.convertToRetinaValue(x), y: AscCommon.AscBrowser.convertToRetinaValue(y), filter: filterObj })); } } } /* Проверяем, может мы на никаком объекте (такая схема оказалась приемлимой * для отдела разработки приложений) */ if (0 === arrMouseMoveObjects.length) { // Отправляем эвент, что мы ни на какой области arrMouseMoveObjects.push(new asc_CMM({type: c_oAscMouseMoveType.None})); } // Отсылаем эвент с объектами this.handlers.trigger("asc_onMouseMove", arrMouseMoveObjects); if (ct.target === c_oTargetType.MoveRange && ctrlKey && ct.cursor === "move") { ct.cursor = "copy"; } this._onUpdateCursor(ct.cursor); if (ct.target === c_oTargetType.ColumnHeader || ct.target === c_oTargetType.RowHeader) { ws.drawHighlightedHeaders(ct.col, ct.row); } else { ws.cleanHighlightedHeaders(); } } asc_applyFunction(callback, ct); }; WorkbookView.prototype._onUpdateCursor = function (cursor) { var newHtmlCursor = AscCommon.g_oHtmlCursor.value(cursor); if (this.element.style.cursor !== newHtmlCursor) { this.element.style.cursor = newHtmlCursor; } }; WorkbookView.prototype._onResizeElement = function(target, x, y) { var arrMouseMoveObjects = []; if (target.target === c_oTargetType.ColumnResize) { arrMouseMoveObjects.push(this.getWorksheet().drawColumnGuides(target.col, x, y, target.mouseX)); } else if (target.target === c_oTargetType.RowResize) { arrMouseMoveObjects.push(this.getWorksheet().drawRowGuides(target.row, x, y, target.mouseY)); } /* Проверяем, может мы на никаком объекте (такая схема оказалась приемлимой * для отдела разработки приложений) */ if (0 === arrMouseMoveObjects.length) { // Отправляем эвент, что мы ни на какой области arrMouseMoveObjects.push(new asc_CMM({type: c_oAscMouseMoveType.None})); } // Отсылаем эвент с объектами this.handlers.trigger("asc_onMouseMove", arrMouseMoveObjects); }; WorkbookView.prototype._onResizeElementDone = function(target, x, y, isResizeModeMove) { var ws = this.getWorksheet(); if (isResizeModeMove) { if (target.target === c_oTargetType.ColumnResize) { ws.changeColumnWidth(target.col, x, target.mouseX); } else if (target.target === c_oTargetType.RowResize) { ws.changeRowHeight(target.row, y, target.mouseY); } window['AscCommon'].g_specialPasteHelper.SpecialPasteButton_Update_Position(); this._onDocumentPlaceChanged(); } ws.draw(); // Отсылаем окончание смены размеров (в FF не срабатывало обычное движение) this.handlers.trigger("asc_onMouseMove", [new asc_CMM({type: c_oAscMouseMoveType.None})]); }; // Обработка автозаполнения WorkbookView.prototype._onChangeFillHandle = function(x, y, callback, tableIndex) { var ws = this.getWorksheet(); var d = ws.changeSelectionFillHandle(x, y, tableIndex); asc_applyFunction(callback, d); }; // Обработка окончания автозаполнения WorkbookView.prototype._onChangeFillHandleDone = function(x, y, ctrlPress) { var ws = this.getWorksheet(); ws.applyFillHandle(x, y, ctrlPress); }; // Обработка перемещения диапазона WorkbookView.prototype._onMoveRangeHandle = function(x, y, callback) { var ws = this.getWorksheet(); var d = ws.changeSelectionMoveRangeHandle(x, y); asc_applyFunction(callback, d); }; // Обработка окончания перемещения диапазона WorkbookView.prototype._onMoveRangeHandleDone = function(ctrlKey) { var ws = this.getWorksheet(); ws.applyMoveRangeHandle(ctrlKey); }; WorkbookView.prototype._onMoveResizeRangeHandle = function(x, y, target, callback) { var ws = this.getWorksheet(); var d = ws.changeSelectionMoveResizeRangeHandle(x, y, target, this.cellEditor); asc_applyFunction(callback, d); }; WorkbookView.prototype._onMoveResizeRangeHandleDone = function(target) { var ws = this.getWorksheet(); ws.applyMoveResizeRangeHandle(target); }; // Frozen anchor WorkbookView.prototype._onMoveFrozenAnchorHandle = function(x, y, target) { var ws = this.getWorksheet(); ws.drawFrozenGuides(x, y, target); }; WorkbookView.prototype._onMoveFrozenAnchorHandleDone = function(x, y, target) { // Закрепляем область var ws = this.getWorksheet(); ws.applyFrozenAnchor(x, y, target); }; WorkbookView.prototype.showAutoComplete = function() { var ws = this.getWorksheet(); var arrValues = ws.getCellAutoCompleteValues(ws.model.selectionRange.activeCell); this.handlers.trigger('asc_onEntriesListMenu', arrValues); }; WorkbookView.prototype._onAutoFiltersClick = function(idFilter) { this.getWorksheet().af_setDialogProp(idFilter); }; WorkbookView.prototype._onGroupRowClick = function(x, y, target, type) { return this.getWorksheet().groupRowClick(x, y, target, type); }; WorkbookView.prototype._onCommentCellClick = function(x, y) { this.getWorksheet().cellCommentator.showCommentByXY(x, y); }; WorkbookView.prototype._onUpdateSelectionName = function (forcibly) { if (this.canUpdateAfterShiftUp || forcibly) { this.canUpdateAfterShiftUp = false; var ws = this.getWorksheet(); this._onSelectionNameChanged(ws.getSelectionName(/*bRangeText*/false)); } }; WorkbookView.prototype._onStopFormatPainter = function() { if (this.stateFormatPainter) { this.formatPainter(c_oAscFormatPainterState.kOff); } }; // Shapes WorkbookView.prototype._onGraphicObjectMouseDown = function(e, x, y) { var ws = this.getWorksheet(); ws.objectRender.graphicObjectMouseDown(e, x, y); }; WorkbookView.prototype._onGraphicObjectMouseMove = function(e, x, y) { var ws = this.getWorksheet(); ws.objectRender.graphicObjectMouseMove(e, x, y); }; WorkbookView.prototype._onGraphicObjectMouseUp = function(e, x, y) { var ws = this.getWorksheet(); ws.objectRender.graphicObjectMouseUp(e, x, y); }; WorkbookView.prototype._onGraphicObjectMouseUpEx = function(e, x, y) { //var ws = this.getWorksheet(); //ws.objectRender.calculateCell(x, y); }; WorkbookView.prototype._onGraphicObjectWindowKeyDown = function(e) { var objectRender = this.getWorksheet().objectRender; return (0 < objectRender.getSelectedGraphicObjects().length) ? objectRender.graphicObjectKeyDown(e) : false; }; WorkbookView.prototype._onGraphicObjectWindowKeyPress = function(e) { var objectRender = this.getWorksheet().objectRender; return (0 < objectRender.getSelectedGraphicObjects().length) ? objectRender.graphicObjectKeyPress(e) : false; }; WorkbookView.prototype._onGetGraphicsInfo = function(x, y) { var ws = this.getWorksheet(); return ws.objectRender.checkCursorDrawingObject(x, y); }; WorkbookView.prototype._onUpdateSelectionShape = function(isSelectOnShape) { var ws = this.getWorksheet(); return ws.setSelectionShape(isSelectOnShape); }; // Double click WorkbookView.prototype._onMouseDblClick = function(x, y, isHideCursor, callback) { var ws = this.getWorksheet(); var ct = ws.getCursorTypeFromXY(x, y); if (ct.target === c_oTargetType.ColumnResize || ct.target === c_oTargetType.RowResize) { if (ct.target === c_oTargetType.ColumnResize) { ws.autoFitColumnsWidth(ct.col); } else { ws.autoFitRowHeight(ct.row, ct.row); } asc_applyFunction(callback); } else { if (ct.col >= 0 && ct.row >= 0) { this.controller.setStrictClose(!ws._isCellNullText(ct.col, ct.row)); } // In view mode or click on column | row | all | frozenMove | drawing object do not process if (!this.Api.canEdit() || c_oTargetType.ColumnHeader === ct.target || c_oTargetType.RowHeader === ct.target || c_oTargetType.Corner === ct.target || c_oTargetType.FrozenAnchorH === ct.target || c_oTargetType.FrozenAnchorV === ct.target || ws.objectRender.checkCursorDrawingObject(x, y)) { asc_applyFunction(callback); return; } // При dbl клике фокус выставляем в зависимости от наличия текста в ячейке this._onEditCell(/*isFocus*/undefined, /*isClearCell*/undefined, /*isHideCursor*/isHideCursor, /*isQuickInput*/false); } }; WorkbookView.prototype._onWindowMouseUpExternal = function (event, x, y) { this.controller._onWindowMouseUpExternal(event, x, y); if (this.isCellEditMode) { this.cellEditor._onWindowMouseUp(event, x, y); } }; WorkbookView.prototype._onEditCell = function(isFocus, isClearCell, isHideCursor, isQuickInput, callback) { var t = this; // Проверка глобального лока if (this.collaborativeEditing.getGlobalLock() || this.controller.isResizeMode) { return; } var ws = t.getWorksheet(); var activeCellRange = ws.getActiveCell(0, 0, false); var selectionRange = ws.model.selectionRange.clone(); var activeWsModel = this.model.getActiveWs(); if (activeWsModel.inPivotTable(activeCellRange)) { this.handlers.trigger("asc_onError", c_oAscError.ID.LockedCellPivot, c_oAscError.Level.NoCritical); return; } var editFunction = function() { t.setCellEditMode(true); t.hideSpecialPasteButton(); ws.openCellEditor(t.cellEditor, /*cursorPos*/undefined, isFocus, isClearCell, /*isHideCursor*/isHideCursor, /*isQuickInput*/isQuickInput, selectionRange); t.input.disabled = false; t.Api.cleanSpelling(true); // Эвент на обновление состояния редактора t.cellEditor._updateEditorState(); asc_applyFunction(callback, true); }; var editLockCallback = function(res) { if (!res) { t.setCellEditMode(false); t.controller.setStrictClose(false); t.controller.setFormulaEditMode(false); ws.setFormulaEditMode(false); t.input.disabled = true; // Выключаем lock для редактирования ячейки t.collaborativeEditing.onStopEditCell(); t.cellEditor.close(false); t._onWSSelectionChanged(); } }; // Стартуем редактировать ячейку activeCellRange = ws.expandActiveCellByFormulaArray(activeCellRange); if (ws._isLockedCells(activeCellRange, /*subType*/null, editLockCallback)) { editFunction(); } }; WorkbookView.prototype._onStopCellEditing = function(cancel) { return this.cellEditor.close(!cancel); }; WorkbookView.prototype._onCloseCellEditor = function() { var isCellEditMode = this.getCellEditMode(); this.setCellEditMode(false); this.controller.setStrictClose(false); this.controller.setFormulaEditMode(false); var ws = this.getWorksheet(), index; if( this.cellFormulaEnterWSOpen ){ index = this.cellFormulaEnterWSOpen.model.getIndex(); this.cellFormulaEnterWSOpen = null; if( index !== ws.model.getIndex() ){ this.showWorksheet(index); } ws = this.getWorksheet(index); } ws.cleanSelection(); for (var i in this.wsViews) { this.wsViews[i].setFormulaEditMode(false); this.wsViews[i].cleanFormulaRanges(); } ws.updateSelectionWithSparklines(); if (isCellEditMode) { this.handlers.trigger("asc_onEditCell", Asc.c_oAscCellEditorState.editEnd); } // Обновляем состояние Undo/Redo if (!this.cellEditor.getMenuEditorMode()) { History._sendCanUndoRedo(); } // Обновляем состояние информации this._onWSSelectionChanged(); // Закрываем подбор формулы if (-1 !== this.lastFPos) { this.handlers.trigger('asc_onFormulaCompleteMenu', null); this.lastFPos = -1; this.lastFNameLength = 0; } this.handlers.trigger('asc_onFormulaInfo', null); }; WorkbookView.prototype._onEmpty = function() { this.getWorksheet().emptySelection(c_oAscCleanOptions.Text); }; WorkbookView.prototype._onShowNextPrevWorksheet = function(direction) { // Колличество листов var countWorksheets = this.model.getWorksheetCount(); // Покажем следующий лист или предыдущий (если больше нет) var i = this.wsActive + direction, ws; while (i !== this.wsActive) { if (0 > i) { i = countWorksheets - 1; } else if (i >= countWorksheets) { i = 0; } ws = this.model.getWorksheet(i); if (!ws.getHidden()) { this.showWorksheet(i); return true; } i += direction; } return false; }; WorkbookView.prototype._onSetFontAttributes = function(prop) { var val; var selectionInfo = this.getWorksheet().getSelectionInfo().asc_getFont(); switch (prop) { case "b": val = !(selectionInfo.asc_getBold()); break; case "i": val = !(selectionInfo.asc_getItalic()); break; case "u": // ToDo для двойного подчеркивания нужно будет немного переделать схему val = !(selectionInfo.asc_getUnderline()); val = val ? Asc.EUnderline.underlineSingle : Asc.EUnderline.underlineNone; break; case "s": val = !(selectionInfo.asc_getStrikeout()); break; } return this.setFontAttributes(prop, val); }; WorkbookView.prototype._onSetCellFormat = function (prop) { var info = new Asc.asc_CFormatCellsInfo(); info.asc_setSymbol(AscCommon.g_oDefaultCultureInfo.LCID); info.asc_setType(Asc.c_oAscNumFormatType.None); var formats = AscCommon.getFormatCells(info); this.setCellFormat(formats[prop]); }; WorkbookView.prototype._onSelectColumnsByRange = function() { this.getWorksheet()._selectColumnsByRange(); }; WorkbookView.prototype._onSelectRowsByRange = function() { this.getWorksheet()._selectRowsByRange(); }; WorkbookView.prototype._onShowCellEditorCursor = function() { // Показываем курсор if (this.getCellEditMode()) { this.cellEditor.showCursor(); } }; WorkbookView.prototype._onDocumentPlaceChanged = function() { if (this.isDocumentPlaceChangedEnabled) { this.handlers.trigger("asc_onDocumentPlaceChanged"); } }; WorkbookView.prototype.getCellStyles = function(width, height) { return AscCommonExcel.generateStyles(width, height, this.model.CellStyles, this); }; WorkbookView.prototype.getWorksheetById = function(id, onlyExist) { var wsModel = this.model.getWorksheetById(id); if (wsModel) { return this.getWorksheet(wsModel.getIndex(), onlyExist); } return null; }; /** * @param {Number} [index] * @param {Boolean} [onlyExist] * @return {AscCommonExcel.WorksheetView} */ WorkbookView.prototype.getWorksheet = function(index, onlyExist) { var wb = this.model; var i = asc_typeof(index) === "number" && index >= 0 ? index : wb.getActive(); var ws = this.wsViews[i]; if (!ws && !onlyExist) { ws = this.wsViews[i] = this._createWorksheetView(wb.getWorksheet(i)); ws._prepareComments(); ws._prepareDrawingObjects(); } return ws; }; WorkbookView.prototype.drawWorksheet = function () { if (-1 === this.wsActive) { return this.showWorksheet(); } var ws = this.getWorksheet(); ws.draw(); ws.objectRender.controller.updateSelectionState(); ws.objectRender.controller.updateOverlay(); this._onScrollReinitialize(AscCommonExcel.c_oAscScrollType.ScrollVertical | AscCommonExcel.c_oAscScrollType.ScrollHorizontal); }; /** * * @param index * @param [bLockDraw] * @returns {WorkbookView} */ WorkbookView.prototype.showWorksheet = function (index, bLockDraw) { if (window["NATIVE_EDITOR_ENJINE"] && !window['IS_NATIVE_EDITOR'] && !window['DoctRendererMode']) { return this; } // ToDo disable method for assembly var ws, wb = this.model; if (asc_typeof(index) !== "number" || 0 > index) { index = wb.getActive(); } if (index === this.wsActive) { if (!bLockDraw) { this.drawWorksheet(); } return this; } var tmpWorksheet, selectionRange = null; // Только если есть активный if (-1 !== this.wsActive) { ws = this.getWorksheet(); // Останавливаем ввод данных в редакторе ввода. Если в режиме ввода формул, то продолжаем работать с cellEditor'ом, чтобы можно было // выбирать ячейки для формулы if (this.getCellEditMode()) { if (this.cellEditor && this.cellEditor.formulaIsOperator()) { this.copyActiveSheet = this.wsActive; if (!this.cellFormulaEnterWSOpen) { this.cellFormulaEnterWSOpen = ws; } else { ws.setFormulaEditMode(false); } } else { this._onStopCellEditing(); } } // Делаем очистку селекта ws.cleanSelection(); this.stopTarget(ws); } if (c_oAscSelectionDialogType.Chart === this.selectionDialogType) { // Когда идет выбор диапазона, то должны на закрываемом листе отменить выбор диапазона tmpWorksheet = this.getWorksheet(); selectionRange = tmpWorksheet.model.selectionRange.getLast().clone(true); tmpWorksheet.setSelectionDialogMode(c_oAscSelectionDialogType.None); } if (this.stateFormatPainter) { // Должны отменить выбор на закрываемом листе this.getWorksheet().formatPainter(c_oAscFormatPainterState.kOff); } if (index !== wb.getActive()) { wb.setActive(index); } this.wsActive = index; this.wsMustDraw = bLockDraw; // Посылаем эвент о смене активного листа this.handlers.trigger("asc_onActiveSheetChanged", this.wsActive); this.handlers.trigger("asc_onHideComment"); ws = this.getWorksheet(index); // Мы делали resize или меняли zoom, но не перерисовывали данный лист (он был не активный) if (ws.updateResize && ws.updateZoom) { ws.changeZoomResize(); } else if (ws.updateResize) { ws.resize(true, this.cellEditor); } else if (ws.updateZoom) { ws.changeZoom(true); } this.updateGroupData(); if (this.cellEditor && this.cellFormulaEnterWSOpen) { if (ws === this.cellFormulaEnterWSOpen) { this.cellFormulaEnterWSOpen.setFormulaEditMode(true); this.cellEditor._showCanvas(); } else if (this.getCellEditMode() && this.cellEditor.isFormula()) { this.cellFormulaEnterWSOpen.setFormulaEditMode(false); /*скрываем cellEditor, в редактор добавляем %selected sheet name%+"!" */ this.cellEditor._hideCanvas(); ws.cleanSelection(); ws.setFormulaEditMode(true); } } if (!bLockDraw) { ws.draw(); } if (c_oAscSelectionDialogType.Chart === this.selectionDialogType) { // Когда идет выбор диапазона, то на показываемом листе должны выставить нужный режим ws.setSelectionDialogMode(this.selectionDialogType, selectionRange); this.handlers.trigger("asc_onSelectionRangeChanged", ws.getSelectionRangeValue()); } if (this.stateFormatPainter) { // Должны отменить выбор на закрываемом листе this.getWorksheet().formatPainter(this.stateFormatPainter); } if (!bLockDraw) { ws.objectRender.controller.updateSelectionState(); ws.objectRender.controller.updateOverlay(); } if (!window["NATIVE_EDITOR_ENJINE"]) { this._onSelectionNameChanged(ws.getSelectionName(/*bRangeText*/false)); this._onWSSelectionChanged(); this._onSelectionMathInfoChanged(ws.getSelectionMathInfo()); } this._onScrollReinitialize(AscCommonExcel.c_oAscScrollType.ScrollVertical | AscCommonExcel.c_oAscScrollType.ScrollHorizontal); // Zoom теперь на каждом листе одинаковый, не отправляем смену //TODO при добавлении любого действия в историю (например добавление нового листа), мы можем его потом отменить с повощью опции авторазвертывания this.toggleAutoCorrectOptions(null, true); window['AscCommon'].g_specialPasteHelper.SpecialPasteButton_Hide(); return this; }; WorkbookView.prototype.stopTarget = function(ws) { if (null === ws && -1 !== this.wsActive) { ws = this.getWorksheet(this.wsActive); } if (null !== ws && ws.objectRender && ws.objectRender.drawingDocument) { ws.objectRender.drawingDocument.TargetEnd(); } }; WorkbookView.prototype.updateWorksheetByModel = function() { // ToDo Сделал небольшую заглушку с показом листа. Нужно как мне кажется перейти от wsViews на wsViewsId (хранить по id) var oldActiveWs; if (-1 !== this.wsActive) { oldActiveWs = this.wsViews[this.wsActive]; } //расставляем ws так как они идут в модели. var oNewWsViews = []; for (var i in this.wsViews) { var item = this.wsViews[i]; if (null != item && null != this.model.getWorksheetById(item.model.getId())) { oNewWsViews[item.model.getIndex()] = item; } } this.wsViews = oNewWsViews; var wsActive = this.model.getActive(); var newActiveWs = this.wsViews[wsActive]; if (undefined === newActiveWs || oldActiveWs !== newActiveWs) { // Если сменили, то покажем this.wsActive = -1; this.showWorksheet(wsActive, true); } else { this.wsActive = wsActive; } }; WorkbookView.prototype._canResize = function() { var isRetina = AscBrowser.isRetina; var oldWidth = this.canvas.width; var oldHeight = this.canvas.height; var width, height, styleWidth, styleHeight; width = styleWidth = this.element.offsetWidth - (this.Api.isMobileVersion ? 0 : this.defaults.scroll.widthPx); height = styleHeight = this.element.offsetHeight - (this.Api.isMobileVersion ? 0 : this.defaults.scroll.heightPx); if (isRetina) { width = AscCommon.AscBrowser.convertToRetinaValue(width, true); height = AscCommon.AscBrowser.convertToRetinaValue(height, true); } if (oldWidth === width && oldHeight === height && this.isInit) { return false; } this.isInit = true; this.canvas.width = this.canvasOverlay.width = this.canvasGraphic.width = this.canvasGraphicOverlay.width = width; this.canvas.height = this.canvasOverlay.height = this.canvasGraphic.height = this.canvasGraphicOverlay.height = height; this.canvas.style.width = this.canvasOverlay.style.width = this.canvasGraphic.style.width = this.canvasGraphicOverlay.style.width = styleWidth + 'px'; this.canvas.style.height = this.canvasOverlay.style.height = this.canvasGraphic.style.height = this.canvasGraphicOverlay.style.height = styleHeight + 'px'; this._reInitGraphics(); return true; }; WorkbookView.prototype._reInitGraphics = function () { var canvasWidth = this.canvasGraphic.width; var canvasHeight = this.canvasGraphic.height; this.shapeCtx.init(this.drawingGraphicCtx.ctx, canvasWidth, canvasHeight, canvasWidth * 25.4 / this.drawingGraphicCtx.ppiX, canvasHeight * 25.4 / this.drawingGraphicCtx.ppiY); this.shapeCtx.CalculateFullTransform(); var overlayWidth = this.canvasGraphicOverlay.width; var overlayHeight = this.canvasGraphicOverlay.height; this.shapeOverlayCtx.init(this.overlayGraphicCtx.ctx, overlayWidth, overlayHeight, overlayWidth * 25.4 / this.overlayGraphicCtx.ppiX, overlayHeight * 25.4 / this.overlayGraphicCtx.ppiY); this.shapeOverlayCtx.CalculateFullTransform(); this.mainGraphics.init(this.drawingCtx.ctx, canvasWidth, canvasHeight, canvasWidth * 25.4 / this.drawingCtx.ppiX, canvasHeight * 25.4 / this.drawingCtx.ppiY); this.trackOverlay.init(this.shapeOverlayCtx.m_oContext, "ws-canvas-graphic-overlay", 0, 0, overlayWidth, overlayHeight, (overlayWidth * 25.4 / this.overlayGraphicCtx.ppiX), (overlayHeight * 25.4 / this.overlayGraphicCtx.ppiY)); this.autoShapeTrack.init(this.trackOverlay, 0, 0, overlayWidth, overlayHeight, overlayWidth * 25.4 / this.overlayGraphicCtx.ppiX, overlayHeight * 25.4 / this.overlayGraphicCtx.ppiY); this.autoShapeTrack.Graphics.CalculateFullTransform(); }; /** @param event {jQuery.Event} */ WorkbookView.prototype.resize = function(event) { if (this._canResize()) { var item; var activeIndex = this.model.getActive(); for (var i in this.wsViews) { item = this.wsViews[i]; // Делаем resize (для не активных сменим как только сделаем его активным) item.resize(/*isDraw*/i == activeIndex, this.cellEditor); } this.drawWorksheet(); } else { // ToDo не должно происходить ничего, но нам приходит resize сверху, поэтому проверим отрисовывали ли мы if (-1 === this.wsActive || this.wsMustDraw) { this.drawWorksheet(); } } this.wsMustDraw = false; }; WorkbookView.prototype.getSelectionInfo = function () { if (!this.oSelectionInfo) { this._updateSelectionInfo(); } return this.oSelectionInfo; }; // Получаем свойство: редактируем мы сейчас или нет WorkbookView.prototype.getCellEditMode = function() { return this.isCellEditMode; }; WorkbookView.prototype.setCellEditMode = function(flag) { this.isCellEditMode = !!flag; }; WorkbookView.prototype.getIsTrackShape = function() { var ws = this.getWorksheet(); if (!ws) { return false; } if (ws.objectRender && ws.objectRender.controller) { return ws.objectRender.controller.checkTrackDrawings(); } }; WorkbookView.prototype.getZoom = function() { return this.drawingCtx.getZoom(); }; WorkbookView.prototype.changeZoom = function(factor) { if (factor === this.getZoom()) { return; } this.buffers.main.changeZoom(factor); this.buffers.overlay.changeZoom(factor); this.buffers.mainGraphic.changeZoom(factor); this.buffers.overlayGraphic.changeZoom(factor); if (!factor) { this.cellEditor.changeZoom(factor); } // Нужно сбросить кэш букв var i, length; for (i = 0, length = this.fmgrGraphics.length; i < length; ++i) this.fmgrGraphics[i].ClearFontsRasterCache(); if (AscCommon.g_fontManager) { AscCommon.g_fontManager.ClearFontsRasterCache(); AscCommon.g_fontManager.m_pFont = null; } if (AscCommon.g_fontManager2) { AscCommon.g_fontManager2.ClearFontsRasterCache(); AscCommon.g_fontManager2.m_pFont = null; } if (!factor) { this.wsMustDraw = true; this._calcMaxDigitWidth(); } var item; var activeIndex = this.model.getActive(); for (i in this.wsViews) { item = this.wsViews[i]; // Меняем zoom (для не активных сменим как только сделаем его активным) if (!factor) { item._initWorksheetDefaultWidth(); } item.changeZoom(/*isDraw*/i == activeIndex); this._reInitGraphics(); item.objectRender.changeZoom(this.drawingCtx.scaleFactor); if (i == activeIndex && factor) { item.draw(); //ToDo item.drawDepCells(); } } this._onScrollReinitialize(AscCommonExcel.c_oAscScrollType.ScrollVertical | AscCommonExcel.c_oAscScrollType.ScrollHorizontal); this.handlers.trigger("asc_onZoomChanged", this.getZoom()); }; WorkbookView.prototype.getEnableKeyEventsHandler = function(bIsNaturalFocus) { var res = this.enableKeyEvents; if (res && bIsNaturalFocus && this.getCellEditMode() && this.input.isFocused) { res = false; } return res; }; WorkbookView.prototype.enableKeyEventsHandler = function(f) { this.enableKeyEvents = !!f; this.controller.enableKeyEventsHandler(this.enableKeyEvents); if (this.cellEditor) { this.cellEditor.enableKeyEventsHandler(this.enableKeyEvents); } }; // Останавливаем ввод данных в редакторе ввода WorkbookView.prototype.closeCellEditor = function (cancel) { return this.getCellEditMode() ? this._onStopCellEditing(cancel) : true; }; WorkbookView.prototype.restoreFocus = function() { if (window["NATIVE_EDITOR_ENJINE"]) { return; } if (this.cellEditor.hasFocus) { this.cellEditor.restoreFocus(); } }; WorkbookView.prototype._onUpdateCellEditor = function(text, cursorPosition, fPos, fName) { if (this.skipHelpSelector) { return; } // ToDo для ускорения можно завести объект, куда класть результаты поиска по формулам и второй раз не искать. var i, arrResult = [], defNamesList, defName, defNameStr; if (fName) { fName = fName.toUpperCase(); for (i = 0; i < this.formulasList.length; ++i) { if (0 === this.formulasList[i].indexOf(fName)) { arrResult.push(new AscCommonExcel.asc_CCompleteMenu(this.formulasList[i], c_oAscPopUpSelectorType.Func)); } } defNamesList = this.getDefinedNames(Asc.c_oAscGetDefinedNamesList.WorksheetWorkbook); fName = fName.toLowerCase(); for (i = 0; i < defNamesList.length; ++i) { /*defName = defNamesList[i]; if (0 === defName.Name.toLowerCase().indexOf(fName)) { arrResult.push(new AscCommonExcel.asc_CCompleteMenu(defName.Name, !defName.isTable ? c_oAscPopUpSelectorType.Range : c_oAscPopUpSelectorType.Table));*/ defName = defNamesList[i]; defNameStr = defName.Name.toLowerCase(); if(null !== defName.LocalSheetId && defNameStr === "print_area") { defNameStr = AscCommon.translateManager.getValue("Print_Area"); } if (0 === defNameStr.toLowerCase().indexOf(fName)) { arrResult.push(new AscCommonExcel.asc_CCompleteMenu(defNameStr, !defName.isTable ? c_oAscPopUpSelectorType.Range : c_oAscPopUpSelectorType.Table)); } } } if (0 < arrResult.length) { this.handlers.trigger('asc_onFormulaCompleteMenu', arrResult); this.lastFPos = fPos; this.lastFNameLength = fName.length; } else { this.handlers.trigger('asc_onFormulaCompleteMenu', null); this.lastFPos = -1; this.lastFNameLength = 0; } }; // Вставка формулы в редактор WorkbookView.prototype.insertFormulaInEditor = function (name, type, autoComplete) { var t = this, ws = this.getWorksheet(), cursorPos, isNotFunction, tmp; var activeCellRange = ws.getActiveCell(0, 0, false); if (ws.model.inPivotTable(activeCellRange)) { this.handlers.trigger("asc_onError", c_oAscError.ID.LockedCellPivot, c_oAscError.Level.NoCritical); return; } if (c_oAscPopUpSelectorType.None === type) { ws.setSelectionInfo("value", name, /*onlyActive*/true); return; } isNotFunction = c_oAscPopUpSelectorType.Func !== type; // Проверяем, открыт ли редактор if (this.getCellEditMode()) { if (isNotFunction) { this.skipHelpSelector = true; } if (-1 !== this.lastFPos) { if (-1 === this.arrExcludeFormulas.indexOf(name) && !isNotFunction) { //если следующий символ скобка - не добавляем ещё одну if('(' !== this.cellEditor.textRender.getChars(this.cellEditor.cursorPos, 1)) { name += '('; // ToDo сделать проверки при добавлении, чтобы не вызывать постоянно окно } } else { this.skipHelpSelector = true; } tmp = this.cellEditor.skipTLUpdate; this.cellEditor.skipTLUpdate = false; this.cellEditor.replaceText(this.lastFPos, this.lastFNameLength, name); this.cellEditor.skipTLUpdate = tmp; } else if (false === this.cellEditor.insertFormula(name, isNotFunction)) { // Не смогли вставить формулу, закроем редактор, с сохранением текста this.cellEditor.close(true); } this.skipHelpSelector = false; } else { // Проверка глобального лока if (this.collaborativeEditing.getGlobalLock()) { return; } var selectionRange = ws.model.selectionRange.clone(); // Редактор закрыт var cellRange = {}; // Если нужно сделать автозаполнение формулы, то ищем ячейки) if (autoComplete) { cellRange = ws.autoCompleteFormula(name); } if (isNotFunction) { name = "=" + name; } else { if (cellRange.notEditCell) { // Мы уже ввели все что нужно, редактор открывать не нужно return; } if (cellRange.text) { // Меняем значение ячейки name = "=" + name + "(" + cellRange.text + ")"; } else { // Меняем значение ячейки name = "=" + name + "()"; } // Вычисляем позицию курсора (он должен быть в функции) cursorPos = name.length - 1; } var openEditor = function (res) { if (res) { // Выставляем переменные, что мы редактируем t.setCellEditMode(true); if (isNotFunction) { t.skipHelpSelector = true; } t.hideSpecialPasteButton(); // Открываем, с выставлением позиции курсора ws.openCellEditorWithText(t.cellEditor, name, cursorPos, /*isFocus*/false, selectionRange); if (isNotFunction) { t.skipHelpSelector = false; } } else { t.setCellEditMode(false); t.controller.setStrictClose(false); t.controller.setFormulaEditMode(false); ws.setFormulaEditMode(false); } }; ws._isLockedCells(activeCellRange, /*subType*/null, openEditor); } }; WorkbookView.prototype.bIsEmptyClipboard = function() { return g_clipboardExcel.bIsEmptyClipboard(this.getCellEditMode()); }; WorkbookView.prototype.checkCopyToClipboard = function(_clipboard, _formats) { var t = this, ws; ws = t.getWorksheet(); g_clipboardExcel.checkCopyToClipboard(ws, _clipboard, _formats); }; WorkbookView.prototype.pasteData = function(_format, data1, data2, text_data, doNotShowButton) { var t = this, ws; ws = t.getWorksheet(); g_clipboardExcel.pasteData(ws, _format, data1, data2, text_data, null, doNotShowButton); }; WorkbookView.prototype.specialPasteData = function(props) { if (!this.getCellEditMode()) { this.getWorksheet().specialPaste(props); } }; WorkbookView.prototype.showSpecialPasteButton = function(props) { if (!this.getCellEditMode()) { this.getWorksheet().showSpecialPasteOptions(props); } }; WorkbookView.prototype.updateSpecialPasteButton = function(props) { if (!this.getCellEditMode()) { this.getWorksheet().updateSpecialPasteButton(props); } }; WorkbookView.prototype.hideSpecialPasteButton = function() { //TODO пересмотреть! //сейчас сначала добавляются данные в историю, потом идет закрытие редактора ячейки //следовательно убираю проверку на редактирование ячейки /*if (!this.getCellEditMode()) {*/ this.handlers.trigger("hideSpecialPasteOptions"); //} }; WorkbookView.prototype.selectionCut = function () { if (this.getCellEditMode()) { this.cellEditor.cutSelection(); } else { if (this.getWorksheet().isNeedSelectionCut()) { this.getWorksheet().emptySelection(c_oAscCleanOptions.All, true); } else { //в данном случае не вырезаем, а записываем if(false === this.getWorksheet().isMultiSelect()) { this.cutIdSheet = this.getWorksheet().model.Id; this.getWorksheet().cutRange = this.getWorksheet().model.selectionRange.getLast(); } } } }; WorkbookView.prototype.undo = function() { var oFormulaLocaleInfo = AscCommonExcel.oFormulaLocaleInfo; oFormulaLocaleInfo.Parse = false; oFormulaLocaleInfo.DigitSep = false; if (!this.getCellEditMode()) { if (!History.Undo() && this.collaborativeEditing.getFast() && this.collaborativeEditing.getCollaborativeEditing()) { this.Api.sync_TryUndoInFastCollaborative(); } } else { this.cellEditor.undo(); } oFormulaLocaleInfo.Parse = true; oFormulaLocaleInfo.DigitSep = true; }; WorkbookView.prototype.redo = function() { if (!this.getCellEditMode()) { History.Redo(); } else { this.cellEditor.redo(); } }; WorkbookView.prototype.setFontAttributes = function(prop, val) { if (!this.getCellEditMode()) { this.getWorksheet().setSelectionInfo(prop, val); } else { this.cellEditor.setTextStyle(prop, val); } }; WorkbookView.prototype.changeFontSize = function(prop, val) { if (!this.getCellEditMode()) { this.getWorksheet().setSelectionInfo(prop, val); } else { this.cellEditor.setTextStyle(prop, val); } }; WorkbookView.prototype.setCellFormat = function (format) { this.getWorksheet().setSelectionInfo("format", format); }; WorkbookView.prototype.emptyCells = function (options) { if (!this.getCellEditMode()) { if (Asc.c_oAscCleanOptions.Comments === options) { this.removeAllComments(false, true); } else { this.getWorksheet().emptySelection(options); } this.restoreFocus(); } else { this.cellEditor.empty(options); } }; WorkbookView.prototype.setSelectionDialogMode = function(selectionDialogType, selectRange) { if (selectionDialogType === this.selectionDialogType) { return; } if (c_oAscSelectionDialogType.None === selectionDialogType) { this.selectionDialogType = selectionDialogType; this.getWorksheet().setSelectionDialogMode(selectionDialogType, selectRange); if (this.copyActiveSheet !== this.wsActive) { this.showWorksheet(this.copyActiveSheet); } this.copyActiveSheet = -1; this.input.disabled = false; } else { this.copyActiveSheet = this.wsActive; var index, tmpSelectRange = AscCommon.parserHelp.parse3DRef(selectRange); if (tmpSelectRange) { if (c_oAscSelectionDialogType.Chart === selectionDialogType) { // Получаем sheet по имени var ws = this.model.getWorksheetByName(tmpSelectRange.sheet); if (!ws || ws.getHidden()) { tmpSelectRange = null; } else { index = ws.getIndex(); this.showWorksheet(index); tmpSelectRange = tmpSelectRange.range; } } else { tmpSelectRange = tmpSelectRange.range; } } else { // Это не 3D ссылка tmpSelectRange = selectRange; } this.getWorksheet().setSelectionDialogMode(selectionDialogType, tmpSelectRange); // Нужно выставить после, т.к. при смене листа не должны проставлять режим this.selectionDialogType = selectionDialogType; this.input.disabled = true; } }; WorkbookView.prototype.formatPainter = function(stateFormatPainter) { // Если передали состояние, то выставляем его. Если нет - то меняем на противоположное. this.stateFormatPainter = (null != stateFormatPainter) ? stateFormatPainter : ((c_oAscFormatPainterState.kOff !== this.stateFormatPainter) ? c_oAscFormatPainterState.kOff : c_oAscFormatPainterState.kOn); this.rangeFormatPainter = this.getWorksheet().formatPainter(this.stateFormatPainter); if (this.stateFormatPainter) { this.copyActiveSheet = this.wsActive; } else { this.copyActiveSheet = -1; this.handlers.trigger('asc_onStopFormatPainter'); } }; // Поиск текста в листе WorkbookView.prototype.findCellText = function (options) { this.closeCellEditor(); // Для поиска эта переменная не нужна (но она может остаться от replace) options.selectionRange = null; var result = this.model.findCellText(options); if (result) { var ws = this.getWorksheet(); var range = new Asc.Range(result.col, result.row, result.col, result.row); options.findInSelection ? ws.setActiveCell(result) : ws.setSelection(range); return true; } return null; }; // Замена текста в листе WorkbookView.prototype.replaceCellText = function(options) { if (!options.isMatchCase) { options.findWhat = options.findWhat.toLowerCase(); } options.findRegExp = AscCommonExcel.getFindRegExp(options.findWhat, options); var ws = this.getWorksheet(); // Останавливаем ввод данных в редакторе ввода if (this.getCellEditMode()) { this._onStopCellEditing(); } History.Create_NewPoint(); History.StartTransaction(); options.clearFindAll(); if (options.isReplaceAll) { // На ReplaceAll ставим медленную операцию this.Api.sync_StartAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.SlowOperation); } ws.replaceCellText(options, false, this.fReplaceCallback); }; WorkbookView.prototype._replaceCellTextCallback = function(options) { if (!options.error) { options.updateFindAll(); if (!options.scanOnOnlySheet && options.isReplaceAll) { // Замена на всей книге var i = ++options.sheetIndex; if (this.model.getActive() === i) { i = ++options.sheetIndex; } if (i < this.model.getWorksheetCount()) { var ws = this.getWorksheet(i); ws.replaceCellText(options, true, this.fReplaceCallback); return; } options.sheetIndex = -1; } this.handlers.trigger("asc_onRenameCellTextEnd", options.countFindAll, options.countReplaceAll); } History.EndTransaction(); if (options.isReplaceAll) { // Заканчиваем медленную операцию this.Api.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.SlowOperation); } }; WorkbookView.prototype.getDefinedNames = function(defNameListId) { return this.model.getDefinedNamesWB(defNameListId, true); }; WorkbookView.prototype.setDefinedNames = function(defName) { //ToDo проверка defName.ref на знак "=" в начале ссылки. знака нет тогда это либо число либо строка, так делает Excel. this.model.setDefinesNames(defName.Name, defName.Ref, defName.Scope); this.handlers.trigger("asc_onDefName"); }; WorkbookView.prototype.editDefinedNames = function(oldName, newName) { //ToDo проверка defName.ref на знак "=" в начале ссылки. знака нет тогда это либо число либо строка, так делает Excel. if (this.collaborativeEditing.getGlobalLock()) { return; } var ws = this.getWorksheet(), t = this; var editDefinedNamesCallback = function(res) { if (res) { if (oldName && oldName.asc_getIsTable()) { ws.model.autoFilters.changeDisplayNameTable(oldName.asc_getName(), newName.asc_getName()); } else { t.model.editDefinesNames(oldName, newName); } t.handlers.trigger("asc_onEditDefName", oldName, newName); //условие исключает второй вызов asc_onRefreshDefNameList(первый в unlockDefName) if(!(t.collaborativeEditing.getCollaborativeEditing() && t.collaborativeEditing.getFast())) { t.handlers.trigger("asc_onRefreshDefNameList"); } } else { t.handlers.trigger("asc_onError", c_oAscError.ID.LockCreateDefName, c_oAscError.Level.NoCritical); } t._onSelectionNameChanged(ws.getSelectionName(/*bRangeText*/false)); if(ws.viewPrintLines) { ws.updateSelection(); } }; var defNameId; if (oldName) { defNameId = t.model.getDefinedName(oldName); defNameId = defNameId ? defNameId.getNodeId() : null; } var callback = function() { ws._isLockedDefNames(editDefinedNamesCallback, defNameId); }; var tableRange; if(oldName && true === oldName.isTable) { var table = ws.model.autoFilters._getFilterByDisplayName(oldName.Name); if(table) { tableRange = table.Ref; } } if(tableRange) { ws._isLockedCells( tableRange, null, callback ); } else { callback(); } }; WorkbookView.prototype.delDefinedNames = function(oldName) { //ToDo проверка defName.ref на знак "=" в начале ссылки. знака нет тогда это либо число либо строка, так делает Excel. if (this.collaborativeEditing.getGlobalLock()) { return; } var ws = this.getWorksheet(), t = this; if (oldName) { var delDefinedNamesCallback = function(res) { if (res) { t.model.delDefinesNames(oldName); t.handlers.trigger("asc_onRefreshDefNameList"); } else { t.handlers.trigger("asc_onError", c_oAscError.ID.LockCreateDefName, c_oAscError.Level.NoCritical); } t._onSelectionNameChanged(ws.getSelectionName(/*bRangeText*/false)); if(ws.viewPrintLines) { ws.updateSelection(); } }; var defNameId = t.model.getDefinedName(oldName).getNodeId(); ws._isLockedDefNames(delDefinedNamesCallback, defNameId); } }; WorkbookView.prototype.getDefaultDefinedName = function() { //ToDo проверка defName.ref на знак "=" в начале ссылки. знака нет тогда это либо число либо строка, так делает Excel. var ws = this.getWorksheet(); var oRangeValue = ws.getSelectionRangeValue(); return new Asc.asc_CDefName("", oRangeValue.asc_getName(), null); }; WorkbookView.prototype.getDefaultTableStyle = function() { return this.model.TableStyles.DefaultTableStyle; }; WorkbookView.prototype.unlockDefName = function() { this.model.unlockDefName(); this.handlers.trigger("asc_onRefreshDefNameList"); this.handlers.trigger("asc_onLockDefNameManager", Asc.c_oAscDefinedNameReason.OK); }; WorkbookView.prototype.unlockCurrentDefName = function(name, sheetId) { this.model.unlockCurrentDefName(name, sheetId); //this.handlers.trigger("asc_onRefreshDefNameList"); //this.handlers.trigger("asc_onLockDefNameManager", Asc.c_oAscDefinedNameReason.OK); }; WorkbookView.prototype._onCheckDefNameLock = function() { return this.model.checkDefNameLock(); }; // Печать WorkbookView.prototype.printSheets = function(printPagesData, pdfDocRenderer) { //change zoom on default var viewZoom = this.getZoom(); this.changeZoom(1); var pdfPrinter = new AscCommonExcel.CPdfPrinter(this.fmgrGraphics[3], this.m_oFont); if (pdfDocRenderer) { pdfPrinter.DocumentRenderer = pdfDocRenderer; } var ws; if (0 === printPagesData.arrPages.length) { // Печать пустой страницы ws = this.getWorksheet(); ws.drawForPrint(pdfPrinter, null); } else { var indexWorksheet = -1; var indexWorksheetTmp = -1; for (var i = 0; i < printPagesData.arrPages.length; ++i) { indexWorksheetTmp = printPagesData.arrPages[i].indexWorksheet; if (indexWorksheetTmp !== indexWorksheet) { ws = this.getWorksheet(indexWorksheetTmp); indexWorksheet = indexWorksheetTmp; } ws.drawForPrint(pdfPrinter, printPagesData.arrPages[i], i, printPagesData.arrPages.length); } } this.changeZoom(viewZoom); return pdfPrinter; }; WorkbookView.prototype._calcPagesPrintSheet = function (index, printPagesData, onlySelection, adjustPrint) { var ws = this.model.getWorksheet(index); var wsView = this.getWorksheet(index); if (!ws.getHidden()) { var pageOptionsMap = adjustPrint ? adjustPrint.asc_getPageOptionsMap() : null; var pagePrintOptions = pageOptionsMap && pageOptionsMap[index] ? pageOptionsMap[index] : ws.PagePrintOptions; wsView.calcPagesPrint(pagePrintOptions, onlySelection, index, printPagesData.arrPages, null, adjustPrint); } }; WorkbookView.prototype.calcPagesPrint = function (adjustPrint) { if (!adjustPrint) { adjustPrint = new Asc.asc_CAdjustPrint(); } var viewZoom = this.getZoom(); this.changeZoom(1); var printPagesData = new asc_CPrintPagesData(); var printType = adjustPrint.asc_getPrintType(); if (printType === Asc.c_oAscPrintType.ActiveSheets) { this._calcPagesPrintSheet(this.model.getActive(), printPagesData, false, adjustPrint); } else if (printType === Asc.c_oAscPrintType.EntireWorkbook) { // Колличество листов var countWorksheets = this.model.getWorksheetCount(); for (var i = 0; i < countWorksheets; ++i) { if(adjustPrint.isOnlyFirstPage && i !== 0) { break; } this._calcPagesPrintSheet(i, printPagesData, false, adjustPrint); } } else if (printType === Asc.c_oAscPrintType.Selection) { this._calcPagesPrintSheet(this.model.getActive(), printPagesData, true, adjustPrint); } if (AscCommonExcel.c_kMaxPrintPages === printPagesData.arrPages.length) { this.handlers.trigger("asc_onError", c_oAscError.ID.PrintMaxPagesCount, c_oAscError.Level.NoCritical); } this.changeZoom(viewZoom); return printPagesData; }; // Вызывать только для нативной печати WorkbookView.prototype._nativeCalculate = function() { var item; for (var i in this.wsViews) { item = this.wsViews[i]; item._cleanCellsTextMetricsCache(); item._prepareDrawingObjects(); } }; WorkbookView.prototype.calculate = function (type) { this.model.calculate(type); this.drawWS(); }; WorkbookView.prototype.reInit = function() { var ws = this.getWorksheet(); ws._initCellsArea(AscCommonExcel.recalcType.full); ws._updateVisibleColsCount(); ws._updateVisibleRowsCount(); }; WorkbookView.prototype.drawWS = function() { this.getWorksheet().draw(); }; WorkbookView.prototype.onShowDrawingObjects = function(clearCanvas) { var ws = this.getWorksheet(); ws.objectRender.showDrawingObjects(clearCanvas); }; WorkbookView.prototype.insertHyperlink = function(options) { var ws = this.getWorksheet(); if (ws.objectRender.selectedGraphicObjectsExists()) { if (ws.objectRender.controller.canAddHyperlink()) { ws.objectRender.controller.insertHyperlink(options); } } else { ws.setSelectionInfo("hyperlink", options); this.restoreFocus(); } }; WorkbookView.prototype.removeHyperlink = function() { var ws = this.getWorksheet(); if (ws.objectRender.selectedGraphicObjectsExists()) { ws.objectRender.controller.removeHyperlink(); } else { ws.setSelectionInfo("rh"); } }; WorkbookView.prototype.setDocumentPlaceChangedEnabled = function(val) { this.isDocumentPlaceChangedEnabled = val; }; WorkbookView.prototype.showComments = function (val, isShowSolved) { if (this.isShowComments !== val || this.isShowSolved !== isShowSolved) { this.isShowComments = val; this.isShowSolved = isShowSolved; this.drawWS(); } }; WorkbookView.prototype.removeComment = function (id) { var ws = this.getWorksheet(); ws.cellCommentator.removeComment(id); this.cellCommentator.removeComment(id); }; WorkbookView.prototype.removeAllComments = function (isMine, isCurrent) { var range; var ws = this.getWorksheet(); isMine = isMine ? (this.Api.DocInfo && this.Api.DocInfo.get_UserId()) : null; History.Create_NewPoint(); History.StartTransaction(); if (isCurrent) { ws._getSelection().ranges.forEach(function (item) { ws.cellCommentator.deleteCommentsRange(item, isMine); }); } else { range = new Asc.Range(0, 0, AscCommon.gc_nMaxCol0, AscCommon.gc_nMaxRow0); this.cellCommentator.deleteCommentsRange(range, isMine); ws.cellCommentator.deleteCommentsRange(range, isMine); } History.EndTransaction(); }; /* * @param {c_oAscRenderingModeType} mode Режим отрисовки * @param {Boolean} isInit инициализация или нет */ WorkbookView.prototype.setFontRenderingMode = function(mode, isInit) { if (mode !== this.fontRenderingMode) { this.fontRenderingMode = mode; if (c_oAscFontRenderingModeType.noHinting === mode) { this._setHintsProps(false, false); } else if (c_oAscFontRenderingModeType.hinting === mode) { this._setHintsProps(true, false); } else if (c_oAscFontRenderingModeType.hintingAndSubpixeling === mode) { this._setHintsProps(true, true); } if (!isInit) { this.drawWS(); this.cellEditor.setFontRenderingMode(mode); } } }; WorkbookView.prototype.initFormulasList = function() { this.formulasList = []; var oFormulaList = AscCommonExcel.cFormulaFunctionLocalized ? AscCommonExcel.cFormulaFunctionLocalized : AscCommonExcel.cFormulaFunction; for (var f in oFormulaList) { this.formulasList.push(f); } this.arrExcludeFormulas = [cBoolLocal.t, cBoolLocal.f]; }; WorkbookView.prototype._setHintsProps = function(bIsHinting, bIsSubpixHinting) { var manager; for (var i = 0, length = this.fmgrGraphics.length; i < length; ++i) { manager = this.fmgrGraphics[i]; // Последний без хинтования (только для измерения) if (i === length - 1) { bIsHinting = bIsSubpixHinting = false; } manager.SetHintsProps(bIsHinting, bIsSubpixHinting); } }; WorkbookView.prototype._calcMaxDigitWidth = function () { // set default worksheet header font for calculations this.buffers.main.setFont(AscCommonExcel.g_oDefaultFormat.Font); // Измеряем в pt this.stringRender.measureString("0123456789", new AscCommonExcel.CellFlags()); // Переводим в px и приводим к целому (int) this.model.maxDigitWidth = this.maxDigitWidth = this.stringRender.getWidestCharWidth(); // Проверка для Calibri 11 должно быть this.maxDigitWidth = 7 if (!this.maxDigitWidth) { throw "Error: can't measure text string"; } // Padding рассчитывается исходя из maxDigitWidth (http://social.msdn.microsoft.com/Forums/en-US/9a6a9785-66ad-4b6b-bb9f-74429381bd72/margin-padding-in-cell-excel?forum=os_binaryfile) this.defaults.worksheetView.cells.padding = Math.max(asc.ceil(this.maxDigitWidth / 4), 2); this.model.paddingPlusBorder = 2 * this.defaults.worksheetView.cells.padding + 1; }; WorkbookView.prototype.getPivotMergeStyle = function (sheetMergedStyles, range, style, pivot) { var styleInfo = pivot.asc_getStyleInfo(); var i, r, dxf, stripe1, stripe2, emptyStripe = new Asc.CTableStyleElement(); if (style) { dxf = style.wholeTable && style.wholeTable.dxf; if (dxf) { sheetMergedStyles.setTablePivotStyle(range, dxf); } if (styleInfo.showColStripes) { stripe1 = style.firstColumnStripe || emptyStripe; stripe2 = style.secondColumnStripe || emptyStripe; if (stripe1.dxf) { sheetMergedStyles.setTablePivotStyle(range, stripe1.dxf, new Asc.CTableStyleStripe(stripe1.size, stripe2.size)); } if (stripe2.dxf && range.c1 + stripe1.size <= range.c2) { sheetMergedStyles.setTablePivotStyle( new Asc.Range(range.c1 + stripe1.size, range.r1, range.c2, range.r2), stripe2.dxf, new Asc.CTableStyleStripe(stripe2.size, stripe1.size)); } } if (styleInfo.showRowStripes) { stripe1 = style.firstRowStripe || emptyStripe; stripe2 = style.secondRowStripe || emptyStripe; if (stripe1.dxf) { sheetMergedStyles.setTablePivotStyle(range, stripe1.dxf, new Asc.CTableStyleStripe(stripe1.size, stripe2.size, true)); } if (stripe2.dxf && range.r1 + stripe1.size <= range.r2) { sheetMergedStyles.setTablePivotStyle( new Asc.Range(range.c1, range.r1 + stripe1.size, range.c2, range.r2), stripe2.dxf, new Asc.CTableStyleStripe(stripe2.size, stripe1.size, true)); } } dxf = style.firstColumn && style.firstColumn.dxf; if (styleInfo.showRowHeaders && dxf) { sheetMergedStyles.setTablePivotStyle(new Asc.Range(range.c1, range.r1, range.c1, range.r2), dxf); } dxf = style.headerRow && style.headerRow.dxf; if (styleInfo.showColHeaders && dxf) { sheetMergedStyles.setTablePivotStyle(new Asc.Range(range.c1, range.r1, range.c2, range.r1), dxf); } dxf = style.firstHeaderCell && style.firstHeaderCell.dxf; if (styleInfo.showColHeaders && styleInfo.showRowHeaders && dxf) { sheetMergedStyles.setTablePivotStyle(new Asc.Range(range.c1, range.r1, range.c1, range.r1), dxf); } if (pivot.asc_getColGrandTotals()) { dxf = style.lastColumn && style.lastColumn.dxf; if (dxf) { sheetMergedStyles.setTablePivotStyle(new Asc.Range(range.c2, range.r1, range.c2, range.r2), dxf); } } if (styleInfo.showRowHeaders) { for (i = range.r1 + 1; i < range.r2; ++i) { r = i - (range.r1 + 1); if (0 === r % 3) { dxf = style.firstRowSubheading; } if (dxf = (dxf && dxf.dxf)) { sheetMergedStyles.setTablePivotStyle(new Asc.Range(range.c1, i, range.c2, i), dxf); } } } if (pivot.asc_getRowGrandTotals()) { dxf = style.totalRow && style.totalRow.dxf; if (dxf) { sheetMergedStyles.setTablePivotStyle(new Asc.Range(range.c1, range.r2, range.c2, range.r2), dxf); } } } }; WorkbookView.prototype.getTableStyles = function (props, bPivotTable) { var wb = this.model; var t = this; var result = []; var canvas = document.createElement('canvas'); var tableStyleInfo; var pivotStyleInfo; var defaultStyles, styleThumbnailHeight, row, col = 5; var styleThumbnailWidth = window["IS_NATIVE_EDITOR"] ? 90 : 61; if(bPivotTable) { styleThumbnailHeight = 49; row = 8; defaultStyles = wb.TableStyles.DefaultStylesPivot; pivotStyleInfo = props; } else { styleThumbnailHeight = window["IS_NATIVE_EDITOR"] ? 48 : 46; row = 5; defaultStyles = wb.TableStyles.DefaultStyles; tableStyleInfo = new AscCommonExcel.TableStyleInfo(); if (props) { tableStyleInfo.ShowColumnStripes = props.asc_getBandVer(); tableStyleInfo.ShowFirstColumn = props.asc_getFirstCol(); tableStyleInfo.ShowLastColumn = props.asc_getLastCol(); tableStyleInfo.ShowRowStripes = props.asc_getBandHor(); tableStyleInfo.HeaderRowCount = props.asc_getFirstRow(); tableStyleInfo.TotalsRowCount = props.asc_getLastRow(); } else { tableStyleInfo.ShowColumnStripes = false; tableStyleInfo.ShowFirstColumn = false; tableStyleInfo.ShowLastColumn = false; tableStyleInfo.ShowRowStripes = true; tableStyleInfo.HeaderRowCount = true; tableStyleInfo.TotalsRowCount = false; } } if (AscBrowser.isRetina) { styleThumbnailWidth = AscCommon.AscBrowser.convertToRetinaValue(styleThumbnailWidth, true); styleThumbnailHeight = AscCommon.AscBrowser.convertToRetinaValue(styleThumbnailHeight, true); } canvas.width = styleThumbnailWidth; canvas.height = styleThumbnailHeight; var sizeInfo = {w: styleThumbnailWidth, h: styleThumbnailHeight, row: row, col: col}; var ctx = new Asc.DrawingContext({canvas: canvas, units: 0/*px*/, fmgrGraphics: this.fmgrGraphics, font: this.m_oFont}); var addStyles = function(styles, type, bEmptyStyle) { var style; for (var i in styles) { if ((bPivotTable && styles[i].pivot) || (!bPivotTable && styles[i].table)) { if (window["IS_NATIVE_EDITOR"]) { //TODO empty style? window["native"]["BeginDrawStyle"](type, i); } t._drawTableStyle(ctx, styles[i], tableStyleInfo, pivotStyleInfo, sizeInfo); if (window["IS_NATIVE_EDITOR"]) { window["native"]["EndDrawStyle"](); } else { style = new AscCommon.CStyleImage(); style.name = bEmptyStyle ? null : i; style.displayName = styles[i].displayName; style.type = type; style.image = canvas.toDataURL("image/png"); result.push(style); } } } }; addStyles(wb.TableStyles.CustomStyles, AscCommon.c_oAscStyleImage.Document); if (props) { //None style var emptyStyle = new Asc.CTableStyle(); emptyStyle.displayName = "None"; emptyStyle.pivot = bPivotTable; addStyles({null: emptyStyle}, AscCommon.c_oAscStyleImage.Default, true); } addStyles(defaultStyles, AscCommon.c_oAscStyleImage.Default); return result; }; WorkbookView.prototype._drawTableStyle = function (ctx, style, tableStyleInfo, pivotStyleInfo, size) { ctx.clear(); var w = size.w; var h = size.h; var row = size.row; var col = size.col; var startX = 1; var startY = 1; var ySize = (h - 1) - 2 * startY; var xSize = w - 2 * startX; var stepY = (ySize) / row; var stepX = (xSize) / col; var lineStepX = (xSize - 1) / 5; var whiteColor = new CColor(255, 255, 255); var blackColor = new CColor(0, 0, 0); var defaultColor; if (!style || !style.wholeTable || !style.wholeTable.dxf.font) { defaultColor = blackColor; } else { defaultColor = style.wholeTable.dxf.font.getColor(); } ctx.setFillStyle(whiteColor); ctx.fillRect(0, 0, xSize + 2 * startX, ySize + 2 * startY); var calculateLineVer = function(color, x, y1, y2) { ctx.beginPath(); ctx.setStrokeStyle(color); ctx.lineVer(x + startX, y1 + startY, y2 + startY); ctx.stroke(); ctx.closePath(); }; var calculateLineHor = function(color, x1, y, x2) { ctx.beginPath(); ctx.setStrokeStyle(color); ctx.lineHor(x1 + startX, y + startY, x2 + startX); ctx.stroke(); ctx.closePath(); }; var calculateRect = function(color, x1, y1, w, h) { ctx.beginPath(); ctx.setFillStyle(color); ctx.fillRect(x1 + startX, y1 + startY, w, h); ctx.closePath(); }; var bbox = new Asc.Range(0, 0, col - 1, row - 1); var sheetMergedStyles = new AscCommonExcel.SheetMergedStyles(); var hiddenManager = new AscCommonExcel.HiddenManager(null); if(pivotStyleInfo) { this.getPivotMergeStyle(sheetMergedStyles, bbox, style, pivotStyleInfo); } else if(tableStyleInfo) { style.initStyle(sheetMergedStyles, bbox, tableStyleInfo, null !== tableStyleInfo.HeaderRowCount ? tableStyleInfo.HeaderRowCount : 1, null !== tableStyleInfo.TotalsRowCount ? tableStyleInfo.TotalsRowCount : 0); } var compiledStylesArr = []; for (var i = 0; i < row; i++) { for (var j = 0; j < col; j++) { var color = null, prevStyle; var curStyle = AscCommonExcel.getCompiledStyle(sheetMergedStyles, hiddenManager, i, j); if(!compiledStylesArr[i]) { compiledStylesArr[i] = []; } compiledStylesArr[i][j] = curStyle; //fill color = curStyle && curStyle.fill && curStyle.fill.bg(); if(color) { calculateRect(color, j * stepX, i * stepY, stepX, stepY); } //borders //left prevStyle = (j - 1 >= 0) ? compiledStylesArr[i][j - 1] : null; color = AscCommonExcel.getMatchingBorder(prevStyle && prevStyle.border && prevStyle.border.r, curStyle && curStyle.border && curStyle.border.l); if(color && color.w > 0) { calculateLineVer(color.c, j * lineStepX, i * stepY, (i + 1) * stepY); } //right color = curStyle && curStyle.border && curStyle.border.r; if(color && color.w > 0) { calculateLineVer(color.c, (j + 1) * lineStepX, i * stepY, (i + 1) * stepY); } //top prevStyle = (i - 1 >= 0) ? compiledStylesArr[i - 1][j] : null; color = AscCommonExcel.getMatchingBorder(prevStyle && prevStyle.border && prevStyle.border.b, curStyle && curStyle.border && curStyle.border.t); if(color && color.w > 0) { calculateLineHor(color.c, j * stepX, i * stepY, (j + 1) * stepX); } //bottom color = curStyle && curStyle.border && curStyle.border.b; if(color && color.w > 0) { calculateLineHor(color.c, j * stepX, (i + 1) * stepY, (j + 1) * stepX); } //marks color = (curStyle && curStyle.font && curStyle.font.c) || defaultColor; calculateLineHor(color, j * lineStepX + 3, (i + 1) * stepY - stepY / 2, (j + 1) * lineStepX - 2); } } }; WorkbookView.prototype.IsSelectionUse = function () { return !this.getWorksheet().getSelectionShape(); }; WorkbookView.prototype.GetSelectionRectsBounds = function () { if (this.getWorksheet().getSelectionShape()) return null; var ws = this.getWorksheet(); var range = ws.model.selectionRange.getLast(); var type = range.getType(); var l = ws.getCellLeft(range.c1, 3); var t = ws.getCellTop(range.r1, 3); var offset = ws.getCellsOffset(3); return { X: asc.c_oAscSelectionType.RangeRow === type ? -offset.left : l - offset.left, Y: asc.c_oAscSelectionType.RangeCol === type ? -offset.top : t - offset.top, W: asc.c_oAscSelectionType.RangeRow === type ? offset.left : ws.getCellLeft(range.c2, 3) - l + ws.getColumnWidth(range.c2, 3), H: asc.c_oAscSelectionType.RangeCol === type ? offset.top : ws.getCellTop(range.r2, 3) - t + ws.getRowHeight(range.r2, 3), T: type }; }; WorkbookView.prototype.GetCaptionSize = function() { var offset = this.getWorksheet().getCellsOffset(3); return { W: offset.left, H: offset.top }; }; WorkbookView.prototype.ConvertXYToLogic = function (x, y) { return this.getWorksheet().ConvertXYToLogic(x, y); }; WorkbookView.prototype.ConvertLogicToXY = function (xL, yL) { return this.getWorksheet().ConvertLogicToXY(xL, yL) }; WorkbookView.prototype.changeFormatTableInfo = function (tableName, optionType, val) { var ws = this.getWorksheet(); return ws.af_changeFormatTableInfo(tableName, optionType, val); }; WorkbookView.prototype.applyAutoCorrectOptions = function (val) { var api = window["Asc"]["editor"]; var prevProps; switch (val) { case Asc.c_oAscAutoCorrectOptions.UndoTableAutoExpansion: { prevProps = { props: this.autoCorrectStore.props, cell: this.autoCorrectStore.cell, wsId: this.autoCorrectStore.wsId }; api.asc_Undo(); this.autoCorrectStore = prevProps; this.autoCorrectStore.props[0] = Asc.c_oAscAutoCorrectOptions.RedoTableAutoExpansion; this.toggleAutoCorrectOptions(true); break; } case Asc.c_oAscAutoCorrectOptions.RedoTableAutoExpansion: { prevProps = { props: this.autoCorrectStore.props, cell: this.autoCorrectStore.cell, wsId: this.autoCorrectStore.wsId }; api.asc_Redo(); this.autoCorrectStore = prevProps; this.autoCorrectStore.props[0] = Asc.c_oAscAutoCorrectOptions.UndoTableAutoExpansion; this.toggleAutoCorrectOptions(true); break; } } return true; }; WorkbookView.prototype.toggleAutoCorrectOptions = function (isSwitch, val) { if (isSwitch) { if (val) { this.autoCorrectStore = val; var options = new Asc.asc_CAutoCorrectOptions(); options.asc_setOptions(this.autoCorrectStore.props); options.asc_setCellCoord( this.getWorksheet().getCellCoord(this.autoCorrectStore.cell.c1, this.autoCorrectStore.cell.r1)); this.handlers.trigger("asc_onToggleAutoCorrectOptions", options); } else if (this.autoCorrectStore) { if (this.autoCorrectStore.wsId === this.model.getActiveWs().getId()) { var options = new Asc.asc_CAutoCorrectOptions(); options.asc_setOptions(this.autoCorrectStore.props); options.asc_setCellCoord( this.getWorksheet().getCellCoord(this.autoCorrectStore.cell.c1, this.autoCorrectStore.cell.r1)); this.handlers.trigger("asc_onToggleAutoCorrectOptions", options); } else { this.handlers.trigger("asc_onToggleAutoCorrectOptions"); } } } else { if(this.autoCorrectStore) { if (val) { this.autoCorrectStore = null; } this.handlers.trigger("asc_onToggleAutoCorrectOptions"); } } }; WorkbookView.prototype.savePagePrintOptions = function (arrPagesPrint) { var t = this; var viewMode = !this.Api.canEdit(); if(!arrPagesPrint) { return; } var callback = function (isSuccess) { if (false === isSuccess) { return; } for(var i in arrPagesPrint) { var ws = t.getWorksheet(parseInt(i)); ws.savePageOptions(arrPagesPrint[i], viewMode); window["Asc"]["editor"]._onUpdateLayoutMenu(ws.model.Id); } }; var lockInfoArr = []; var lockInfo; for(var i in arrPagesPrint) { lockInfo = this.getWorksheet(parseInt(i)).getLayoutLockInfo(); lockInfoArr.push(lockInfo); } if(viewMode) { callback(); } else { this.collaborativeEditing.lock(lockInfoArr, callback); } }; WorkbookView.prototype.cleanCutData = function (bDrawSelection, bCleanBuffer) { if(this.cutIdSheet) { var activeWs = this.wsViews[this.wsActive]; var ws = this.getWorksheetById(this.cutIdSheet); if(bDrawSelection && activeWs && ws && activeWs.model.Id === ws.model.Id) { activeWs.cleanSelection(); } if(ws) { ws.cutRange = null; } this.cutIdSheet = null; if(bDrawSelection && activeWs && ws && activeWs.model.Id === ws.model.Id) { activeWs.updateSelection(); } //ms чистит буфер, если происходят какие-то изменения в документе с посвеченной областью вырезать //мы в данном случае не можем так делать, поскольку не можем прочесть информацию из буфера и убедиться, что //там именно тот вырезанный фрагмент. тем самым можем затереть какую-то важную информацию if(bCleanBuffer) { AscCommon.g_clipboardBase.ClearBuffer(); } } }; WorkbookView.prototype.updateGroupData = function () { this.getWorksheet()._updateGroups(true); this.getWorksheet()._updateGroups(null); }; WorkbookView.prototype.pasteSheet = function (base64, insertBefore, name, callback) { var t = this; var tempWorkbook = new AscCommonExcel.Workbook(); tempWorkbook.setCommonIndexObjectsFrom(this.model); var pasteProcessor = AscCommonExcel.g_clipboardExcel.pasteProcessor; var aPastedImages = pasteProcessor._readExcelBinary(base64.split('xslData;')[1], tempWorkbook, true); var pastedWs = tempWorkbook.aWorksheets[0]; var newFonts = {}; newFonts = tempWorkbook.generateFontMap2(); newFonts = pasteProcessor._convertFonts(newFonts); for (var i = 0; i < pastedWs.Drawings.length; i++) { pastedWs.Drawings[i].graphicObject.getAllFonts(newFonts); } var doCopy = function() { History.Create_NewPoint(); var renameParams = t.model.copyWorksheet(0, insertBefore, name, undefined, undefined, undefined, pastedWs); callback(renameParams); }; var api = window["Asc"]["editor"]; api._loadFonts(newFonts, function () { if (aPastedImages && aPastedImages.length) { pasteProcessor._loadImagesOnServer(aPastedImages, function () { doCopy(); }); } else { doCopy(); } }); }; //------------------------------------------------------------export--------------------------------------------------- window['AscCommonExcel'] = window['AscCommonExcel'] || {}; window["AscCommonExcel"].WorkbookView = WorkbookView; })(window);
cell/view/WorkbookView.js
/* * (c) Copyright Ascensio System SIA 2010-2019 * * This program is a free software product. You can redistribute it and/or * modify it under the terms of the GNU Affero General Public License (AGPL) * version 3 as published by the Free Software Foundation. In accordance with * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect * that Ascensio System SIA expressly excludes the warranty of non-infringement * of any third-party rights. * * This program is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html * * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha * street, Riga, Latvia, EU, LV-1050. * * The interactive user interfaces in modified source and object code versions * of the Program must display Appropriate Legal Notices, as required under * Section 5 of the GNU AGPL version 3. * * Pursuant to Section 7(b) of the License you must retain the original Product * logo when distributing the program. Pursuant to Section 7(e) we decline to * grant you any rights under trademark law for use of our trademarks. * * All the Product's GUI elements, including illustrations and icon sets, as * well as technical writing content are licensed under the terms of the * Creative Commons Attribution-ShareAlike 4.0 International. See the License * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode * */ "use strict"; (/** * @param {Window} window * @param {undefined} undefined */ function(window, undefined) { /* * Import * ----------------------------------------------------------------------------- */ var c_oAscFormatPainterState = AscCommon.c_oAscFormatPainterState; var AscBrowser = AscCommon.AscBrowser; var CColor = AscCommon.CColor; var cBoolLocal = AscCommon.cBoolLocal; var History = AscCommon.History; var asc = window["Asc"]; var asc_applyFunction = AscCommonExcel.applyFunction; var asc_round = asc.round; var asc_typeof = asc.typeOf; var asc_CMM = AscCommonExcel.asc_CMouseMoveData; var asc_CPrintPagesData = AscCommonExcel.CPrintPagesData; var c_oTargetType = AscCommonExcel.c_oTargetType; var c_oAscError = asc.c_oAscError; var c_oAscCleanOptions = asc.c_oAscCleanOptions; var c_oAscSelectionDialogType = asc.c_oAscSelectionDialogType; var c_oAscMouseMoveType = asc.c_oAscMouseMoveType; var c_oAscPopUpSelectorType = asc.c_oAscPopUpSelectorType; var c_oAscAsyncAction = asc.c_oAscAsyncAction; var c_oAscFontRenderingModeType = asc.c_oAscFontRenderingModeType; var c_oAscAsyncActionType = asc.c_oAscAsyncActionType; var g_clipboardExcel = AscCommonExcel.g_clipboardExcel; function WorkbookCommentsModel(handlers, aComments) { this.workbook = {handlers: handlers}; this.aComments = aComments; } WorkbookCommentsModel.prototype.getId = function() { return null; }; WorkbookCommentsModel.prototype.getMergedByCell = function() { return null; }; function WorksheetViewSettings() { this.header = { style: [// Header colors { // kHeaderDefault background: new CColor(241, 241, 241), border: new CColor(213, 213, 213), color: new CColor(54, 54, 54) }, { // kHeaderActive background: new CColor(193, 193, 193), border: new CColor(146, 146, 146), color: new CColor(54, 54, 54) }, { // kHeaderHighlighted background: new CColor(223, 223, 223), border: new CColor(175, 175, 175), color: new CColor(101, 106, 112) }, { // kHeaderSelected background: new CColor(170, 170, 170), border: new CColor(117, 119, 122), color: new CColor(54, 54, 54) }], cornerColor: new CColor(193, 193, 193) }; this.cells = { defaultState: { background: new CColor(255, 255, 255), border: new CColor(202, 202, 202) }, padding: -1 /*px horizontal padding*/ }; this.activeCellBorderColor = new CColor(72, 121, 92); this.activeCellBorderColor2 = new CColor(255, 255, 255, 1); this.findFillColor = new CColor(255, 238, 128, 1); // Цвет закрепленных областей this.frozenColor = new CColor(105, 119, 62, 1); // Число знаков для математической информации this.mathMaxDigCount = 9; var cnv = document.createElement("canvas"); cnv.width = 2; cnv.height = 2; var ctx = cnv.getContext("2d"); ctx.clearRect(0, 0, 2, 2); ctx.fillStyle = "#000"; ctx.fillRect(0, 0, 1, 1); ctx.fillRect(1, 1, 1, 1); this.ptrnLineDotted1 = ctx.createPattern(cnv, "repeat"); this.halfSelection = false; return this; } /** * Widget for displaying and editing Workbook object * ----------------------------------------------------------------------------- * @param {AscCommonExcel.Workbook} model Workbook * @param {AscCommonExcel.asc_CEventsController} controller Events controller * @param {HandlersList} handlers Events handlers for WorkbookView events * @param {Element} elem Container element * @param {Element} inputElem Input element for top line editor * @param {Object} Api * @param {CCollaborativeEditing} collaborativeEditing * @param {c_oAscFontRenderingModeType} fontRenderingMode * * @constructor * @memberOf Asc */ function WorkbookView(model, controller, handlers, elem, inputElem, Api, collaborativeEditing, fontRenderingMode) { this.defaults = { scroll: { widthPx: 14, heightPx: 14 }, worksheetView: new WorksheetViewSettings() }; this.model = model; this.enableKeyEvents = true; this.controller = controller; this.handlers = handlers; this.wsViewHandlers = null; this.element = elem; this.input = inputElem; this.Api = Api; this.collaborativeEditing = collaborativeEditing; this.lastSendInfoRange = null; this.oSelectionInfo = null; this.canUpdateAfterShiftUp = false; // Нужно ли обновлять информацию после отпускания Shift this.keepType = false; this.timerId = null; this.timerEnd = false; //----- declaration ----- this.isInit = false; this.canvas = undefined; this.canvasOverlay = undefined; this.canvasGraphic = undefined; this.canvasGraphicOverlay = undefined; this.wsActive = -1; this.wsMustDraw = false; // Означает, что мы выставили активный, но не отрисовали его this.wsViews = []; this.cellEditor = undefined; this.fontRenderingMode = null; this.lockDraw = false; // Lock отрисовки на некоторое время this.isCellEditMode = false; this.isShowComments = true; this.isShowSolved = true; this.formulasList = []; // Список всех формул this.lastFPos = -1; // Последняя позиция формулы this.lastFNameLength = ''; // Последний кусок формулы this.skipHelpSelector = false; // Пока true - не показываем окно подсказки // Константы для подстановке формулы (что не нужно добавлять скобки) this.arrExcludeFormulas = []; this.fReplaceCallback = null; // Callback для замены текста // Фонт, который выставлен в DrawingContext, он должен быть один на все DrawingContext-ы this.m_oFont = AscCommonExcel.g_oDefaultFormat.Font.clone(); // Теперь у нас 2 FontManager-а на весь документ + 1 для автофигур (а не на каждом листе свой) this.fmgrGraphics = []; // FontManager for draw (1 для обычного + 1 для поворотного текста) this.fmgrGraphics.push(new AscFonts.CFontManager({mode:"cell"})); // Для обычного this.fmgrGraphics.push(new AscFonts.CFontManager({mode:"cell"})); // Для поворотного this.fmgrGraphics.push(new AscFonts.CFontManager()); // Для автофигур this.fmgrGraphics.push(new AscFonts.CFontManager({mode:"cell"})); // Для измерений this.fmgrGraphics[0].Initialize(true); // IE memory enable this.fmgrGraphics[1].Initialize(true); // IE memory enable this.fmgrGraphics[2].Initialize(true); // IE memory enable this.fmgrGraphics[3].Initialize(true); // IE memory enable this.buffers = {}; this.drawingCtx = undefined; this.overlayCtx = undefined; this.drawingGraphicCtx = undefined; this.overlayGraphicCtx = undefined; this.shapeCtx = null; this.shapeOverlayCtx = null; this.mainGraphics = undefined; this.stringRender = undefined; this.trackOverlay = null; this.autoShapeTrack = null; this.stateFormatPainter = c_oAscFormatPainterState.kOff; this.rangeFormatPainter = null; this.selectionDialogType = c_oAscSelectionDialogType.None; this.copyActiveSheet = -1; // Комментарии для всего документа this.cellCommentator = null; // Флаг о подписке на эвенты о смене позиции документа (скролл) для меню this.isDocumentPlaceChangedEnabled = false; // Максимальная ширина числа из 0,1,2...,9, померенная в нормальном шрифте(дефалтовый для книги) в px(целое) // Ecma-376 Office Open XML Part 1, пункт 18.3.1.13 this.maxDigitWidth = 0; //----------------------- this.MobileTouchManager = null; this.defNameAllowCreate = true; this._init(fontRenderingMode); this.autoCorrectStore = null;//объект для хранения параметров иконки авторазвертывания таблиц this.cutIdSheet = null; return this; } WorkbookView.prototype._init = function(fontRenderingMode) { var self = this; // Init font managers rendering // Изначально мы инициализируем c_oAscFontRenderingModeType.hintingAndSubpixeling this.setFontRenderingMode(fontRenderingMode, /*isInit*/true); // add style var _head = document.getElementsByTagName('head')[0]; var style0 = document.createElement('style'); style0.type = 'text/css'; style0.innerHTML = ".block_elem { position:absolute;padding:0;margin:0; }"; _head.appendChild(style0); // create canvas if (null != this.element) { this.element.innerHTML = '<div id="ws-canvas-outer">\ <canvas id="ws-canvas"></canvas>\ <canvas id="ws-canvas-overlay"></canvas>\ <canvas id="ws-canvas-graphic"></canvas>\ <canvas id="ws-canvas-graphic-overlay"></canvas>\ <canvas id="id_target_cursor" class="block_elem" width="1" height="1"\ style="width:2px;height:13px;display:none;z-index:9;"></canvas>\ </div>'; this.canvas = document.getElementById("ws-canvas"); this.canvasOverlay = document.getElementById("ws-canvas-overlay"); this.canvasGraphic = document.getElementById("ws-canvas-graphic"); this.canvasGraphicOverlay = document.getElementById("ws-canvas-graphic-overlay"); } this.buffers.main = new asc.DrawingContext({ canvas: this.canvas, units: 0/*px*/, fmgrGraphics: this.fmgrGraphics, font: this.m_oFont }); this.buffers.overlay = new asc.DrawingContext({ canvas: this.canvasOverlay, units: 0/*px*/, fmgrGraphics: this.fmgrGraphics, font: this.m_oFont }); this.buffers.mainGraphic = new asc.DrawingContext({ canvas: this.canvasGraphic, units: 0/*px*/, fmgrGraphics: this.fmgrGraphics, font: this.m_oFont }); this.buffers.overlayGraphic = new asc.DrawingContext({ canvas: this.canvasGraphicOverlay, units: 0/*px*/, fmgrGraphics: this.fmgrGraphics, font: this.m_oFont }); this.drawingCtx = this.buffers.main; this.overlayCtx = this.buffers.overlay; this.drawingGraphicCtx = this.buffers.mainGraphic; this.overlayGraphicCtx = this.buffers.overlayGraphic; this.shapeCtx = new AscCommon.CGraphics(); this.shapeOverlayCtx = new AscCommon.CGraphics(); this.mainGraphics = new AscCommon.CGraphics(); this.trackOverlay = new AscCommon.COverlay(); this.trackOverlay.IsCellEditor = true; this.autoShapeTrack = new AscCommon.CAutoshapeTrack(); this.shapeCtx.m_oAutoShapesTrack = this.autoShapeTrack; this.shapeCtx.m_oFontManager = this.fmgrGraphics[2]; this.shapeOverlayCtx.m_oFontManager = this.fmgrGraphics[2]; this.mainGraphics.m_oFontManager = this.fmgrGraphics[0]; // Обновляем размеры (чуть ниже, потому что должны быть проинициализированы ctx) this._canResize(); this.stringRender = new AscCommonExcel.StringRender(this.buffers.main); // Мерить нужно только со 100% и один раз для всего документа this._calcMaxDigitWidth(); if (!window["NATIVE_EDITOR_ENJINE"]) { // initialize events controller this.controller.init(this, this.element, /*this.canvasOverlay*/ this.canvasGraphicOverlay, /*handlers*/{ "resize": function () { self.resize.apply(self, arguments); }, "initRowsCount": function () { self._onInitRowsCount.apply(self, arguments); }, "initColsCount": function () { self._onInitColsCount.apply(self, arguments); }, "scrollY": function () { self._onScrollY.apply(self, arguments); }, "scrollX": function () { self._onScrollX.apply(self, arguments); }, "changeSelection": function () { self._onChangeSelection.apply(self, arguments); }, "changeSelectionDone": function () { self._onChangeSelectionDone.apply(self, arguments); }, "changeSelectionRightClick": function () { self._onChangeSelectionRightClick.apply(self, arguments); }, "selectionActivePointChanged": function () { self._onSelectionActivePointChanged.apply(self, arguments); }, "updateWorksheet": function () { self._onUpdateWorksheet.apply(self, arguments); }, "resizeElement": function () { self._onResizeElement.apply(self, arguments); }, "resizeElementDone": function () { self._onResizeElementDone.apply(self, arguments); }, "changeFillHandle": function () { self._onChangeFillHandle.apply(self, arguments); }, "changeFillHandleDone": function () { self._onChangeFillHandleDone.apply(self, arguments); }, "moveRangeHandle": function () { self._onMoveRangeHandle.apply(self, arguments); }, "moveRangeHandleDone": function () { self._onMoveRangeHandleDone.apply(self, arguments); }, "moveResizeRangeHandle": function () { self._onMoveResizeRangeHandle.apply(self, arguments); }, "moveResizeRangeHandleDone": function () { self._onMoveResizeRangeHandleDone.apply(self, arguments); }, "editCell": function () { self._onEditCell.apply(self, arguments); }, "stopCellEditing": function () { return self._onStopCellEditing.apply(self, arguments); }, "getCellEditMode": function () { return self.isCellEditMode; }, "canEdit": function () { return self.Api.canEdit(); }, "isRestrictionComments": function () { return self.Api.isRestrictionComments(); }, "empty": function () { self._onEmpty.apply(self, arguments); }, "canEnterCellRange": function () { self.cellEditor.setFocus(false); var ret = self.cellEditor.canEnterCellRange(); ret ? self.cellEditor.activateCellRange() : true; return ret; }, "enterCellRange": function () { self.lockDraw = true; self.skipHelpSelector = true; self.cellEditor.setFocus(false); self.getWorksheet().enterCellRange(self.cellEditor); self.skipHelpSelector = false; self.lockDraw = false; }, "undo": function () { self.undo.apply(self, arguments); }, "redo": function () { self.redo.apply(self, arguments); }, "mouseDblClick": function () { self._onMouseDblClick.apply(self, arguments); }, "showNextPrevWorksheet": function () { self._onShowNextPrevWorksheet.apply(self, arguments); }, "setFontAttributes": function () { self._onSetFontAttributes.apply(self, arguments); }, "setCellFormat": function () { self._onSetCellFormat.apply(self, arguments); }, "selectColumnsByRange": function () { self._onSelectColumnsByRange.apply(self, arguments); }, "selectRowsByRange": function () { self._onSelectRowsByRange.apply(self, arguments); }, "save": function () { self.Api.asc_Save(); }, "showCellEditorCursor": function () { self._onShowCellEditorCursor.apply(self, arguments); }, "print": function () { self.Api.onPrint(); }, "addFunction": function () { self.insertFormulaInEditor.apply(self, arguments); }, "canvasClick": function () { self.enableKeyEventsHandler(true); }, "autoFiltersClick": function () { self._onAutoFiltersClick.apply(self, arguments); }, "commentCellClick": function () { self._onCommentCellClick.apply(self, arguments); }, "isGlobalLockEditCell": function () { return self.collaborativeEditing.getGlobalLockEditCell(); }, "updateSelectionName": function () { self._onUpdateSelectionName.apply(self, arguments); }, "stopFormatPainter": function () { self._onStopFormatPainter.apply(self, arguments); }, "groupRowClick": function () { return self._onGroupRowClick.apply(self, arguments); }, // Shapes "graphicObjectMouseDown": function () { self._onGraphicObjectMouseDown.apply(self, arguments); }, "graphicObjectMouseMove": function () { self._onGraphicObjectMouseMove.apply(self, arguments); }, "graphicObjectMouseUp": function () { self._onGraphicObjectMouseUp.apply(self, arguments); }, "graphicObjectMouseUpEx": function () { self._onGraphicObjectMouseUpEx.apply(self, arguments); }, "graphicObjectWindowKeyDown": function () { return self._onGraphicObjectWindowKeyDown.apply(self, arguments); }, "graphicObjectWindowKeyPress": function () { return self._onGraphicObjectWindowKeyPress.apply(self, arguments); }, "getGraphicsInfo": function () { return self._onGetGraphicsInfo.apply(self, arguments); }, "updateSelectionShape": function () { return self._onUpdateSelectionShape.apply(self, arguments); }, "canReceiveKeyPress": function () { return self.getWorksheet().objectRender.controller.canReceiveKeyPress(); }, "stopAddShape": function () { self.getWorksheet().objectRender.controller.checkEndAddShape(); }, // Frozen anchor "moveFrozenAnchorHandle": function () { self._onMoveFrozenAnchorHandle.apply(self, arguments); }, "moveFrozenAnchorHandleDone": function () { self._onMoveFrozenAnchorHandleDone.apply(self, arguments); }, // AutoComplete "showAutoComplete": function () { self.showAutoComplete.apply(self, arguments); }, "onContextMenu": function (event) { self.handlers.trigger("asc_onContextMenu", event); }, // DataValidation "onDataValidation": function () { if (self.oSelectionInfo && self.oSelectionInfo.dataValidation) { self.handlers.trigger("asc_onValidationListMenu", self.oSelectionInfo.dataValidation.getListValues(self.model.getActiveWs())); } }, // FormatPainter 'isFormatPainter': function () { return self.stateFormatPainter; }, //calculate 'calculate': function () { self.calculate.apply(self, arguments); }, 'changeFormatTableInfo': function () { var table = self.getSelectionInfo().formatTableInfo; return table && self.changeFormatTableInfo(table.tableName, Asc.c_oAscChangeTableStyleInfo.rowTotal, !table.lastRow); }, //special paste "hideSpecialPasteOptions": function () { self.handlers.trigger("hideSpecialPasteOptions"); } }); if (this.input && this.input.addEventListener) { this.input.addEventListener("focus", function () { self.input.isFocused = true; if (!self.Api.canEdit()) { return; } self._onStopFormatPainter(); self.controller.setStrictClose(true); self.cellEditor.callTopLineMouseup = true; if (!self.getCellEditMode() && !self.controller.isFillHandleMode) { self._onEditCell(/*isFocus*/true); } }, false); this.input.addEventListener('keydown', function (event) { if (self.isCellEditMode) { self.handlers.trigger('asc_onInputKeyDown', event); if (!event.defaultPrevented) { self.cellEditor._onWindowKeyDown(event, true); } } }, false); } this.Api.onKeyDown = function (event) { self.controller._onWindowKeyDown(event); if (self.isCellEditMode) { self.cellEditor._onWindowKeyDown(event, false); } }; this.Api.onKeyPress = function (event) { self.controller._onWindowKeyPress(event); if (self.isCellEditMode) { self.cellEditor._onWindowKeyPress(event); } }; this.Api.onKeyUp = function (event) { self.controller._onWindowKeyUp(event); if (self.isCellEditMode) { self.cellEditor._onWindowKeyUp(event); } }; this.Api.Begin_CompositeInput = function () { var oWSView = self.getWorksheet(); if (oWSView && oWSView.isSelectOnShape) { if (oWSView.objectRender) { oWSView.objectRender.Begin_CompositeInput(); } return; } if (!self.isCellEditMode) { self._onEditCell(false, true, undefined, true, function () { self.cellEditor.Begin_CompositeInput(); }); } else { self.cellEditor.Begin_CompositeInput(); } }; this.Api.Replace_CompositeText = function (arrCharCodes) { var oWSView = self.getWorksheet(); if(oWSView && oWSView.isSelectOnShape){ if(oWSView.objectRender){ oWSView.objectRender.Replace_CompositeText(arrCharCodes); } return; } if (self.isCellEditMode) { self.cellEditor.Replace_CompositeText(arrCharCodes); } }; this.Api.End_CompositeInput = function () { var oWSView = self.getWorksheet(); if(oWSView && oWSView.isSelectOnShape){ if(oWSView.objectRender){ oWSView.objectRender.End_CompositeInput(); } return; } if (self.isCellEditMode) { self.cellEditor.End_CompositeInput(); } }; this.Api.Set_CursorPosInCompositeText = function (nPos) { var oWSView = self.getWorksheet(); if(oWSView && oWSView.isSelectOnShape){ if(oWSView.objectRender){ oWSView.objectRender.Set_CursorPosInCompositeText(nPos); } return; } if (self.isCellEditMode) { self.cellEditor.Set_CursorPosInCompositeText(nPos); } }; this.Api.Get_CursorPosInCompositeText = function () { var res = 0; var oWSView = self.getWorksheet(); if(oWSView && oWSView.isSelectOnShape){ if(oWSView.objectRender){ res = oWSView.objectRender.Get_CursorPosInCompositeText(); } } else if (self.isCellEditMode) { res = self.cellEditor.Get_CursorPosInCompositeText(); } return res; }; this.Api.Get_MaxCursorPosInCompositeText = function () { var res = 0; var oWSView = self.getWorksheet(); if(oWSView && oWSView.isSelectOnShape){ if(oWSView.objectRender){ res = oWSView.objectRender.Get_CursorPosInCompositeText(); } } else if (self.isCellEditMode) { res = self.cellEditor.Get_MaxCursorPosInCompositeText(); } return res; }; this.Api.AddTextWithPr = function (familyName, arrCharCodes) { var ws = self.getWorksheet(); if (ws && ws.isSelectOnShape) { var textPr = new CTextPr(); textPr.RFonts = new CRFonts(); textPr.RFonts.Set_All(familyName, -1); ws.objectRender.controller.addTextWithPr(new AscCommon.CUnicodeStringEmulator(arrCharCodes), textPr, true); return; } if (!self.isCellEditMode) { self._onEditCell(undefined, undefined, undefined, false, function () { self.cellEditor.setTextStyle('fn', familyName); self.cellEditor._addCharCodes(arrCharCodes); }); } else { self.cellEditor.setTextStyle('fn', familyName); self.cellEditor._addCharCodes(arrCharCodes); } }; this.Api.beginInlineDropTarget = function (event) { if (!self.controller.isMoveRangeMode) { self.controller.isMoveRangeMode = true; self.getWorksheet().dragAndDropRange = new Asc.Range(0, 0, 0, 0); } self.controller._onMouseMove(event); }; this.Api.endInlineDropTarget = function (event) { self.controller.isMoveRangeMode = false; var ws = self.getWorksheet(); var newSelection = ws.activeMoveRange.clone(); ws._cleanSelectionMoveRange(); ws.dragAndDropRange = null; self._onSetSelection(newSelection); }; this.Api.isEnabledDropTarget = function () { return !self.isCellEditMode; }; AscCommon.InitBrowserInputContext(this.Api, "id_target_cursor"); this.model.dependencyFormulas.calcTree(); } this.cellEditor = new AscCommonExcel.CellEditor(this.element, this.input, this.fmgrGraphics, this.m_oFont, /*handlers*/{ "closed": function () { self._onCloseCellEditor.apply(self, arguments); }, "updated": function () { self.Api.checkLastWork(); self._onUpdateCellEditor.apply(self, arguments); }, "gotFocus": function (hasFocus) { self.controller.setFocus(!hasFocus); }, "updateFormulaEditMod": function () { self.controller.setFormulaEditMode.apply(self.controller, arguments); var ws = self.getWorksheet(); if (ws) { if (!self.lockDraw) { ws.cleanSelection(); } for (var i in self.wsViews) { self.wsViews[i].cleanFormulaRanges(); } // ws.cleanFormulaRanges(); ws.setFormulaEditMode.apply(ws, arguments); } }, "updateEditorState": function (state) { self.handlers.trigger("asc_onEditCell", state); }, "isGlobalLockEditCell": function () { return self.collaborativeEditing.getGlobalLockEditCell(); }, "updateFormulaEditModEnd": function () { if (!self.lockDraw) { self.getWorksheet().updateSelection(); } }, "newRange": function (range, ws) { if (!ws) { self.getWorksheet().addFormulaRange(range); } else { self.getWorksheet(self.model.getWorksheetIndexByName(ws)).addFormulaRange(range); } }, "existedRange": function (range, ws) { var editRangeSheet = ws ? self.model.getWorksheetIndexByName(ws) : self.copyActiveSheet; if (-1 === editRangeSheet || editRangeSheet === self.wsActive) { self.getWorksheet().activeFormulaRange(range); } else { self.getWorksheet(editRangeSheet).removeFormulaRange(range); self.getWorksheet().addFormulaRange(range); } }, "updateUndoRedoChanged": function (bCanUndo, bCanRedo) { self.handlers.trigger("asc_onCanUndoChanged", bCanUndo); self.handlers.trigger("asc_onCanRedoChanged", bCanRedo); }, "applyCloseEvent": function () { self.controller._onWindowKeyDown.apply(self.controller, arguments); }, "canEdit": function () { return self.Api.canEdit(); }, "getFormulaRanges": function () { return (self.cellFormulaEnterWSOpen || self.getWorksheet()).getFormulaRanges(); }, "getCellFormulaEnterWSOpen": function () { return self.cellFormulaEnterWSOpen; }, "getActiveWS": function () { return self.getWorksheet().model; }, "setStrictClose": function (val) { self.controller.setStrictClose(val); }, "updateEditorSelectionInfo": function (info) { self.handlers.trigger("asc_onEditorSelectionChanged", info); }, "onContextMenu": function (event) { self.handlers.trigger("asc_onContextMenu", event); }, "updatedEditableFunction": function (fName) { self.handlers.trigger("asc_onFormulaInfo", fName); } }, this.defaults.worksheetView.cells.padding); this.wsViewHandlers = new AscCommonExcel.asc_CHandlersList(/*handlers*/{ "canEdit": function () { return self.Api.canEdit(); }, "getViewMode": function () { return self.Api.getViewMode(); }, "isRestrictionComments": function () { return self.Api.isRestrictionComments(); }, "reinitializeScroll": function (type) { self._onScrollReinitialize(type); }, "selectionChanged": function () { self._onWSSelectionChanged(); }, "selectionNameChanged": function () { self._onSelectionNameChanged.apply(self, arguments); }, "selectionMathInfoChanged": function () { self._onSelectionMathInfoChanged.apply(self, arguments); }, 'onFilterInfo': function (countFilter, countRecords) { self.handlers.trigger("asc_onFilterInfo", countFilter, countRecords); }, "onErrorEvent": function (errorId, level) { self.handlers.trigger("asc_onError", errorId, level); }, "slowOperation": function (isStart) { (isStart ? self.Api.sync_StartAction : self.Api.sync_EndAction).call(self.Api, c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.SlowOperation); }, "setAutoFiltersDialog": function (arrVal) { self.handlers.trigger("asc_onSetAFDialog", arrVal); }, "selectionRangeChanged": function (val) { self.handlers.trigger("asc_onSelectionRangeChanged", val); }, "onRenameCellTextEnd": function (countFind, countReplace) { self.handlers.trigger("asc_onRenameCellTextEnd", countFind, countReplace); }, 'onStopFormatPainter': function () { self._onStopFormatPainter(); }, 'getRangeFormatPainter': function () { return self.rangeFormatPainter; }, "onDocumentPlaceChanged": function () { self._onDocumentPlaceChanged(); }, "updateSheetViewSettings": function () { self.handlers.trigger("asc_onUpdateSheetViewSettings"); }, "onScroll": function (d) { self.controller.scroll(d); }, "getLockDefNameManagerStatus": function () { return self.defNameAllowCreate; }, 'isActive': function () { return (-1 === self.copyActiveSheet || self.wsActive === self.copyActiveSheet); }, "getCellEditMode": function () { return self.isCellEditMode; }, "drawMobileSelection": function (color) { if (self.MobileTouchManager) { self.MobileTouchManager.CheckSelect(self.trackOverlay, color); } }, "showSpecialPasteOptions": function (val) { self.handlers.trigger("asc_onShowSpecialPasteOptions", val); if (!window['AscCommon'].g_specialPasteHelper.showSpecialPasteButton) { window['AscCommon'].g_specialPasteHelper.showSpecialPasteButton = true; } }, 'checkLastWork': function () { self.Api.checkLastWork(); }, "toggleAutoCorrectOptions": function (bIsShow, val) { self.toggleAutoCorrectOptions(bIsShow, val); }, "selectSearchingResults": function () { return self.Api.selectSearchingResults; }, "getMainGraphics": function () { return self.mainGraphics; }, "cleanCutData": function (bDrawSelection, bCleanBuffer) { self.cleanCutData(bDrawSelection, bCleanBuffer); } }); this.model.handlers.add("cleanCellCache", function(wsId, oRanges, skipHeight) { var ws = self.getWorksheetById(wsId, true); if (ws) { ws.updateRanges(oRanges, skipHeight); } }); this.model.handlers.add("changeWorksheetUpdate", function(wsId, val) { var ws = self.getWorksheetById(wsId); if (ws) { ws.changeWorksheet("update", val); } }); this.model.handlers.add("showWorksheet", function(wsId) { var wsModel = self.model.getWorksheetById(wsId), index; if (wsModel) { index = wsModel.getIndex(); self.showWorksheet(index, true); } }); this.model.handlers.add("setSelection", function() { self._onSetSelection.apply(self, arguments); }); this.model.handlers.add("getSelectionState", function() { return self._onGetSelectionState.apply(self); }); this.model.handlers.add("setSelectionState", function() { self._onSetSelectionState.apply(self, arguments); }); this.model.handlers.add("reInit", function() { self.reInit.apply(self, arguments); }); this.model.handlers.add("drawWS", function() { self.drawWS.apply(self, arguments); }); this.model.handlers.add("showDrawingObjects", function() { self.onShowDrawingObjects.apply(self, arguments); }); this.model.handlers.add("setCanUndo", function(bCanUndo) { self.handlers.trigger("asc_onCanUndoChanged", bCanUndo); }); this.model.handlers.add("setCanRedo", function(bCanRedo) { self.handlers.trigger("asc_onCanRedoChanged", bCanRedo); }); this.model.handlers.add("setDocumentModified", function(bIsModified) { self.Api.onUpdateDocumentModified(bIsModified); }); this.model.handlers.add("updateWorksheetByModel", function() { self.updateWorksheetByModel.apply(self, arguments); }); this.model.handlers.add("undoRedoAddRemoveRowCols", function(sheetId, type, range, bUndo) { if (true === bUndo) { if (AscCH.historyitem_Worksheet_AddRows === type) { self.collaborativeEditing.removeRowsRange(sheetId, range.clone(true)); self.collaborativeEditing.undoRows(sheetId, range.r2 - range.r1 + 1); } else if (AscCH.historyitem_Worksheet_RemoveRows === type) { self.collaborativeEditing.addRowsRange(sheetId, range.clone(true)); self.collaborativeEditing.undoRows(sheetId, range.r2 - range.r1 + 1); } else if (AscCH.historyitem_Worksheet_AddCols === type) { self.collaborativeEditing.removeColsRange(sheetId, range.clone(true)); self.collaborativeEditing.undoCols(sheetId, range.c2 - range.c1 + 1); } else if (AscCH.historyitem_Worksheet_RemoveCols === type) { self.collaborativeEditing.addColsRange(sheetId, range.clone(true)); self.collaborativeEditing.undoCols(sheetId, range.c2 - range.c1 + 1); } } else { if (AscCH.historyitem_Worksheet_AddRows === type) { self.collaborativeEditing.addRowsRange(sheetId, range.clone(true)); self.collaborativeEditing.addRows(sheetId, range.r1, range.r2 - range.r1 + 1); } else if (AscCH.historyitem_Worksheet_RemoveRows === type) { self.collaborativeEditing.removeRowsRange(sheetId, range.clone(true)); self.collaborativeEditing.removeRows(sheetId, range.r1, range.r2 - range.r1 + 1); } else if (AscCH.historyitem_Worksheet_AddCols === type) { self.collaborativeEditing.addColsRange(sheetId, range.clone(true)); self.collaborativeEditing.addCols(sheetId, range.c1, range.c2 - range.c1 + 1); } else if (AscCH.historyitem_Worksheet_RemoveCols === type) { self.collaborativeEditing.removeColsRange(sheetId, range.clone(true)); self.collaborativeEditing.removeCols(sheetId, range.c1, range.c2 - range.c1 + 1); } } }); this.model.handlers.add("undoRedoHideSheet", function(sheetId) { self.showWorksheet(sheetId); // Посылаем callback об изменении списка листов self.Api.sheetsChanged(); }); this.model.handlers.add("updateSelection", function () { if (!self.lockDraw) { self.getWorksheet().updateSelection(); } }); this.handlers.add("asc_onLockDefNameManager", function(reason) { self.defNameAllowCreate = !(reason == Asc.c_oAscDefinedNameReason.LockDefNameManager); }); this.handlers.add('addComment', function (id, data) { self._onWSSelectionChanged(); self.handlers.trigger('asc_onAddComment', id, data); }); this.handlers.add('removeComment', function (id) { self._onWSSelectionChanged(); self.handlers.trigger('asc_onRemoveComment', id); }); this.handlers.add('hiddenComments', function () { return !self.isShowComments; }); this.handlers.add('showSolved', function () { return self.isShowSolved; }); this.model.handlers.add("hideSpecialPasteOptions", function() { self.handlers.trigger("asc_onHideSpecialPasteOptions"); }); this.model.handlers.add("toggleAutoCorrectOptions", function(bIsShow, val) { self.toggleAutoCorrectOptions(bIsShow, val); }); this.model.handlers.add("cleanCutData", function(bDrawSelection, bCleanBuffer) { self.cleanCutData(bDrawSelection, bCleanBuffer); }); this.model.handlers.add("updateGroupData", function() { self.updateGroupData(); }); this.cellCommentator = new AscCommonExcel.CCellCommentator({ model: new WorkbookCommentsModel(this.handlers, this.model.aComments), collaborativeEditing: this.collaborativeEditing, draw: function() { }, handlers: { trigger: function() { return false; } } }); if (0 < this.model.aComments.length) { this.handlers.trigger("asc_onAddComments", this.model.aComments); } this.initFormulasList(); this.fReplaceCallback = function() { self._replaceCellTextCallback.apply(self, arguments); }; return this; }; WorkbookView.prototype.destroy = function() { this.controller.destroy(); this.cellEditor.destroy(); return this; }; WorkbookView.prototype._createWorksheetView = function(wsModel) { return new AscCommonExcel.WorksheetView(this, wsModel, this.wsViewHandlers, this.buffers, this.stringRender, this.maxDigitWidth, this.collaborativeEditing, this.defaults.worksheetView); }; WorkbookView.prototype._onSelectionNameChanged = function(name) { this.handlers.trigger("asc_onSelectionNameChanged", name); }; WorkbookView.prototype._onSelectionMathInfoChanged = function(info) { this.handlers.trigger("asc_onSelectionMathChanged", info); }; // Проверяет, сменили ли мы диапазон (для того, чтобы не отправлять одинаковую информацию о диапазоне) WorkbookView.prototype._isEqualRange = function(range, isSelectOnShape) { if (null === this.lastSendInfoRange) { return false; } return this.lastSendInfoRange.isEqual(range) && this.lastSendInfoRangeIsSelectOnShape === isSelectOnShape; }; WorkbookView.prototype._updateSelectionInfo = function () { var ws = this.cellFormulaEnterWSOpen ? this.cellFormulaEnterWSOpen : this.getWorksheet(); this.oSelectionInfo = ws.getSelectionInfo(); this.lastSendInfoRange = ws.model.selectionRange.clone(); this.lastSendInfoRangeIsSelectOnShape = ws.getSelectionShape(); }; WorkbookView.prototype._onWSSelectionChanged = function(isSaving) { this._updateSelectionInfo(); // При редактировании ячейки не нужно пересылать изменения if (this.input && false === this.getCellEditMode() && c_oAscSelectionDialogType.None === this.selectionDialogType) { // Сами запретим заходить в строку формул, когда выделен shape if (this.lastSendInfoRangeIsSelectOnShape) { this.input.disabled = true; this.input.value = ''; } else { this.input.disabled = false; this.input.value = this.oSelectionInfo.text; } } this.handlers.trigger("asc_onSelectionChanged", this.oSelectionInfo); this.handlers.trigger("asc_onSelectionEnd"); this._onInputMessage(); if (!isSaving) { this.Api.cleanSpelling(); } }; WorkbookView.prototype._onInputMessage = function () { var title = null, message = null; var dataValidation = this.oSelectionInfo && this.oSelectionInfo.dataValidation; if (dataValidation && dataValidation.showInputMessage && !this.model.getActiveWs().getDisablePrompts()) { title = dataValidation.promptTitle; message = dataValidation.promt; } this.handlers.trigger("asc_onInputMessage", title, message); }; WorkbookView.prototype._onScrollReinitialize = function (type) { if (window["NATIVE_EDITOR_ENJINE"] || !type) { return; } var ws = this.getWorksheet(); if (AscCommonExcel.c_oAscScrollType.ScrollHorizontal & type) { this.controller.reinitScrollX(ws.getFirstVisibleCol(true), ws.getHorizontalScrollRange(), ws.getHorizontalScrollMax()); } if (AscCommonExcel.c_oAscScrollType.ScrollVertical & type) { this.controller.reinitScrollY(ws.getFirstVisibleRow(true), ws.getVerticalScrollRange(), ws.getVerticalScrollMax()); } if (this.Api.isMobileVersion) { this.MobileTouchManager.Resize(); } }; WorkbookView.prototype._onInitRowsCount = function () { var ws = this.getWorksheet(); if (ws._initRowsCount()) { this._onScrollReinitialize(AscCommonExcel.c_oAscScrollType.ScrollVertical); } }; WorkbookView.prototype._onInitColsCount = function () { var ws = this.getWorksheet(); if (ws._initColsCount()) { this._onScrollReinitialize(AscCommonExcel.c_oAscScrollType.ScrollHorizontal); } }; WorkbookView.prototype._onScrollY = function(pos, initRowsCount) { var ws = this.getWorksheet(); var delta = asc_round(pos - ws.getFirstVisibleRow(true)); if (delta !== 0) { ws.scrollVertical(delta, this.cellEditor, initRowsCount); } }; WorkbookView.prototype._onScrollX = function(pos, initColsCount) { var ws = this.getWorksheet(); var delta = asc_round(pos - ws.getFirstVisibleCol(true)); if (delta !== 0) { ws.scrollHorizontal(delta, this.cellEditor, initColsCount); } }; WorkbookView.prototype._onSetSelection = function(range) { var ws = this.getWorksheet(); ws._endSelectionShape(); ws.setSelection(range); }; WorkbookView.prototype._onGetSelectionState = function() { var res = null; var ws = this.getWorksheet(null, true); if (ws && AscCommon.isRealObject(ws.objectRender) && AscCommon.isRealObject(ws.objectRender.controller)) { res = ws.objectRender.controller.getSelectionState(); } return (res && res[0] && res[0].focus) ? res : null; }; WorkbookView.prototype._onSetSelectionState = function(state) { if (null !== state) { var ws = this.getWorksheetById(state[0].worksheetId); if (ws && ws.objectRender && ws.objectRender.controller) { ws.objectRender.controller.setSelectionState(state); ws.setSelectionShape(true); ws._scrollToRange(ws.objectRender.getSelectedDrawingsRange()); ws.objectRender.showDrawingObjectsEx(true); ws.objectRender.controller.updateOverlay(); ws.objectRender.controller.updateSelectionState(); } // Селектим после выставления состояния } }; WorkbookView.prototype._onChangeSelection = function (isStartPoint, dc, dr, isCoord, isCtrl, callback) { var ws = this.getWorksheet(); var t = this; var d = isStartPoint ? ws.changeSelectionStartPoint(dc, dr, isCoord, isCtrl) : ws.changeSelectionEndPoint(dc, dr, isCoord, isCoord && this.keepType); if (!isCoord && !isStartPoint) { // Выделение с зажатым shift this.canUpdateAfterShiftUp = true; } this.keepType = isCoord; if (isCoord && !this.timerEnd && this.timerId === null) { this.timerId = setTimeout(function () { var arrClose = []; arrClose.push(new asc_CMM({type: c_oAscMouseMoveType.None})); t.handlers.trigger("asc_onMouseMove", arrClose); t._onUpdateCursor(AscCommonExcel.kCurCells); t.timerId = null; t.timerEnd = true; },1000); } asc_applyFunction(callback, d); }; // Окончание выделения WorkbookView.prototype._onChangeSelectionDone = function(x, y, event) { if (this.timerId !== null) { clearTimeout(this.timerId); this.timerId = null; } this.keepType = false; if (c_oAscSelectionDialogType.None !== this.selectionDialogType) { return; } var ws = this.getWorksheet(); ws.changeSelectionDone(); this._onSelectionNameChanged(ws.getSelectionName(/*bRangeText*/false)); // Проверим, нужно ли отсылать информацию о ячейке var ar = ws.model.selectionRange.getLast(); var isSelectOnShape = ws.getSelectionShape(); if (!this._isEqualRange(ws.model.selectionRange, isSelectOnShape)) { this._onWSSelectionChanged(); this._onSelectionMathInfoChanged(ws.getSelectionMathInfo()); } // Нужно очистить поиск this.model.cleanFindResults(); var ct = ws.getCursorTypeFromXY(x, y); if (c_oTargetType.Hyperlink === ct.target && !this.controller.isFormulaEditMode) { // Проверим замерженность var isHyperlinkClick = false; if(isSelectOnShape) { var button = 0; if(event) { button = AscCommon.getMouseButton(event); } if(button === 0) { isHyperlinkClick = true; } } else if(ar.isOneCell()) { isHyperlinkClick = true; } else { var mergedRange = ws.model.getMergedByCell(ar.r1, ar.c1); if (mergedRange && ar.isEqual(mergedRange)) { isHyperlinkClick = true; } } if (isHyperlinkClick && !this.timerEnd) { if (false === ct.hyperlink.hyperlinkModel.getVisited() && !isSelectOnShape) { ct.hyperlink.hyperlinkModel.setVisited(true); if (ct.hyperlink.hyperlinkModel.Ref) { ws._updateRange(ct.hyperlink.hyperlinkModel.Ref.getBBox0()); ws.draw(); } } switch (ct.hyperlink.asc_getType()) { case Asc.c_oAscHyperlinkType.WebLink: this.handlers.trigger("asc_onHyperlinkClick", ct.hyperlink.asc_getHyperlinkUrl()); break; case Asc.c_oAscHyperlinkType.RangeLink: // ToDo надо поправить отрисовку комментария для данной ячейки (с которой уходим) this.handlers.trigger("asc_onHideComment"); this.Api._asc_setWorksheetRange(ct.hyperlink); break; } } } this.timerEnd = false; }; // Обработка нажатия правой кнопки мыши WorkbookView.prototype._onChangeSelectionRightClick = function(dc, dr, target) { var ws = this.getWorksheet(); ws.changeSelectionStartPointRightClick(dc, dr, target); }; // Обработка движения в выделенной области WorkbookView.prototype._onSelectionActivePointChanged = function(dc, dr, callback) { var ws = this.getWorksheet(); var d = ws.changeSelectionActivePoint(dc, dr); asc_applyFunction(callback, d); }; WorkbookView.prototype._onUpdateWorksheet = function(x, y, ctrlKey, callback) { var ws = this.getWorksheet(), ct = undefined; var arrMouseMoveObjects = []; // Теперь это массив из объектов, над которыми курсор var t = this; //ToDo: включить определение target, если находимся в режиме редактирования ячейки. if (x === undefined && y === undefined) { ws.cleanHighlightedHeaders(); if (this.timerId === null) { this.timerId = setTimeout(function () { var arrClose = []; arrClose.push(new asc_CMM({type: c_oAscMouseMoveType.None})); t.handlers.trigger("asc_onMouseMove", arrClose); t.timerId = null; }, 1000); } } else { ct = ws.getCursorTypeFromXY(x, y); ct.coordX = x; ct.coordY = y; if (this.timerId !== null) { clearTimeout(this.timerId); this.timerId = null; } // Отправление эвента об удалении всего листа (именно удалении, т.к. если просто залочен, то не рисуем рамку вокруг) if (undefined !== ct.userIdAllSheet) { arrMouseMoveObjects.push(new asc_CMM({ type: c_oAscMouseMoveType.LockedObject, x: AscCommon.AscBrowser.convertToRetinaValue(ct.lockAllPosLeft), y: AscCommon.AscBrowser.convertToRetinaValue(ct.lockAllPosTop), userId: ct.userIdAllSheet, lockedObjectType: Asc.c_oAscMouseMoveLockedObjectType.Sheet })); } else { // Отправление эвента о залоченности свойств всего листа (только если не удален весь лист) if (undefined !== ct.userIdAllProps) { arrMouseMoveObjects.push(new asc_CMM({ type: c_oAscMouseMoveType.LockedObject, x: AscCommon.AscBrowser.convertToRetinaValue(ct.lockAllPosLeft), y: AscCommon.AscBrowser.convertToRetinaValue(ct.lockAllPosTop), userId: ct.userIdAllProps, lockedObjectType: Asc.c_oAscMouseMoveLockedObjectType.TableProperties })); } } // Отправление эвента о наведении на залоченный объект if (undefined !== ct.userId) { arrMouseMoveObjects.push(new asc_CMM({ type: c_oAscMouseMoveType.LockedObject, x: AscCommon.AscBrowser.convertToRetinaValue(ct.lockRangePosLeft), y: AscCommon.AscBrowser.convertToRetinaValue(ct.lockRangePosTop), userId: ct.userId, lockedObjectType: Asc.c_oAscMouseMoveLockedObjectType.Range })); } // Проверяем комментарии ячейки if (ct.commentIndexes) { arrMouseMoveObjects.push(new asc_CMM({ type: c_oAscMouseMoveType.Comment, x: ct.commentCoords.dLeftPX, reverseX: ct.commentCoords.dReverseLeftPX, y: ct.commentCoords.dTopPX, aCommentIndexes: ct.commentIndexes })); } // Проверяем гиперссылку if (ct.target === c_oTargetType.Hyperlink) { if (!ctrlKey) { arrMouseMoveObjects.push(new asc_CMM({ type: c_oAscMouseMoveType.Hyperlink, x: AscCommon.AscBrowser.convertToRetinaValue(x), y: AscCommon.AscBrowser.convertToRetinaValue(y), hyperlink: ct.hyperlink })); } else { ct.cursor = AscCommonExcel.kCurCells; } } // проверяем фильтр if (ct.target === c_oTargetType.FilterObject) { if (ct.isPivot) { //необходимо сгенерировать объект AutoFiltersOptions } else { var filterObj = ws.af_setDialogProp(ct.idFilter, true); if(filterObj) { arrMouseMoveObjects.push(new asc_CMM({ type: c_oAscMouseMoveType.Filter, x: AscCommon.AscBrowser.convertToRetinaValue(x), y: AscCommon.AscBrowser.convertToRetinaValue(y), filter: filterObj })); } } } /* Проверяем, может мы на никаком объекте (такая схема оказалась приемлимой * для отдела разработки приложений) */ if (0 === arrMouseMoveObjects.length) { // Отправляем эвент, что мы ни на какой области arrMouseMoveObjects.push(new asc_CMM({type: c_oAscMouseMoveType.None})); } // Отсылаем эвент с объектами this.handlers.trigger("asc_onMouseMove", arrMouseMoveObjects); if (ct.target === c_oTargetType.MoveRange && ctrlKey && ct.cursor === "move") { ct.cursor = "copy"; } this._onUpdateCursor(ct.cursor); if (ct.target === c_oTargetType.ColumnHeader || ct.target === c_oTargetType.RowHeader) { ws.drawHighlightedHeaders(ct.col, ct.row); } else { ws.cleanHighlightedHeaders(); } } asc_applyFunction(callback, ct); }; WorkbookView.prototype._onUpdateCursor = function (cursor) { var newHtmlCursor = AscCommon.g_oHtmlCursor.value(cursor); if (this.element.style.cursor !== newHtmlCursor) { this.element.style.cursor = newHtmlCursor; } }; WorkbookView.prototype._onResizeElement = function(target, x, y) { var arrMouseMoveObjects = []; if (target.target === c_oTargetType.ColumnResize) { arrMouseMoveObjects.push(this.getWorksheet().drawColumnGuides(target.col, x, y, target.mouseX)); } else if (target.target === c_oTargetType.RowResize) { arrMouseMoveObjects.push(this.getWorksheet().drawRowGuides(target.row, x, y, target.mouseY)); } /* Проверяем, может мы на никаком объекте (такая схема оказалась приемлимой * для отдела разработки приложений) */ if (0 === arrMouseMoveObjects.length) { // Отправляем эвент, что мы ни на какой области arrMouseMoveObjects.push(new asc_CMM({type: c_oAscMouseMoveType.None})); } // Отсылаем эвент с объектами this.handlers.trigger("asc_onMouseMove", arrMouseMoveObjects); }; WorkbookView.prototype._onResizeElementDone = function(target, x, y, isResizeModeMove) { var ws = this.getWorksheet(); if (isResizeModeMove) { if (target.target === c_oTargetType.ColumnResize) { ws.changeColumnWidth(target.col, x, target.mouseX); } else if (target.target === c_oTargetType.RowResize) { ws.changeRowHeight(target.row, y, target.mouseY); } window['AscCommon'].g_specialPasteHelper.SpecialPasteButton_Update_Position(); this._onDocumentPlaceChanged(); } ws.draw(); // Отсылаем окончание смены размеров (в FF не срабатывало обычное движение) this.handlers.trigger("asc_onMouseMove", [new asc_CMM({type: c_oAscMouseMoveType.None})]); }; // Обработка автозаполнения WorkbookView.prototype._onChangeFillHandle = function(x, y, callback, tableIndex) { var ws = this.getWorksheet(); var d = ws.changeSelectionFillHandle(x, y, tableIndex); asc_applyFunction(callback, d); }; // Обработка окончания автозаполнения WorkbookView.prototype._onChangeFillHandleDone = function(x, y, ctrlPress) { var ws = this.getWorksheet(); ws.applyFillHandle(x, y, ctrlPress); }; // Обработка перемещения диапазона WorkbookView.prototype._onMoveRangeHandle = function(x, y, callback) { var ws = this.getWorksheet(); var d = ws.changeSelectionMoveRangeHandle(x, y); asc_applyFunction(callback, d); }; // Обработка окончания перемещения диапазона WorkbookView.prototype._onMoveRangeHandleDone = function(ctrlKey) { var ws = this.getWorksheet(); ws.applyMoveRangeHandle(ctrlKey); }; WorkbookView.prototype._onMoveResizeRangeHandle = function(x, y, target, callback) { var ws = this.getWorksheet(); var d = ws.changeSelectionMoveResizeRangeHandle(x, y, target, this.cellEditor); asc_applyFunction(callback, d); }; WorkbookView.prototype._onMoveResizeRangeHandleDone = function(target) { var ws = this.getWorksheet(); ws.applyMoveResizeRangeHandle(target); }; // Frozen anchor WorkbookView.prototype._onMoveFrozenAnchorHandle = function(x, y, target) { var ws = this.getWorksheet(); ws.drawFrozenGuides(x, y, target); }; WorkbookView.prototype._onMoveFrozenAnchorHandleDone = function(x, y, target) { // Закрепляем область var ws = this.getWorksheet(); ws.applyFrozenAnchor(x, y, target); }; WorkbookView.prototype.showAutoComplete = function() { var ws = this.getWorksheet(); var arrValues = ws.getCellAutoCompleteValues(ws.model.selectionRange.activeCell); this.handlers.trigger('asc_onEntriesListMenu', arrValues); }; WorkbookView.prototype._onAutoFiltersClick = function(idFilter) { this.getWorksheet().af_setDialogProp(idFilter); }; WorkbookView.prototype._onGroupRowClick = function(x, y, target, type) { return this.getWorksheet().groupRowClick(x, y, target, type); }; WorkbookView.prototype._onCommentCellClick = function(x, y) { this.getWorksheet().cellCommentator.showCommentByXY(x, y); }; WorkbookView.prototype._onUpdateSelectionName = function (forcibly) { if (this.canUpdateAfterShiftUp || forcibly) { this.canUpdateAfterShiftUp = false; var ws = this.getWorksheet(); this._onSelectionNameChanged(ws.getSelectionName(/*bRangeText*/false)); } }; WorkbookView.prototype._onStopFormatPainter = function() { if (this.stateFormatPainter) { this.formatPainter(c_oAscFormatPainterState.kOff); } }; // Shapes WorkbookView.prototype._onGraphicObjectMouseDown = function(e, x, y) { var ws = this.getWorksheet(); ws.objectRender.graphicObjectMouseDown(e, x, y); }; WorkbookView.prototype._onGraphicObjectMouseMove = function(e, x, y) { var ws = this.getWorksheet(); ws.objectRender.graphicObjectMouseMove(e, x, y); }; WorkbookView.prototype._onGraphicObjectMouseUp = function(e, x, y) { var ws = this.getWorksheet(); ws.objectRender.graphicObjectMouseUp(e, x, y); }; WorkbookView.prototype._onGraphicObjectMouseUpEx = function(e, x, y) { //var ws = this.getWorksheet(); //ws.objectRender.calculateCell(x, y); }; WorkbookView.prototype._onGraphicObjectWindowKeyDown = function(e) { var objectRender = this.getWorksheet().objectRender; return (0 < objectRender.getSelectedGraphicObjects().length) ? objectRender.graphicObjectKeyDown(e) : false; }; WorkbookView.prototype._onGraphicObjectWindowKeyPress = function(e) { var objectRender = this.getWorksheet().objectRender; return (0 < objectRender.getSelectedGraphicObjects().length) ? objectRender.graphicObjectKeyPress(e) : false; }; WorkbookView.prototype._onGetGraphicsInfo = function(x, y) { var ws = this.getWorksheet(); return ws.objectRender.checkCursorDrawingObject(x, y); }; WorkbookView.prototype._onUpdateSelectionShape = function(isSelectOnShape) { var ws = this.getWorksheet(); return ws.setSelectionShape(isSelectOnShape); }; // Double click WorkbookView.prototype._onMouseDblClick = function(x, y, isHideCursor, callback) { var ws = this.getWorksheet(); var ct = ws.getCursorTypeFromXY(x, y); if (ct.target === c_oTargetType.ColumnResize || ct.target === c_oTargetType.RowResize) { if (ct.target === c_oTargetType.ColumnResize) { ws.autoFitColumnsWidth(ct.col); } else { ws.autoFitRowHeight(ct.row, ct.row); } asc_applyFunction(callback); } else { if (ct.col >= 0 && ct.row >= 0) { this.controller.setStrictClose(!ws._isCellNullText(ct.col, ct.row)); } // In view mode or click on column | row | all | frozenMove | drawing object do not process if (!this.Api.canEdit() || c_oTargetType.ColumnHeader === ct.target || c_oTargetType.RowHeader === ct.target || c_oTargetType.Corner === ct.target || c_oTargetType.FrozenAnchorH === ct.target || c_oTargetType.FrozenAnchorV === ct.target || ws.objectRender.checkCursorDrawingObject(x, y)) { asc_applyFunction(callback); return; } // При dbl клике фокус выставляем в зависимости от наличия текста в ячейке this._onEditCell(/*isFocus*/undefined, /*isClearCell*/undefined, /*isHideCursor*/isHideCursor, /*isQuickInput*/false); } }; WorkbookView.prototype._onWindowMouseUpExternal = function (event, x, y) { this.controller._onWindowMouseUpExternal(event, x, y); if (this.isCellEditMode) { this.cellEditor._onWindowMouseUp(event, x, y); } }; WorkbookView.prototype._onEditCell = function(isFocus, isClearCell, isHideCursor, isQuickInput, callback) { var t = this; // Проверка глобального лока if (this.collaborativeEditing.getGlobalLock() || this.controller.isResizeMode) { return; } var ws = t.getWorksheet(); var activeCellRange = ws.getActiveCell(0, 0, false); var selectionRange = ws.model.selectionRange.clone(); var activeWsModel = this.model.getActiveWs(); if (activeWsModel.inPivotTable(activeCellRange)) { this.handlers.trigger("asc_onError", c_oAscError.ID.LockedCellPivot, c_oAscError.Level.NoCritical); return; } var editFunction = function() { t.setCellEditMode(true); t.hideSpecialPasteButton(); ws.openCellEditor(t.cellEditor, /*cursorPos*/undefined, isFocus, isClearCell, /*isHideCursor*/isHideCursor, /*isQuickInput*/isQuickInput, selectionRange); t.input.disabled = false; t.Api.cleanSpelling(true); // Эвент на обновление состояния редактора t.cellEditor._updateEditorState(); asc_applyFunction(callback, true); }; var editLockCallback = function(res) { if (!res) { t.setCellEditMode(false); t.controller.setStrictClose(false); t.controller.setFormulaEditMode(false); ws.setFormulaEditMode(false); t.input.disabled = true; // Выключаем lock для редактирования ячейки t.collaborativeEditing.onStopEditCell(); t.cellEditor.close(false); t._onWSSelectionChanged(); } }; // Стартуем редактировать ячейку activeCellRange = ws.expandActiveCellByFormulaArray(activeCellRange); if (ws._isLockedCells(activeCellRange, /*subType*/null, editLockCallback)) { editFunction(); } }; WorkbookView.prototype._onStopCellEditing = function(cancel) { return this.cellEditor.close(!cancel); }; WorkbookView.prototype._onCloseCellEditor = function() { var isCellEditMode = this.getCellEditMode(); this.setCellEditMode(false); this.controller.setStrictClose(false); this.controller.setFormulaEditMode(false); var ws = this.getWorksheet(), index; if( this.cellFormulaEnterWSOpen ){ index = this.cellFormulaEnterWSOpen.model.getIndex(); this.cellFormulaEnterWSOpen = null; if( index !== ws.model.getIndex() ){ this.showWorksheet(index); } ws = this.getWorksheet(index); } ws.cleanSelection(); for (var i in this.wsViews) { this.wsViews[i].setFormulaEditMode(false); this.wsViews[i].cleanFormulaRanges(); } ws.updateSelectionWithSparklines(); if (isCellEditMode) { this.handlers.trigger("asc_onEditCell", Asc.c_oAscCellEditorState.editEnd); } // Обновляем состояние Undo/Redo if (!this.cellEditor.getMenuEditorMode()) { History._sendCanUndoRedo(); } // Обновляем состояние информации this._onWSSelectionChanged(); // Закрываем подбор формулы if (-1 !== this.lastFPos) { this.handlers.trigger('asc_onFormulaCompleteMenu', null); this.lastFPos = -1; this.lastFNameLength = 0; } this.handlers.trigger('asc_onFormulaInfo', null); }; WorkbookView.prototype._onEmpty = function() { this.getWorksheet().emptySelection(c_oAscCleanOptions.Text); }; WorkbookView.prototype._onShowNextPrevWorksheet = function(direction) { // Колличество листов var countWorksheets = this.model.getWorksheetCount(); // Покажем следующий лист или предыдущий (если больше нет) var i = this.wsActive + direction, ws; while (i !== this.wsActive) { if (0 > i) { i = countWorksheets - 1; } else if (i >= countWorksheets) { i = 0; } ws = this.model.getWorksheet(i); if (!ws.getHidden()) { this.showWorksheet(i); return true; } i += direction; } return false; }; WorkbookView.prototype._onSetFontAttributes = function(prop) { var val; var selectionInfo = this.getWorksheet().getSelectionInfo().asc_getFont(); switch (prop) { case "b": val = !(selectionInfo.asc_getBold()); break; case "i": val = !(selectionInfo.asc_getItalic()); break; case "u": // ToDo для двойного подчеркивания нужно будет немного переделать схему val = !(selectionInfo.asc_getUnderline()); val = val ? Asc.EUnderline.underlineSingle : Asc.EUnderline.underlineNone; break; case "s": val = !(selectionInfo.asc_getStrikeout()); break; } return this.setFontAttributes(prop, val); }; WorkbookView.prototype._onSetCellFormat = function (prop) { var info = new Asc.asc_CFormatCellsInfo(); info.asc_setSymbol(AscCommon.g_oDefaultCultureInfo.LCID); info.asc_setType(Asc.c_oAscNumFormatType.None); var formats = AscCommon.getFormatCells(info); this.setCellFormat(formats[prop]); }; WorkbookView.prototype._onSelectColumnsByRange = function() { this.getWorksheet()._selectColumnsByRange(); }; WorkbookView.prototype._onSelectRowsByRange = function() { this.getWorksheet()._selectRowsByRange(); }; WorkbookView.prototype._onShowCellEditorCursor = function() { // Показываем курсор if (this.getCellEditMode()) { this.cellEditor.showCursor(); } }; WorkbookView.prototype._onDocumentPlaceChanged = function() { if (this.isDocumentPlaceChangedEnabled) { this.handlers.trigger("asc_onDocumentPlaceChanged"); } }; WorkbookView.prototype.getCellStyles = function(width, height) { return AscCommonExcel.generateStyles(width, height, this.model.CellStyles, this); }; WorkbookView.prototype.getWorksheetById = function(id, onlyExist) { var wsModel = this.model.getWorksheetById(id); if (wsModel) { return this.getWorksheet(wsModel.getIndex(), onlyExist); } return null; }; /** * @param {Number} [index] * @param {Boolean} [onlyExist] * @return {AscCommonExcel.WorksheetView} */ WorkbookView.prototype.getWorksheet = function(index, onlyExist) { var wb = this.model; var i = asc_typeof(index) === "number" && index >= 0 ? index : wb.getActive(); var ws = this.wsViews[i]; if (!ws && !onlyExist) { ws = this.wsViews[i] = this._createWorksheetView(wb.getWorksheet(i)); ws._prepareComments(); ws._prepareDrawingObjects(); } return ws; }; WorkbookView.prototype.drawWorksheet = function () { if (-1 === this.wsActive) { return this.showWorksheet(); } var ws = this.getWorksheet(); ws.draw(); ws.objectRender.controller.updateSelectionState(); ws.objectRender.controller.updateOverlay(); this._onScrollReinitialize(AscCommonExcel.c_oAscScrollType.ScrollVertical | AscCommonExcel.c_oAscScrollType.ScrollHorizontal); }; /** * * @param index * @param [bLockDraw] * @returns {WorkbookView} */ WorkbookView.prototype.showWorksheet = function (index, bLockDraw) { if (window["NATIVE_EDITOR_ENJINE"] && !window['IS_NATIVE_EDITOR'] && !window['DoctRendererMode']) { return this; } // ToDo disable method for assembly var ws, wb = this.model; if (asc_typeof(index) !== "number" || 0 > index) { index = wb.getActive(); } if (index === this.wsActive) { if (!bLockDraw) { this.drawWorksheet(); } return this; } var tmpWorksheet, selectionRange = null; // Только если есть активный if (-1 !== this.wsActive) { ws = this.getWorksheet(); // Останавливаем ввод данных в редакторе ввода. Если в режиме ввода формул, то продолжаем работать с cellEditor'ом, чтобы можно было // выбирать ячейки для формулы if (this.getCellEditMode()) { if (this.cellEditor && this.cellEditor.formulaIsOperator()) { this.copyActiveSheet = this.wsActive; if (!this.cellFormulaEnterWSOpen) { this.cellFormulaEnterWSOpen = ws; } else { ws.setFormulaEditMode(false); } } else { this._onStopCellEditing(); } } // Делаем очистку селекта ws.cleanSelection(); this.stopTarget(ws); } if (c_oAscSelectionDialogType.Chart === this.selectionDialogType) { // Когда идет выбор диапазона, то должны на закрываемом листе отменить выбор диапазона tmpWorksheet = this.getWorksheet(); selectionRange = tmpWorksheet.model.selectionRange.getLast().clone(true); tmpWorksheet.setSelectionDialogMode(c_oAscSelectionDialogType.None); } if (this.stateFormatPainter) { // Должны отменить выбор на закрываемом листе this.getWorksheet().formatPainter(c_oAscFormatPainterState.kOff); } if (index !== wb.getActive()) { wb.setActive(index); } this.wsActive = index; this.wsMustDraw = bLockDraw; // Посылаем эвент о смене активного листа this.handlers.trigger("asc_onActiveSheetChanged", this.wsActive); this.handlers.trigger("asc_onHideComment"); ws = this.getWorksheet(index); // Мы делали resize или меняли zoom, но не перерисовывали данный лист (он был не активный) if (ws.updateResize && ws.updateZoom) { ws.changeZoomResize(); } else if (ws.updateResize) { ws.resize(true, this.cellEditor); } else if (ws.updateZoom) { ws.changeZoom(true); } this.updateGroupData(); if (this.cellEditor && this.cellFormulaEnterWSOpen) { if (ws === this.cellFormulaEnterWSOpen) { this.cellFormulaEnterWSOpen.setFormulaEditMode(true); this.cellEditor._showCanvas(); } else if (this.getCellEditMode() && this.cellEditor.isFormula()) { this.cellFormulaEnterWSOpen.setFormulaEditMode(false); /*скрываем cellEditor, в редактор добавляем %selected sheet name%+"!" */ this.cellEditor._hideCanvas(); ws.cleanSelection(); ws.setFormulaEditMode(true); } } if (!bLockDraw) { ws.draw(); } if (c_oAscSelectionDialogType.Chart === this.selectionDialogType) { // Когда идет выбор диапазона, то на показываемом листе должны выставить нужный режим ws.setSelectionDialogMode(this.selectionDialogType, selectionRange); this.handlers.trigger("asc_onSelectionRangeChanged", ws.getSelectionRangeValue()); } if (this.stateFormatPainter) { // Должны отменить выбор на закрываемом листе this.getWorksheet().formatPainter(this.stateFormatPainter); } if (!bLockDraw) { ws.objectRender.controller.updateSelectionState(); ws.objectRender.controller.updateOverlay(); } if (!window["NATIVE_EDITOR_ENJINE"]) { this._onSelectionNameChanged(ws.getSelectionName(/*bRangeText*/false)); this._onWSSelectionChanged(); this._onSelectionMathInfoChanged(ws.getSelectionMathInfo()); } this._onScrollReinitialize(AscCommonExcel.c_oAscScrollType.ScrollVertical | AscCommonExcel.c_oAscScrollType.ScrollHorizontal); // Zoom теперь на каждом листе одинаковый, не отправляем смену //TODO при добавлении любого действия в историю (например добавление нового листа), мы можем его потом отменить с повощью опции авторазвертывания this.toggleAutoCorrectOptions(null, true); window['AscCommon'].g_specialPasteHelper.SpecialPasteButton_Hide(); return this; }; WorkbookView.prototype.stopTarget = function(ws) { if (null === ws && -1 !== this.wsActive) { ws = this.getWorksheet(this.wsActive); } if (null !== ws && ws.objectRender && ws.objectRender.drawingDocument) { ws.objectRender.drawingDocument.TargetEnd(); } }; WorkbookView.prototype.updateWorksheetByModel = function() { // ToDo Сделал небольшую заглушку с показом листа. Нужно как мне кажется перейти от wsViews на wsViewsId (хранить по id) var oldActiveWs; if (-1 !== this.wsActive) { oldActiveWs = this.wsViews[this.wsActive]; } //расставляем ws так как они идут в модели. var oNewWsViews = []; for (var i in this.wsViews) { var item = this.wsViews[i]; if (null != item && null != this.model.getWorksheetById(item.model.getId())) { oNewWsViews[item.model.getIndex()] = item; } } this.wsViews = oNewWsViews; var wsActive = this.model.getActive(); var newActiveWs = this.wsViews[wsActive]; if (undefined === newActiveWs || oldActiveWs !== newActiveWs) { // Если сменили, то покажем this.wsActive = -1; this.showWorksheet(wsActive, true); } else { this.wsActive = wsActive; } }; WorkbookView.prototype._canResize = function() { var isRetina = AscBrowser.isRetina; var oldWidth = this.canvas.width; var oldHeight = this.canvas.height; var width, height, styleWidth, styleHeight; width = styleWidth = this.element.offsetWidth - (this.Api.isMobileVersion ? 0 : this.defaults.scroll.widthPx); height = styleHeight = this.element.offsetHeight - (this.Api.isMobileVersion ? 0 : this.defaults.scroll.heightPx); if (isRetina) { width = AscCommon.AscBrowser.convertToRetinaValue(width, true); height = AscCommon.AscBrowser.convertToRetinaValue(height, true); } if (oldWidth === width && oldHeight === height && this.isInit) { return false; } this.isInit = true; this.canvas.width = this.canvasOverlay.width = this.canvasGraphic.width = this.canvasGraphicOverlay.width = width; this.canvas.height = this.canvasOverlay.height = this.canvasGraphic.height = this.canvasGraphicOverlay.height = height; this.canvas.style.width = this.canvasOverlay.style.width = this.canvasGraphic.style.width = this.canvasGraphicOverlay.style.width = styleWidth + 'px'; this.canvas.style.height = this.canvasOverlay.style.height = this.canvasGraphic.style.height = this.canvasGraphicOverlay.style.height = styleHeight + 'px'; this._reInitGraphics(); return true; }; WorkbookView.prototype._reInitGraphics = function () { var canvasWidth = this.canvasGraphic.width; var canvasHeight = this.canvasGraphic.height; this.shapeCtx.init(this.drawingGraphicCtx.ctx, canvasWidth, canvasHeight, canvasWidth * 25.4 / this.drawingGraphicCtx.ppiX, canvasHeight * 25.4 / this.drawingGraphicCtx.ppiY); this.shapeCtx.CalculateFullTransform(); var overlayWidth = this.canvasGraphicOverlay.width; var overlayHeight = this.canvasGraphicOverlay.height; this.shapeOverlayCtx.init(this.overlayGraphicCtx.ctx, overlayWidth, overlayHeight, overlayWidth * 25.4 / this.overlayGraphicCtx.ppiX, overlayHeight * 25.4 / this.overlayGraphicCtx.ppiY); this.shapeOverlayCtx.CalculateFullTransform(); this.mainGraphics.init(this.drawingCtx.ctx, canvasWidth, canvasHeight, canvasWidth * 25.4 / this.drawingCtx.ppiX, canvasHeight * 25.4 / this.drawingCtx.ppiY); this.trackOverlay.init(this.shapeOverlayCtx.m_oContext, "ws-canvas-graphic-overlay", 0, 0, overlayWidth, overlayHeight, (overlayWidth * 25.4 / this.overlayGraphicCtx.ppiX), (overlayHeight * 25.4 / this.overlayGraphicCtx.ppiY)); this.autoShapeTrack.init(this.trackOverlay, 0, 0, overlayWidth, overlayHeight, overlayWidth * 25.4 / this.overlayGraphicCtx.ppiX, overlayHeight * 25.4 / this.overlayGraphicCtx.ppiY); this.autoShapeTrack.Graphics.CalculateFullTransform(); }; /** @param event {jQuery.Event} */ WorkbookView.prototype.resize = function(event) { if (this._canResize()) { var item; var activeIndex = this.model.getActive(); for (var i in this.wsViews) { item = this.wsViews[i]; // Делаем resize (для не активных сменим как только сделаем его активным) item.resize(/*isDraw*/i == activeIndex, this.cellEditor); } this.drawWorksheet(); } else { // ToDo не должно происходить ничего, но нам приходит resize сверху, поэтому проверим отрисовывали ли мы if (-1 === this.wsActive || this.wsMustDraw) { this.drawWorksheet(); } } this.wsMustDraw = false; }; WorkbookView.prototype.getSelectionInfo = function () { if (!this.oSelectionInfo) { this._updateSelectionInfo(); } return this.oSelectionInfo; }; // Получаем свойство: редактируем мы сейчас или нет WorkbookView.prototype.getCellEditMode = function() { return this.isCellEditMode; }; WorkbookView.prototype.setCellEditMode = function(flag) { this.isCellEditMode = !!flag; }; WorkbookView.prototype.getIsTrackShape = function() { var ws = this.getWorksheet(); if (!ws) { return false; } if (ws.objectRender && ws.objectRender.controller) { return ws.objectRender.controller.checkTrackDrawings(); } }; WorkbookView.prototype.getZoom = function() { return this.drawingCtx.getZoom(); }; WorkbookView.prototype.changeZoom = function(factor) { if (factor === this.getZoom()) { return; } this.buffers.main.changeZoom(factor); this.buffers.overlay.changeZoom(factor); this.buffers.mainGraphic.changeZoom(factor); this.buffers.overlayGraphic.changeZoom(factor); if (!factor) { this.cellEditor.changeZoom(factor); } // Нужно сбросить кэш букв var i, length; for (i = 0, length = this.fmgrGraphics.length; i < length; ++i) this.fmgrGraphics[i].ClearFontsRasterCache(); if (AscCommon.g_fontManager) { AscCommon.g_fontManager.ClearFontsRasterCache(); AscCommon.g_fontManager.m_pFont = null; } if (AscCommon.g_fontManager2) { AscCommon.g_fontManager2.ClearFontsRasterCache(); AscCommon.g_fontManager2.m_pFont = null; } if (!factor) { this.wsMustDraw = true; this._calcMaxDigitWidth(); } var item; var activeIndex = this.model.getActive(); for (i in this.wsViews) { item = this.wsViews[i]; // Меняем zoom (для не активных сменим как только сделаем его активным) if (!factor) { item._initWorksheetDefaultWidth(); } item.changeZoom(/*isDraw*/i == activeIndex); this._reInitGraphics(); item.objectRender.changeZoom(this.drawingCtx.scaleFactor); if (i == activeIndex && factor) { item.draw(); //ToDo item.drawDepCells(); } } this._onScrollReinitialize(AscCommonExcel.c_oAscScrollType.ScrollVertical | AscCommonExcel.c_oAscScrollType.ScrollHorizontal); this.handlers.trigger("asc_onZoomChanged", this.getZoom()); }; WorkbookView.prototype.getEnableKeyEventsHandler = function(bIsNaturalFocus) { var res = this.enableKeyEvents; if (res && bIsNaturalFocus && this.getCellEditMode() && this.input.isFocused) { res = false; } return res; }; WorkbookView.prototype.enableKeyEventsHandler = function(f) { this.enableKeyEvents = !!f; this.controller.enableKeyEventsHandler(this.enableKeyEvents); if (this.cellEditor) { this.cellEditor.enableKeyEventsHandler(this.enableKeyEvents); } }; // Останавливаем ввод данных в редакторе ввода WorkbookView.prototype.closeCellEditor = function (cancel) { return this.getCellEditMode() ? this._onStopCellEditing(cancel) : true; }; WorkbookView.prototype.restoreFocus = function() { if (window["NATIVE_EDITOR_ENJINE"]) { return; } if (this.cellEditor.hasFocus) { this.cellEditor.restoreFocus(); } }; WorkbookView.prototype._onUpdateCellEditor = function(text, cursorPosition, fPos, fName) { if (this.skipHelpSelector) { return; } // ToDo для ускорения можно завести объект, куда класть результаты поиска по формулам и второй раз не искать. var i, arrResult = [], defNamesList, defName, defNameStr; if (fName) { fName = fName.toUpperCase(); for (i = 0; i < this.formulasList.length; ++i) { if (0 === this.formulasList[i].indexOf(fName)) { arrResult.push(new AscCommonExcel.asc_CCompleteMenu(this.formulasList[i], c_oAscPopUpSelectorType.Func)); } } defNamesList = this.getDefinedNames(Asc.c_oAscGetDefinedNamesList.WorksheetWorkbook); fName = fName.toLowerCase(); for (i = 0; i < defNamesList.length; ++i) { /*defName = defNamesList[i]; if (0 === defName.Name.toLowerCase().indexOf(fName)) { arrResult.push(new AscCommonExcel.asc_CCompleteMenu(defName.Name, !defName.isTable ? c_oAscPopUpSelectorType.Range : c_oAscPopUpSelectorType.Table));*/ defName = defNamesList[i]; defNameStr = defName.Name.toLowerCase(); if(null !== defName.LocalSheetId && defNameStr === "print_area") { defNameStr = AscCommon.translateManager.getValue("Print_Area"); } if (0 === defNameStr.toLowerCase().indexOf(fName)) { arrResult.push(new AscCommonExcel.asc_CCompleteMenu(defNameStr, !defName.isTable ? c_oAscPopUpSelectorType.Range : c_oAscPopUpSelectorType.Table)); } } } if (0 < arrResult.length) { this.handlers.trigger('asc_onFormulaCompleteMenu', arrResult); this.lastFPos = fPos; this.lastFNameLength = fName.length; } else { this.handlers.trigger('asc_onFormulaCompleteMenu', null); this.lastFPos = -1; this.lastFNameLength = 0; } }; // Вставка формулы в редактор WorkbookView.prototype.insertFormulaInEditor = function (name, type, autoComplete) { var t = this, ws = this.getWorksheet(), cursorPos, isNotFunction, tmp; var activeCellRange = ws.getActiveCell(0, 0, false); if (ws.model.inPivotTable(activeCellRange)) { this.handlers.trigger("asc_onError", c_oAscError.ID.LockedCellPivot, c_oAscError.Level.NoCritical); return; } if (c_oAscPopUpSelectorType.None === type) { ws.setSelectionInfo("value", name, /*onlyActive*/true); return; } isNotFunction = c_oAscPopUpSelectorType.Func !== type; // Проверяем, открыт ли редактор if (this.getCellEditMode()) { if (isNotFunction) { this.skipHelpSelector = true; } if (-1 !== this.lastFPos) { if (-1 === this.arrExcludeFormulas.indexOf(name) && !isNotFunction) { //если следующий символ скобка - не добавляем ещё одну if('(' !== this.cellEditor.textRender.getChars(this.cellEditor.cursorPos, 1)) { name += '('; // ToDo сделать проверки при добавлении, чтобы не вызывать постоянно окно } } else { this.skipHelpSelector = true; } tmp = this.cellEditor.skipTLUpdate; this.cellEditor.skipTLUpdate = false; this.cellEditor.replaceText(this.lastFPos, this.lastFNameLength, name); this.cellEditor.skipTLUpdate = tmp; } else if (false === this.cellEditor.insertFormula(name, isNotFunction)) { // Не смогли вставить формулу, закроем редактор, с сохранением текста this.cellEditor.close(true); } this.skipHelpSelector = false; } else { // Проверка глобального лока if (this.collaborativeEditing.getGlobalLock()) { return; } var selectionRange = ws.model.selectionRange.clone(); // Редактор закрыт var cellRange = {}; // Если нужно сделать автозаполнение формулы, то ищем ячейки) if (autoComplete) { cellRange = ws.autoCompleteFormula(name); } if (isNotFunction) { name = "=" + name; } else { if (cellRange.notEditCell) { // Мы уже ввели все что нужно, редактор открывать не нужно return; } if (cellRange.text) { // Меняем значение ячейки name = "=" + name + "(" + cellRange.text + ")"; } else { // Меняем значение ячейки name = "=" + name + "()"; } // Вычисляем позицию курсора (он должен быть в функции) cursorPos = name.length - 1; } var openEditor = function (res) { if (res) { // Выставляем переменные, что мы редактируем t.setCellEditMode(true); if (isNotFunction) { t.skipHelpSelector = true; } t.hideSpecialPasteButton(); // Открываем, с выставлением позиции курсора ws.openCellEditorWithText(t.cellEditor, name, cursorPos, /*isFocus*/false, selectionRange); if (isNotFunction) { t.skipHelpSelector = false; } } else { t.setCellEditMode(false); t.controller.setStrictClose(false); t.controller.setFormulaEditMode(false); ws.setFormulaEditMode(false); } }; ws._isLockedCells(activeCellRange, /*subType*/null, openEditor); } }; WorkbookView.prototype.bIsEmptyClipboard = function() { return g_clipboardExcel.bIsEmptyClipboard(this.getCellEditMode()); }; WorkbookView.prototype.checkCopyToClipboard = function(_clipboard, _formats) { var t = this, ws; ws = t.getWorksheet(); g_clipboardExcel.checkCopyToClipboard(ws, _clipboard, _formats); }; WorkbookView.prototype.pasteData = function(_format, data1, data2, text_data, doNotShowButton) { var t = this, ws; ws = t.getWorksheet(); g_clipboardExcel.pasteData(ws, _format, data1, data2, text_data, null, doNotShowButton); }; WorkbookView.prototype.specialPasteData = function(props) { if (!this.getCellEditMode()) { this.getWorksheet().specialPaste(props); } }; WorkbookView.prototype.showSpecialPasteButton = function(props) { if (!this.getCellEditMode()) { this.getWorksheet().showSpecialPasteOptions(props); } }; WorkbookView.prototype.updateSpecialPasteButton = function(props) { if (!this.getCellEditMode()) { this.getWorksheet().updateSpecialPasteButton(props); } }; WorkbookView.prototype.hideSpecialPasteButton = function() { //TODO пересмотреть! //сейчас сначала добавляются данные в историю, потом идет закрытие редактора ячейки //следовательно убираю проверку на редактирование ячейки /*if (!this.getCellEditMode()) {*/ this.handlers.trigger("hideSpecialPasteOptions"); //} }; WorkbookView.prototype.selectionCut = function () { if (this.getCellEditMode()) { this.cellEditor.cutSelection(); } else { if (this.getWorksheet().isNeedSelectionCut()) { this.getWorksheet().emptySelection(c_oAscCleanOptions.All, true); } else { //в данном случае не вырезаем, а записываем if(false === this.getWorksheet().isMultiSelect()) { this.cutIdSheet = this.getWorksheet().model.Id; this.getWorksheet().cutRange = this.getWorksheet().model.selectionRange.getLast(); } } } }; WorkbookView.prototype.undo = function() { var oFormulaLocaleInfo = AscCommonExcel.oFormulaLocaleInfo; oFormulaLocaleInfo.Parse = false; oFormulaLocaleInfo.DigitSep = false; if (!this.getCellEditMode()) { if (!History.Undo() && this.collaborativeEditing.getFast() && this.collaborativeEditing.getCollaborativeEditing()) { this.Api.sync_TryUndoInFastCollaborative(); } } else { this.cellEditor.undo(); } oFormulaLocaleInfo.Parse = true; oFormulaLocaleInfo.DigitSep = true; }; WorkbookView.prototype.redo = function() { if (!this.getCellEditMode()) { History.Redo(); } else { this.cellEditor.redo(); } }; WorkbookView.prototype.setFontAttributes = function(prop, val) { if (!this.getCellEditMode()) { this.getWorksheet().setSelectionInfo(prop, val); } else { this.cellEditor.setTextStyle(prop, val); } }; WorkbookView.prototype.changeFontSize = function(prop, val) { if (!this.getCellEditMode()) { this.getWorksheet().setSelectionInfo(prop, val); } else { this.cellEditor.setTextStyle(prop, val); } }; WorkbookView.prototype.setCellFormat = function (format) { this.getWorksheet().setSelectionInfo("format", format); }; WorkbookView.prototype.emptyCells = function (options) { if (!this.getCellEditMode()) { if (Asc.c_oAscCleanOptions.Comments === options) { this.removeAllComments(false, true); } else { this.getWorksheet().emptySelection(options); } this.restoreFocus(); } else { this.cellEditor.empty(options); } }; WorkbookView.prototype.setSelectionDialogMode = function(selectionDialogType, selectRange) { if (selectionDialogType === this.selectionDialogType) { return; } if (c_oAscSelectionDialogType.None === selectionDialogType) { this.selectionDialogType = selectionDialogType; this.getWorksheet().setSelectionDialogMode(selectionDialogType, selectRange); if (this.copyActiveSheet !== this.wsActive) { this.showWorksheet(this.copyActiveSheet); } this.copyActiveSheet = -1; this.input.disabled = false; } else { this.copyActiveSheet = this.wsActive; var index, tmpSelectRange = AscCommon.parserHelp.parse3DRef(selectRange); if (tmpSelectRange) { if (c_oAscSelectionDialogType.Chart === selectionDialogType) { // Получаем sheet по имени var ws = this.model.getWorksheetByName(tmpSelectRange.sheet); if (!ws || ws.getHidden()) { tmpSelectRange = null; } else { index = ws.getIndex(); this.showWorksheet(index); tmpSelectRange = tmpSelectRange.range; } } else { tmpSelectRange = tmpSelectRange.range; } } else { // Это не 3D ссылка tmpSelectRange = selectRange; } this.getWorksheet().setSelectionDialogMode(selectionDialogType, tmpSelectRange); // Нужно выставить после, т.к. при смене листа не должны проставлять режим this.selectionDialogType = selectionDialogType; this.input.disabled = true; } }; WorkbookView.prototype.formatPainter = function(stateFormatPainter) { // Если передали состояние, то выставляем его. Если нет - то меняем на противоположное. this.stateFormatPainter = (null != stateFormatPainter) ? stateFormatPainter : ((c_oAscFormatPainterState.kOff !== this.stateFormatPainter) ? c_oAscFormatPainterState.kOff : c_oAscFormatPainterState.kOn); this.rangeFormatPainter = this.getWorksheet().formatPainter(this.stateFormatPainter); if (this.stateFormatPainter) { this.copyActiveSheet = this.wsActive; } else { this.copyActiveSheet = -1; this.handlers.trigger('asc_onStopFormatPainter'); } }; // Поиск текста в листе WorkbookView.prototype.findCellText = function(options) { // Для поиска эта переменная не нужна (но она может остаться от replace) options.selectionRange = null; var ws = this.getWorksheet(); // Останавливаем ввод данных в редакторе ввода if (this.getCellEditMode()) { this._onStopCellEditing(); } var result = this.model.findCellText(options); if (result) { var range = new Asc.Range(result.col, result.row, result.col, result.row); options.findInSelection ? ws.setActiveCell(result) : ws.setSelection(range); return true; } return null; }; // Замена текста в листе WorkbookView.prototype.replaceCellText = function(options) { if (!options.isMatchCase) { options.findWhat = options.findWhat.toLowerCase(); } options.findRegExp = AscCommonExcel.getFindRegExp(options.findWhat, options); var ws = this.getWorksheet(); // Останавливаем ввод данных в редакторе ввода if (this.getCellEditMode()) { this._onStopCellEditing(); } History.Create_NewPoint(); History.StartTransaction(); options.clearFindAll(); if (options.isReplaceAll) { // На ReplaceAll ставим медленную операцию this.Api.sync_StartAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.SlowOperation); } ws.replaceCellText(options, false, this.fReplaceCallback); }; WorkbookView.prototype._replaceCellTextCallback = function(options) { if (!options.error) { options.updateFindAll(); if (!options.scanOnOnlySheet && options.isReplaceAll) { // Замена на всей книге var i = ++options.sheetIndex; if (this.model.getActive() === i) { i = ++options.sheetIndex; } if (i < this.model.getWorksheetCount()) { var ws = this.getWorksheet(i); ws.replaceCellText(options, true, this.fReplaceCallback); return; } options.sheetIndex = -1; } this.handlers.trigger("asc_onRenameCellTextEnd", options.countFindAll, options.countReplaceAll); } History.EndTransaction(); if (options.isReplaceAll) { // Заканчиваем медленную операцию this.Api.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.SlowOperation); } }; WorkbookView.prototype.getDefinedNames = function(defNameListId) { return this.model.getDefinedNamesWB(defNameListId, true); }; WorkbookView.prototype.setDefinedNames = function(defName) { //ToDo проверка defName.ref на знак "=" в начале ссылки. знака нет тогда это либо число либо строка, так делает Excel. this.model.setDefinesNames(defName.Name, defName.Ref, defName.Scope); this.handlers.trigger("asc_onDefName"); }; WorkbookView.prototype.editDefinedNames = function(oldName, newName) { //ToDo проверка defName.ref на знак "=" в начале ссылки. знака нет тогда это либо число либо строка, так делает Excel. if (this.collaborativeEditing.getGlobalLock()) { return; } var ws = this.getWorksheet(), t = this; var editDefinedNamesCallback = function(res) { if (res) { if (oldName && oldName.asc_getIsTable()) { ws.model.autoFilters.changeDisplayNameTable(oldName.asc_getName(), newName.asc_getName()); } else { t.model.editDefinesNames(oldName, newName); } t.handlers.trigger("asc_onEditDefName", oldName, newName); //условие исключает второй вызов asc_onRefreshDefNameList(первый в unlockDefName) if(!(t.collaborativeEditing.getCollaborativeEditing() && t.collaborativeEditing.getFast())) { t.handlers.trigger("asc_onRefreshDefNameList"); } } else { t.handlers.trigger("asc_onError", c_oAscError.ID.LockCreateDefName, c_oAscError.Level.NoCritical); } t._onSelectionNameChanged(ws.getSelectionName(/*bRangeText*/false)); if(ws.viewPrintLines) { ws.updateSelection(); } }; var defNameId; if (oldName) { defNameId = t.model.getDefinedName(oldName); defNameId = defNameId ? defNameId.getNodeId() : null; } var callback = function() { ws._isLockedDefNames(editDefinedNamesCallback, defNameId); }; var tableRange; if(oldName && true === oldName.isTable) { var table = ws.model.autoFilters._getFilterByDisplayName(oldName.Name); if(table) { tableRange = table.Ref; } } if(tableRange) { ws._isLockedCells( tableRange, null, callback ); } else { callback(); } }; WorkbookView.prototype.delDefinedNames = function(oldName) { //ToDo проверка defName.ref на знак "=" в начале ссылки. знака нет тогда это либо число либо строка, так делает Excel. if (this.collaborativeEditing.getGlobalLock()) { return; } var ws = this.getWorksheet(), t = this; if (oldName) { var delDefinedNamesCallback = function(res) { if (res) { t.model.delDefinesNames(oldName); t.handlers.trigger("asc_onRefreshDefNameList"); } else { t.handlers.trigger("asc_onError", c_oAscError.ID.LockCreateDefName, c_oAscError.Level.NoCritical); } t._onSelectionNameChanged(ws.getSelectionName(/*bRangeText*/false)); if(ws.viewPrintLines) { ws.updateSelection(); } }; var defNameId = t.model.getDefinedName(oldName).getNodeId(); ws._isLockedDefNames(delDefinedNamesCallback, defNameId); } }; WorkbookView.prototype.getDefaultDefinedName = function() { //ToDo проверка defName.ref на знак "=" в начале ссылки. знака нет тогда это либо число либо строка, так делает Excel. var ws = this.getWorksheet(); var oRangeValue = ws.getSelectionRangeValue(); return new Asc.asc_CDefName("", oRangeValue.asc_getName(), null); }; WorkbookView.prototype.getDefaultTableStyle = function() { return this.model.TableStyles.DefaultTableStyle; }; WorkbookView.prototype.unlockDefName = function() { this.model.unlockDefName(); this.handlers.trigger("asc_onRefreshDefNameList"); this.handlers.trigger("asc_onLockDefNameManager", Asc.c_oAscDefinedNameReason.OK); }; WorkbookView.prototype.unlockCurrentDefName = function(name, sheetId) { this.model.unlockCurrentDefName(name, sheetId); //this.handlers.trigger("asc_onRefreshDefNameList"); //this.handlers.trigger("asc_onLockDefNameManager", Asc.c_oAscDefinedNameReason.OK); }; WorkbookView.prototype._onCheckDefNameLock = function() { return this.model.checkDefNameLock(); }; // Печать WorkbookView.prototype.printSheets = function(printPagesData, pdfDocRenderer) { //change zoom on default var viewZoom = this.getZoom(); this.changeZoom(1); var pdfPrinter = new AscCommonExcel.CPdfPrinter(this.fmgrGraphics[3], this.m_oFont); if (pdfDocRenderer) { pdfPrinter.DocumentRenderer = pdfDocRenderer; } var ws; if (0 === printPagesData.arrPages.length) { // Печать пустой страницы ws = this.getWorksheet(); ws.drawForPrint(pdfPrinter, null); } else { var indexWorksheet = -1; var indexWorksheetTmp = -1; for (var i = 0; i < printPagesData.arrPages.length; ++i) { indexWorksheetTmp = printPagesData.arrPages[i].indexWorksheet; if (indexWorksheetTmp !== indexWorksheet) { ws = this.getWorksheet(indexWorksheetTmp); indexWorksheet = indexWorksheetTmp; } ws.drawForPrint(pdfPrinter, printPagesData.arrPages[i], i, printPagesData.arrPages.length); } } this.changeZoom(viewZoom); return pdfPrinter; }; WorkbookView.prototype._calcPagesPrintSheet = function (index, printPagesData, onlySelection, adjustPrint) { var ws = this.model.getWorksheet(index); var wsView = this.getWorksheet(index); if (!ws.getHidden()) { var pageOptionsMap = adjustPrint ? adjustPrint.asc_getPageOptionsMap() : null; var pagePrintOptions = pageOptionsMap && pageOptionsMap[index] ? pageOptionsMap[index] : ws.PagePrintOptions; wsView.calcPagesPrint(pagePrintOptions, onlySelection, index, printPagesData.arrPages, null, adjustPrint); } }; WorkbookView.prototype.calcPagesPrint = function (adjustPrint) { if (!adjustPrint) { adjustPrint = new Asc.asc_CAdjustPrint(); } var viewZoom = this.getZoom(); this.changeZoom(1); var printPagesData = new asc_CPrintPagesData(); var printType = adjustPrint.asc_getPrintType(); if (printType === Asc.c_oAscPrintType.ActiveSheets) { this._calcPagesPrintSheet(this.model.getActive(), printPagesData, false, adjustPrint); } else if (printType === Asc.c_oAscPrintType.EntireWorkbook) { // Колличество листов var countWorksheets = this.model.getWorksheetCount(); for (var i = 0; i < countWorksheets; ++i) { if(adjustPrint.isOnlyFirstPage && i !== 0) { break; } this._calcPagesPrintSheet(i, printPagesData, false, adjustPrint); } } else if (printType === Asc.c_oAscPrintType.Selection) { this._calcPagesPrintSheet(this.model.getActive(), printPagesData, true, adjustPrint); } if (AscCommonExcel.c_kMaxPrintPages === printPagesData.arrPages.length) { this.handlers.trigger("asc_onError", c_oAscError.ID.PrintMaxPagesCount, c_oAscError.Level.NoCritical); } this.changeZoom(viewZoom); return printPagesData; }; // Вызывать только для нативной печати WorkbookView.prototype._nativeCalculate = function() { var item; for (var i in this.wsViews) { item = this.wsViews[i]; item._cleanCellsTextMetricsCache(); item._prepareDrawingObjects(); } }; WorkbookView.prototype.calculate = function (type) { this.model.calculate(type); this.drawWS(); }; WorkbookView.prototype.reInit = function() { var ws = this.getWorksheet(); ws._initCellsArea(AscCommonExcel.recalcType.full); ws._updateVisibleColsCount(); ws._updateVisibleRowsCount(); }; WorkbookView.prototype.drawWS = function() { this.getWorksheet().draw(); }; WorkbookView.prototype.onShowDrawingObjects = function(clearCanvas) { var ws = this.getWorksheet(); ws.objectRender.showDrawingObjects(clearCanvas); }; WorkbookView.prototype.insertHyperlink = function(options) { var ws = this.getWorksheet(); if (ws.objectRender.selectedGraphicObjectsExists()) { if (ws.objectRender.controller.canAddHyperlink()) { ws.objectRender.controller.insertHyperlink(options); } } else { ws.setSelectionInfo("hyperlink", options); this.restoreFocus(); } }; WorkbookView.prototype.removeHyperlink = function() { var ws = this.getWorksheet(); if (ws.objectRender.selectedGraphicObjectsExists()) { ws.objectRender.controller.removeHyperlink(); } else { ws.setSelectionInfo("rh"); } }; WorkbookView.prototype.setDocumentPlaceChangedEnabled = function(val) { this.isDocumentPlaceChangedEnabled = val; }; WorkbookView.prototype.showComments = function (val, isShowSolved) { if (this.isShowComments !== val || this.isShowSolved !== isShowSolved) { this.isShowComments = val; this.isShowSolved = isShowSolved; this.drawWS(); } }; WorkbookView.prototype.removeComment = function (id) { var ws = this.getWorksheet(); ws.cellCommentator.removeComment(id); this.cellCommentator.removeComment(id); }; WorkbookView.prototype.removeAllComments = function (isMine, isCurrent) { var range; var ws = this.getWorksheet(); isMine = isMine ? (this.Api.DocInfo && this.Api.DocInfo.get_UserId()) : null; History.Create_NewPoint(); History.StartTransaction(); if (isCurrent) { ws._getSelection().ranges.forEach(function (item) { ws.cellCommentator.deleteCommentsRange(item, isMine); }); } else { range = new Asc.Range(0, 0, AscCommon.gc_nMaxCol0, AscCommon.gc_nMaxRow0); this.cellCommentator.deleteCommentsRange(range, isMine); ws.cellCommentator.deleteCommentsRange(range, isMine); } History.EndTransaction(); }; /* * @param {c_oAscRenderingModeType} mode Режим отрисовки * @param {Boolean} isInit инициализация или нет */ WorkbookView.prototype.setFontRenderingMode = function(mode, isInit) { if (mode !== this.fontRenderingMode) { this.fontRenderingMode = mode; if (c_oAscFontRenderingModeType.noHinting === mode) { this._setHintsProps(false, false); } else if (c_oAscFontRenderingModeType.hinting === mode) { this._setHintsProps(true, false); } else if (c_oAscFontRenderingModeType.hintingAndSubpixeling === mode) { this._setHintsProps(true, true); } if (!isInit) { this.drawWS(); this.cellEditor.setFontRenderingMode(mode); } } }; WorkbookView.prototype.initFormulasList = function() { this.formulasList = []; var oFormulaList = AscCommonExcel.cFormulaFunctionLocalized ? AscCommonExcel.cFormulaFunctionLocalized : AscCommonExcel.cFormulaFunction; for (var f in oFormulaList) { this.formulasList.push(f); } this.arrExcludeFormulas = [cBoolLocal.t, cBoolLocal.f]; }; WorkbookView.prototype._setHintsProps = function(bIsHinting, bIsSubpixHinting) { var manager; for (var i = 0, length = this.fmgrGraphics.length; i < length; ++i) { manager = this.fmgrGraphics[i]; // Последний без хинтования (только для измерения) if (i === length - 1) { bIsHinting = bIsSubpixHinting = false; } manager.SetHintsProps(bIsHinting, bIsSubpixHinting); } }; WorkbookView.prototype._calcMaxDigitWidth = function () { // set default worksheet header font for calculations this.buffers.main.setFont(AscCommonExcel.g_oDefaultFormat.Font); // Измеряем в pt this.stringRender.measureString("0123456789", new AscCommonExcel.CellFlags()); // Переводим в px и приводим к целому (int) this.model.maxDigitWidth = this.maxDigitWidth = this.stringRender.getWidestCharWidth(); // Проверка для Calibri 11 должно быть this.maxDigitWidth = 7 if (!this.maxDigitWidth) { throw "Error: can't measure text string"; } // Padding рассчитывается исходя из maxDigitWidth (http://social.msdn.microsoft.com/Forums/en-US/9a6a9785-66ad-4b6b-bb9f-74429381bd72/margin-padding-in-cell-excel?forum=os_binaryfile) this.defaults.worksheetView.cells.padding = Math.max(asc.ceil(this.maxDigitWidth / 4), 2); this.model.paddingPlusBorder = 2 * this.defaults.worksheetView.cells.padding + 1; }; WorkbookView.prototype.getPivotMergeStyle = function (sheetMergedStyles, range, style, pivot) { var styleInfo = pivot.asc_getStyleInfo(); var i, r, dxf, stripe1, stripe2, emptyStripe = new Asc.CTableStyleElement(); if (style) { dxf = style.wholeTable && style.wholeTable.dxf; if (dxf) { sheetMergedStyles.setTablePivotStyle(range, dxf); } if (styleInfo.showColStripes) { stripe1 = style.firstColumnStripe || emptyStripe; stripe2 = style.secondColumnStripe || emptyStripe; if (stripe1.dxf) { sheetMergedStyles.setTablePivotStyle(range, stripe1.dxf, new Asc.CTableStyleStripe(stripe1.size, stripe2.size)); } if (stripe2.dxf && range.c1 + stripe1.size <= range.c2) { sheetMergedStyles.setTablePivotStyle( new Asc.Range(range.c1 + stripe1.size, range.r1, range.c2, range.r2), stripe2.dxf, new Asc.CTableStyleStripe(stripe2.size, stripe1.size)); } } if (styleInfo.showRowStripes) { stripe1 = style.firstRowStripe || emptyStripe; stripe2 = style.secondRowStripe || emptyStripe; if (stripe1.dxf) { sheetMergedStyles.setTablePivotStyle(range, stripe1.dxf, new Asc.CTableStyleStripe(stripe1.size, stripe2.size, true)); } if (stripe2.dxf && range.r1 + stripe1.size <= range.r2) { sheetMergedStyles.setTablePivotStyle( new Asc.Range(range.c1, range.r1 + stripe1.size, range.c2, range.r2), stripe2.dxf, new Asc.CTableStyleStripe(stripe2.size, stripe1.size, true)); } } dxf = style.firstColumn && style.firstColumn.dxf; if (styleInfo.showRowHeaders && dxf) { sheetMergedStyles.setTablePivotStyle(new Asc.Range(range.c1, range.r1, range.c1, range.r2), dxf); } dxf = style.headerRow && style.headerRow.dxf; if (styleInfo.showColHeaders && dxf) { sheetMergedStyles.setTablePivotStyle(new Asc.Range(range.c1, range.r1, range.c2, range.r1), dxf); } dxf = style.firstHeaderCell && style.firstHeaderCell.dxf; if (styleInfo.showColHeaders && styleInfo.showRowHeaders && dxf) { sheetMergedStyles.setTablePivotStyle(new Asc.Range(range.c1, range.r1, range.c1, range.r1), dxf); } if (pivot.asc_getColGrandTotals()) { dxf = style.lastColumn && style.lastColumn.dxf; if (dxf) { sheetMergedStyles.setTablePivotStyle(new Asc.Range(range.c2, range.r1, range.c2, range.r2), dxf); } } if (styleInfo.showRowHeaders) { for (i = range.r1 + 1; i < range.r2; ++i) { r = i - (range.r1 + 1); if (0 === r % 3) { dxf = style.firstRowSubheading; } if (dxf = (dxf && dxf.dxf)) { sheetMergedStyles.setTablePivotStyle(new Asc.Range(range.c1, i, range.c2, i), dxf); } } } if (pivot.asc_getRowGrandTotals()) { dxf = style.totalRow && style.totalRow.dxf; if (dxf) { sheetMergedStyles.setTablePivotStyle(new Asc.Range(range.c1, range.r2, range.c2, range.r2), dxf); } } } }; WorkbookView.prototype.getTableStyles = function (props, bPivotTable) { var wb = this.model; var t = this; var result = []; var canvas = document.createElement('canvas'); var tableStyleInfo; var pivotStyleInfo; var defaultStyles, styleThumbnailHeight, row, col = 5; var styleThumbnailWidth = window["IS_NATIVE_EDITOR"] ? 90 : 61; if(bPivotTable) { styleThumbnailHeight = 49; row = 8; defaultStyles = wb.TableStyles.DefaultStylesPivot; pivotStyleInfo = props; } else { styleThumbnailHeight = window["IS_NATIVE_EDITOR"] ? 48 : 46; row = 5; defaultStyles = wb.TableStyles.DefaultStyles; tableStyleInfo = new AscCommonExcel.TableStyleInfo(); if (props) { tableStyleInfo.ShowColumnStripes = props.asc_getBandVer(); tableStyleInfo.ShowFirstColumn = props.asc_getFirstCol(); tableStyleInfo.ShowLastColumn = props.asc_getLastCol(); tableStyleInfo.ShowRowStripes = props.asc_getBandHor(); tableStyleInfo.HeaderRowCount = props.asc_getFirstRow(); tableStyleInfo.TotalsRowCount = props.asc_getLastRow(); } else { tableStyleInfo.ShowColumnStripes = false; tableStyleInfo.ShowFirstColumn = false; tableStyleInfo.ShowLastColumn = false; tableStyleInfo.ShowRowStripes = true; tableStyleInfo.HeaderRowCount = true; tableStyleInfo.TotalsRowCount = false; } } if (AscBrowser.isRetina) { styleThumbnailWidth = AscCommon.AscBrowser.convertToRetinaValue(styleThumbnailWidth, true); styleThumbnailHeight = AscCommon.AscBrowser.convertToRetinaValue(styleThumbnailHeight, true); } canvas.width = styleThumbnailWidth; canvas.height = styleThumbnailHeight; var sizeInfo = {w: styleThumbnailWidth, h: styleThumbnailHeight, row: row, col: col}; var ctx = new Asc.DrawingContext({canvas: canvas, units: 0/*px*/, fmgrGraphics: this.fmgrGraphics, font: this.m_oFont}); var addStyles = function(styles, type, bEmptyStyle) { var style; for (var i in styles) { if ((bPivotTable && styles[i].pivot) || (!bPivotTable && styles[i].table)) { if (window["IS_NATIVE_EDITOR"]) { //TODO empty style? window["native"]["BeginDrawStyle"](type, i); } t._drawTableStyle(ctx, styles[i], tableStyleInfo, pivotStyleInfo, sizeInfo); if (window["IS_NATIVE_EDITOR"]) { window["native"]["EndDrawStyle"](); } else { style = new AscCommon.CStyleImage(); style.name = bEmptyStyle ? null : i; style.displayName = styles[i].displayName; style.type = type; style.image = canvas.toDataURL("image/png"); result.push(style); } } } }; addStyles(wb.TableStyles.CustomStyles, AscCommon.c_oAscStyleImage.Document); if (props) { //None style var emptyStyle = new Asc.CTableStyle(); emptyStyle.displayName = "None"; emptyStyle.pivot = bPivotTable; addStyles({null: emptyStyle}, AscCommon.c_oAscStyleImage.Default, true); } addStyles(defaultStyles, AscCommon.c_oAscStyleImage.Default); return result; }; WorkbookView.prototype._drawTableStyle = function (ctx, style, tableStyleInfo, pivotStyleInfo, size) { ctx.clear(); var w = size.w; var h = size.h; var row = size.row; var col = size.col; var startX = 1; var startY = 1; var ySize = (h - 1) - 2 * startY; var xSize = w - 2 * startX; var stepY = (ySize) / row; var stepX = (xSize) / col; var lineStepX = (xSize - 1) / 5; var whiteColor = new CColor(255, 255, 255); var blackColor = new CColor(0, 0, 0); var defaultColor; if (!style || !style.wholeTable || !style.wholeTable.dxf.font) { defaultColor = blackColor; } else { defaultColor = style.wholeTable.dxf.font.getColor(); } ctx.setFillStyle(whiteColor); ctx.fillRect(0, 0, xSize + 2 * startX, ySize + 2 * startY); var calculateLineVer = function(color, x, y1, y2) { ctx.beginPath(); ctx.setStrokeStyle(color); ctx.lineVer(x + startX, y1 + startY, y2 + startY); ctx.stroke(); ctx.closePath(); }; var calculateLineHor = function(color, x1, y, x2) { ctx.beginPath(); ctx.setStrokeStyle(color); ctx.lineHor(x1 + startX, y + startY, x2 + startX); ctx.stroke(); ctx.closePath(); }; var calculateRect = function(color, x1, y1, w, h) { ctx.beginPath(); ctx.setFillStyle(color); ctx.fillRect(x1 + startX, y1 + startY, w, h); ctx.closePath(); }; var bbox = new Asc.Range(0, 0, col - 1, row - 1); var sheetMergedStyles = new AscCommonExcel.SheetMergedStyles(); var hiddenManager = new AscCommonExcel.HiddenManager(null); if(pivotStyleInfo) { this.getPivotMergeStyle(sheetMergedStyles, bbox, style, pivotStyleInfo); } else if(tableStyleInfo) { style.initStyle(sheetMergedStyles, bbox, tableStyleInfo, null !== tableStyleInfo.HeaderRowCount ? tableStyleInfo.HeaderRowCount : 1, null !== tableStyleInfo.TotalsRowCount ? tableStyleInfo.TotalsRowCount : 0); } var compiledStylesArr = []; for (var i = 0; i < row; i++) { for (var j = 0; j < col; j++) { var color = null, prevStyle; var curStyle = AscCommonExcel.getCompiledStyle(sheetMergedStyles, hiddenManager, i, j); if(!compiledStylesArr[i]) { compiledStylesArr[i] = []; } compiledStylesArr[i][j] = curStyle; //fill color = curStyle && curStyle.fill && curStyle.fill.bg(); if(color) { calculateRect(color, j * stepX, i * stepY, stepX, stepY); } //borders //left prevStyle = (j - 1 >= 0) ? compiledStylesArr[i][j - 1] : null; color = AscCommonExcel.getMatchingBorder(prevStyle && prevStyle.border && prevStyle.border.r, curStyle && curStyle.border && curStyle.border.l); if(color && color.w > 0) { calculateLineVer(color.c, j * lineStepX, i * stepY, (i + 1) * stepY); } //right color = curStyle && curStyle.border && curStyle.border.r; if(color && color.w > 0) { calculateLineVer(color.c, (j + 1) * lineStepX, i * stepY, (i + 1) * stepY); } //top prevStyle = (i - 1 >= 0) ? compiledStylesArr[i - 1][j] : null; color = AscCommonExcel.getMatchingBorder(prevStyle && prevStyle.border && prevStyle.border.b, curStyle && curStyle.border && curStyle.border.t); if(color && color.w > 0) { calculateLineHor(color.c, j * stepX, i * stepY, (j + 1) * stepX); } //bottom color = curStyle && curStyle.border && curStyle.border.b; if(color && color.w > 0) { calculateLineHor(color.c, j * stepX, (i + 1) * stepY, (j + 1) * stepX); } //marks color = (curStyle && curStyle.font && curStyle.font.c) || defaultColor; calculateLineHor(color, j * lineStepX + 3, (i + 1) * stepY - stepY / 2, (j + 1) * lineStepX - 2); } } }; WorkbookView.prototype.IsSelectionUse = function () { return !this.getWorksheet().getSelectionShape(); }; WorkbookView.prototype.GetSelectionRectsBounds = function () { if (this.getWorksheet().getSelectionShape()) return null; var ws = this.getWorksheet(); var range = ws.model.selectionRange.getLast(); var type = range.getType(); var l = ws.getCellLeft(range.c1, 3); var t = ws.getCellTop(range.r1, 3); var offset = ws.getCellsOffset(3); return { X: asc.c_oAscSelectionType.RangeRow === type ? -offset.left : l - offset.left, Y: asc.c_oAscSelectionType.RangeCol === type ? -offset.top : t - offset.top, W: asc.c_oAscSelectionType.RangeRow === type ? offset.left : ws.getCellLeft(range.c2, 3) - l + ws.getColumnWidth(range.c2, 3), H: asc.c_oAscSelectionType.RangeCol === type ? offset.top : ws.getCellTop(range.r2, 3) - t + ws.getRowHeight(range.r2, 3), T: type }; }; WorkbookView.prototype.GetCaptionSize = function() { var offset = this.getWorksheet().getCellsOffset(3); return { W: offset.left, H: offset.top }; }; WorkbookView.prototype.ConvertXYToLogic = function (x, y) { return this.getWorksheet().ConvertXYToLogic(x, y); }; WorkbookView.prototype.ConvertLogicToXY = function (xL, yL) { return this.getWorksheet().ConvertLogicToXY(xL, yL) }; WorkbookView.prototype.changeFormatTableInfo = function (tableName, optionType, val) { var ws = this.getWorksheet(); return ws.af_changeFormatTableInfo(tableName, optionType, val); }; WorkbookView.prototype.applyAutoCorrectOptions = function (val) { var api = window["Asc"]["editor"]; var prevProps; switch (val) { case Asc.c_oAscAutoCorrectOptions.UndoTableAutoExpansion: { prevProps = { props: this.autoCorrectStore.props, cell: this.autoCorrectStore.cell, wsId: this.autoCorrectStore.wsId }; api.asc_Undo(); this.autoCorrectStore = prevProps; this.autoCorrectStore.props[0] = Asc.c_oAscAutoCorrectOptions.RedoTableAutoExpansion; this.toggleAutoCorrectOptions(true); break; } case Asc.c_oAscAutoCorrectOptions.RedoTableAutoExpansion: { prevProps = { props: this.autoCorrectStore.props, cell: this.autoCorrectStore.cell, wsId: this.autoCorrectStore.wsId }; api.asc_Redo(); this.autoCorrectStore = prevProps; this.autoCorrectStore.props[0] = Asc.c_oAscAutoCorrectOptions.UndoTableAutoExpansion; this.toggleAutoCorrectOptions(true); break; } } return true; }; WorkbookView.prototype.toggleAutoCorrectOptions = function (isSwitch, val) { if (isSwitch) { if (val) { this.autoCorrectStore = val; var options = new Asc.asc_CAutoCorrectOptions(); options.asc_setOptions(this.autoCorrectStore.props); options.asc_setCellCoord( this.getWorksheet().getCellCoord(this.autoCorrectStore.cell.c1, this.autoCorrectStore.cell.r1)); this.handlers.trigger("asc_onToggleAutoCorrectOptions", options); } else if (this.autoCorrectStore) { if (this.autoCorrectStore.wsId === this.model.getActiveWs().getId()) { var options = new Asc.asc_CAutoCorrectOptions(); options.asc_setOptions(this.autoCorrectStore.props); options.asc_setCellCoord( this.getWorksheet().getCellCoord(this.autoCorrectStore.cell.c1, this.autoCorrectStore.cell.r1)); this.handlers.trigger("asc_onToggleAutoCorrectOptions", options); } else { this.handlers.trigger("asc_onToggleAutoCorrectOptions"); } } } else { if(this.autoCorrectStore) { if (val) { this.autoCorrectStore = null; } this.handlers.trigger("asc_onToggleAutoCorrectOptions"); } } }; WorkbookView.prototype.savePagePrintOptions = function (arrPagesPrint) { var t = this; var viewMode = !this.Api.canEdit(); if(!arrPagesPrint) { return; } var callback = function (isSuccess) { if (false === isSuccess) { return; } for(var i in arrPagesPrint) { var ws = t.getWorksheet(parseInt(i)); ws.savePageOptions(arrPagesPrint[i], viewMode); window["Asc"]["editor"]._onUpdateLayoutMenu(ws.model.Id); } }; var lockInfoArr = []; var lockInfo; for(var i in arrPagesPrint) { lockInfo = this.getWorksheet(parseInt(i)).getLayoutLockInfo(); lockInfoArr.push(lockInfo); } if(viewMode) { callback(); } else { this.collaborativeEditing.lock(lockInfoArr, callback); } }; WorkbookView.prototype.cleanCutData = function (bDrawSelection, bCleanBuffer) { if(this.cutIdSheet) { var activeWs = this.wsViews[this.wsActive]; var ws = this.getWorksheetById(this.cutIdSheet); if(bDrawSelection && activeWs && ws && activeWs.model.Id === ws.model.Id) { activeWs.cleanSelection(); } if(ws) { ws.cutRange = null; } this.cutIdSheet = null; if(bDrawSelection && activeWs && ws && activeWs.model.Id === ws.model.Id) { activeWs.updateSelection(); } //ms чистит буфер, если происходят какие-то изменения в документе с посвеченной областью вырезать //мы в данном случае не можем так делать, поскольку не можем прочесть информацию из буфера и убедиться, что //там именно тот вырезанный фрагмент. тем самым можем затереть какую-то важную информацию if(bCleanBuffer) { AscCommon.g_clipboardBase.ClearBuffer(); } } }; WorkbookView.prototype.updateGroupData = function () { this.getWorksheet()._updateGroups(true); this.getWorksheet()._updateGroups(null); }; WorkbookView.prototype.pasteSheet = function (base64, insertBefore, name, callback) { var t = this; var tempWorkbook = new AscCommonExcel.Workbook(); tempWorkbook.setCommonIndexObjectsFrom(this.model); var pasteProcessor = AscCommonExcel.g_clipboardExcel.pasteProcessor; var aPastedImages = pasteProcessor._readExcelBinary(base64.split('xslData;')[1], tempWorkbook, true); var pastedWs = tempWorkbook.aWorksheets[0]; var newFonts = {}; newFonts = tempWorkbook.generateFontMap2(); newFonts = pasteProcessor._convertFonts(newFonts); for (var i = 0; i < pastedWs.Drawings.length; i++) { pastedWs.Drawings[i].graphicObject.getAllFonts(newFonts); } var doCopy = function() { History.Create_NewPoint(); var renameParams = t.model.copyWorksheet(0, insertBefore, name, undefined, undefined, undefined, pastedWs); callback(renameParams); }; var api = window["Asc"]["editor"]; api._loadFonts(newFonts, function () { if (aPastedImages && aPastedImages.length) { pasteProcessor._loadImagesOnServer(aPastedImages, function () { doCopy(); }); } else { doCopy(); } }); }; //------------------------------------------------------------export--------------------------------------------------- window['AscCommonExcel'] = window['AscCommonExcel'] || {}; window["AscCommonExcel"].WorkbookView = WorkbookView; })(window);
[se] Fix Simplify
cell/view/WorkbookView.js
[se] Fix
<ide><path>ell/view/WorkbookView.js <ide> }; <ide> <ide> // Поиск текста в листе <del> WorkbookView.prototype.findCellText = function(options) { <add> WorkbookView.prototype.findCellText = function (options) { <add> this.closeCellEditor(); <ide> // Для поиска эта переменная не нужна (но она может остаться от replace) <ide> options.selectionRange = null; <ide> <del> var ws = this.getWorksheet(); <del> // Останавливаем ввод данных в редакторе ввода <del> if (this.getCellEditMode()) { <del> this._onStopCellEditing(); <del> } <del> <ide> var result = this.model.findCellText(options); <ide> if (result) { <add> var ws = this.getWorksheet(); <ide> var range = new Asc.Range(result.col, result.row, result.col, result.row); <ide> options.findInSelection ? ws.setActiveCell(result) : ws.setSelection(range); <ide> return true;
JavaScript
mit
d2a2be157c7f3727359602e5cb06d5d2199ae523
0
OperationSpark/notes
$(function () { window.opspark = window.opspark || {}; window.opspark.notes = window.opspark.notes || {}; var notes = window.opspark.notes; notes.show = function (prependTo, file) { prependTo = prependTo ? prependTo : '#container'; file = file ? file : '.notes/directions.html'; if (window.location.href.match(/c9[\w-_]*\.io|localhost|127\.0\.0\.1|file\:\/\/\//)) { $('<a/>') .attr('id', 'btnDirections') .attr('href', file) .attr('target', '_blank') .attr('type', 'button') .addClass('btn btn-primary btn-sm btn-block') .css('margin-top', '5px') .css('margin-bottom', '5px') .html('Directions...') .prependTo($(prependTo)); } }; notes.hide = function (btnId) { btnId = btnId ? btnId : '#btnDirections'; $(btnId).detach(); }; });
notes.js
$(function () { window.opspark = window.opspark || {}; window.opspark.notes = window.opspark.notes || {}; var notes = window.opspark.notes; notes.show = function (prependTo, file) { prependTo = prependTo ? prependTo : '#container'; file = file ? file : '.notes/directions.html'; if (window.location.href.match(/c9\.io|github_io|localhost|127\.0\.0\.1|file\:\/\/\//)) { $('<a/>') .attr('id', 'btnDirections') .attr('href', file) .attr('target', '_blank') .attr('type', 'button') .addClass('btn btn-primary btn-sm btn-block') .css('margin-top', '5px') .css('margin-bottom', '5px') .html('Directions...') .prependTo($(prependTo)); } }; notes.hide = function (btnId) { btnId = btnId ? btnId : '#btnDirections'; $(btnId).detach(); }; });
* fix valid show-notes url regex
notes.js
* fix valid show-notes url regex
<ide><path>otes.js <ide> notes.show = function (prependTo, file) { <ide> prependTo = prependTo ? prependTo : '#container'; <ide> file = file ? file : '.notes/directions.html'; <del> if (window.location.href.match(/c9\.io|github_io|localhost|127\.0\.0\.1|file\:\/\/\//)) { <add> if (window.location.href.match(/c9[\w-_]*\.io|localhost|127\.0\.0\.1|file\:\/\/\//)) { <ide> $('<a/>') <ide> .attr('id', 'btnDirections') <ide> .attr('href', file)
Java
mit
dfa41b9e1a221517b7714320dd5c36076868cef3
0
yzhnasa/TASSEL-iRods,yzhnasa/TASSEL-iRods,yzhnasa/TASSEL-iRods,yzhnasa/TASSEL-iRods
package net.maizegenetics.gbs.maps; import cern.colt.GenericSorting; import cern.colt.Swapper; import cern.colt.function.IntComparator; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import net.maizegenetics.gbs.tagdist.AbstractTags; import net.maizegenetics.gbs.tagdist.TagCountMutable; import net.maizegenetics.gbs.tagdist.Tags; import net.maizegenetics.gbs.util.SAMUtils; import net.maizegenetics.gbs.util.BaseEncoder; import net.maizegenetics.pal.alignment.Alignment; import net.maizegenetics.pal.alignment.AlignmentUtils; import net.maizegenetics.pal.alignment.ImportUtils; import net.maizegenetics.pal.alignment.Locus; import net.maizegenetics.pal.alignment.NucleotideAlignmentConstants; import net.maizegenetics.util.MultiMemberGZIPInputStream; /** * Holds tag data compressed in long and a physical position. This can have two * variations either include redundant positions or only unique positions. If * redundant than tags that map to multiple regions should be placed adjacently * * Default 40 bytes per position. If we have 10,000,000 million positions then * this will be at 400M byte data structure. * * User: ed */ public class TagsOnPhysicalMap extends AbstractTagsOnPhysicalMap { int[] endPosition; // chromosomal position of the common adapter end of the tag (smaller than bestStartPos if tag matches minus bestStrand) // 4 bytes byte[] divergence; // number of diverging bp (edit distance) from reference, unknown = Byte.MIN_VALUE byte[] dcoP, mapP; //Round(Log2(P)), unknown Byte.MIN_VALUE boolean redundantTags = true; // this field has not been utilized yet public static enum SAMFormat { BWA, BOWTIE2 }; // Supported SAM formats (each program defines some custom features) private SAMFormat mySAMFormat = SAMFormat.BWA; // BWA by default public TagsOnPhysicalMap() { } public TagsOnPhysicalMap(String inFile, boolean binary) { if (binary) { readBinaryFile(new File(inFile)); } else { readTextFile(new File(inFile)); } initPhysicalSort(); } public TagsOnPhysicalMap(int rows) { initMatrices(rows); } public TagsOnPhysicalMap(int rows, int tagLengthInLong, int maxVariants) { this.tagLengthInLong = tagLengthInLong; this.myMaxVariants = maxVariants; initMatrices(rows); } public TagsOnPhysicalMap(Tags readList) { tagLengthInLong = readList.getTagSizeInLong(); initMatrices(readList.getTagCount()); for (int i = 0; i < readList.getTagCount(); i++) { for (int j = 0; j < tagLengthInLong; j++) { tags[j][i] = readList.getTag(i)[j]; } } } public TagsOnPhysicalMap(TagsOnPhysicalMap oldTOPM, boolean filterDuplicates) { this.tagLengthInLong = oldTOPM.tagLengthInLong; this.myMaxVariants = oldTOPM.myMaxVariants; oldTOPM.sortTable(true); int uniqueCnt = 1; for (int i = 1; i < oldTOPM.getSize(); i++) { if (!Arrays.equals(oldTOPM.getTag(i - 1), oldTOPM.getTag(i))) { uniqueCnt++; } } System.out.println("The Physical Map File has UniqueTags:" + uniqueCnt + " TotalLocations:" + oldTOPM.getSize()); initMatrices(uniqueCnt); this.myNumTags = uniqueCnt; uniqueCnt = 0; this.copyTagMapRow(oldTOPM, 0, 0, filterDuplicates); for (int i = 1; i < oldTOPM.getTagCount(); i++) { // System.out.println(this.getTag(uniqueCnt)[1]+":"+ oldTOPM.getTag(i)[1]); // System.out.println(":"+ oldTOPM.getTag(i)[1]); if (!Arrays.equals(this.getTag(uniqueCnt), oldTOPM.getTag(i))) { uniqueCnt++; // copyTagMapRow(oldTOPM, i, uniqueCnt, filterDuplicates); } else { // System.out.printf("i=%d uniqueCnt=%d %n",i, uniqueCnt); } copyTagMapRow(oldTOPM, i, uniqueCnt, filterDuplicates); } initPhysicalSort(); } void initMatrices(int rows) { tags = new long[tagLengthInLong][rows]; // 16 bytes tagLength = new byte[rows]; // length of tag (number of bases) // 1 byte multimaps = new byte[rows]; // number of locations this tagSet maps to, unknown = Byte.MIN_VALUE bestChr = new int[rows]; // 4 bytes bestStrand = new byte[rows]; // 1 = same sense as reference FASTA file. -1 = opposite sense. unknown = Byte.MIN_VALUE // 1 byte bestStartPos = new int[rows]; // chromosomal position of the barcoded end of the tag // 4 bytes endPosition = new int[rows]; // chromosomal position of the common adapter end of the tag (smaller than bestStartPos if tag matches minus bestStrand) // 4 bytes divergence = new byte[rows]; // number of diverging bp from reference, unknown = Byte.MIN_VALUE variantOffsets = new byte[rows][]; // offset from position minimum, maximum number of variants is defined above // myMaxVariants bytes variantDefs = new byte[rows][]; // allele state - A, C, G, T or some indel definition // myMaxVariants bytes dcoP = new byte[rows]; mapP = new byte[rows]; // Round(Log2(P)), unknown = Byte.MIN_VALUE; if these disagree with the location, then set the p to negative myNumTags = rows; // try{ // System.out.println("Sleeping after memory creation"); // Thread.sleep(100000); // } catch(Exception e) { // System.out.println(e); // } } public void expandMaxVariants(int newMaxVariants) { if (newMaxVariants <= this.myMaxVariants) { System.out.println("TagsOnPhysicalMap.expandMaxVariants(" + newMaxVariants + ") not performed because newMaxVariants (" + newMaxVariants + ") <= current maxVariants (" + this.myMaxVariants + ")"); return; } int oldMaxVariants = this.myMaxVariants; byte[][] newVariantPosOff = new byte[myNumTags][newMaxVariants]; byte[][] newVariantDef = new byte[myNumTags][newMaxVariants]; for (int t = 0; t < myNumTags; ++t) { for (int v = 0; v < this.myMaxVariants; ++v) { newVariantPosOff[t][v] = this.variantOffsets[t][v]; newVariantDef[t][v] = this.variantDefs[t][v]; } for (int v = this.myMaxVariants; v < newMaxVariants; ++v) { newVariantPosOff[t][v] = Byte.MIN_VALUE; newVariantDef[t][v] = Byte.MIN_VALUE; } } this.myMaxVariants = newMaxVariants; this.variantOffsets = newVariantPosOff; this.variantDefs = newVariantDef; System.out.println("TagsOnPhysicalMap maxVariants expanded from " + oldMaxVariants + " to " + newMaxVariants); } /** * This helps collapse identical reads from different regions of the genome * together. * * @param sourceTOPM * @param sourceRow * @param destRow * @param merge */ public void copyTagMapRow(TagsOnPhysicalMap sourceTOPM, int sourceRow, int destRow, boolean merge) { boolean overwrite = true; long[] ctag = sourceTOPM.getTag(sourceRow); if (Arrays.equals(ctag, this.getTag(destRow)) && merge) { overwrite = false; } for (int i = 0; i < tagLengthInLong; i++) { tags[i][destRow] = ctag[i]; } if (overwrite) { tagLength[destRow] = sourceTOPM.tagLength[sourceRow]; multimaps[destRow] = sourceTOPM.multimaps[sourceRow]; bestChr[destRow] = sourceTOPM.bestChr[sourceRow]; bestStrand[destRow] = sourceTOPM.bestStrand[sourceRow]; bestStartPos[destRow] = sourceTOPM.bestStartPos[sourceRow]; endPosition[destRow] = sourceTOPM.endPosition[sourceRow]; divergence[destRow] = sourceTOPM.divergence[sourceRow]; for (int j = 0; j < myMaxVariants; j++) { variantOffsets[destRow][j] = sourceTOPM.variantOffsets[sourceRow][j]; variantDefs[destRow][j] = sourceTOPM.variantOffsets[sourceRow][j]; } dcoP[destRow] = sourceTOPM.dcoP[sourceRow]; mapP[destRow] = sourceTOPM.mapP[sourceRow]; } else { //tagLength[destRow]=tagLength[sourceRow]; if ((bestChr[destRow] != sourceTOPM.bestChr[sourceRow]) || (bestStrand[destRow] != sourceTOPM.bestStrand[sourceRow]) || (bestStartPos[destRow] != sourceTOPM.bestStartPos[sourceRow]) || (endPosition[destRow] != sourceTOPM.endPosition[sourceRow])) { multimaps[destRow] += sourceTOPM.multimaps[sourceRow]; bestChr[destRow] = bestStrand[destRow] = Byte.MIN_VALUE; bestStartPos[destRow] = endPosition[destRow] = Integer.MIN_VALUE; } //dcoP[destRow]=dcoP[sourceRow]; //mapP[destRow]=mapP[sourceRow]; } } public long sortTable(boolean byHaplotype) { System.out.print("Starting Read Table Sort ..."); if (byHaplotype == false) { //TODO change the signature at some time System.out.print("ERROR: Position sorting has been eliminated ..."); return -1; } long time = System.currentTimeMillis(); GenericSorting.quickSort(0, tags[0].length, this, this); long totalTime = System.currentTimeMillis() - time; System.out.println("Done in " + totalTime + "ms"); initPhysicalSort(); return totalTime; } protected void readBinaryFile(File currentFile) { int tagsInput = 0; try { DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(currentFile), 65536)); System.out.println("File = " + currentFile); myNumTags = dis.readInt(); // myNumTags=100000; tagLengthInLong = dis.readInt(); myMaxVariants = dis.readInt(); initMatrices(myNumTags); for (int row = 0; row < myNumTags; row++) { for (int j = 0; j < tagLengthInLong; j++) { tags[j][row] = dis.readLong(); } tagLength[row] = dis.readByte(); multimaps[row] = dis.readByte(); bestChr[row] = dis.readInt(); bestStrand[row] = dis.readByte(); bestStartPos[row] = dis.readInt(); endPosition[row] = dis.readInt(); divergence[row] = dis.readByte(); byte[] currVD=new byte[myMaxVariants]; byte[] currVO=new byte[myMaxVariants]; int numWithData=0; for (int j = 0; j < myMaxVariants; j++) { currVO[j] = dis.readByte(); currVD[j] = dis.readByte(); if((currVD[j]>0xf)&&(AlignmentUtils.isHeterozygous(currVD[j]))) {//ascii bytes need to be converted to TASSEL 4 // System.out.printf("row:%d vd:%d %n", row, variantDefs[row][j]); currVD[j]=NucleotideAlignmentConstants.getNucleotideAlleleByte(String.valueOf((char)currVD[j])); } if(currVO[j]!=TOPMInterface.BYTE_MISSING) numWithData++; } if(numWithData>0) { variantDefs[row]=Arrays.copyOf(currVD, numWithData); variantOffsets[row]=Arrays.copyOf(currVO, numWithData); } dcoP[row] = dis.readByte(); mapP[row] = dis.readByte(); tagsInput++; if (row % 1000000 == 0) { System.out.println("TagMapFile Row Read:" + row); } } dis.close(); } catch (Exception e) { System.out.println("Error tagsInput=" + tagsInput + " e=" + e); } System.out.println("Count of Tags=" + tagsInput); } public boolean variantsDefined(int tagIndex) { for (int i = 0; i < myMaxVariants; i++) { if ((variantOffsets[tagIndex][i] != Byte.MIN_VALUE) && (variantDefs[tagIndex][i] != Byte.MIN_VALUE)) { return true; } } return false; } public void readTextFile(File inFile) { System.out.println("Reading tag alignment from:" + inFile.toString()); String[] inputLine = {"NotRead"}; try { BufferedReader br = new BufferedReader(new FileReader(inFile), 65536); inputLine = br.readLine().split("\t"); //Parse header line (Number of tags, number of Long ints per tag, maximum variant bases per tag). this.myNumTags = Integer.parseInt(inputLine[0]); this.tagLengthInLong = Integer.parseInt(inputLine[1]); this.myMaxVariants = Integer.parseInt(inputLine[2]); // initMatrices(9000000); initMatrices(myNumTags); //Loop through remaining lines, store contents in a series of arrays indexed by row number for (int row = 0; row < myNumTags; row++) { inputLine = br.readLine().split("\t"); int c = 0; long[] tt = BaseEncoder.getLongArrayFromSeq(inputLine[c++]); for (int j = 0; j < tt.length; j++) { tags[j][row] = tt[j]; } tagLength[row] = parseByteWMissing(inputLine[c++]); multimaps[row] = parseByteWMissing(inputLine[c++]); bestChr[row] = parseIntWMissing(inputLine[c++]); bestStrand[row] = parseByteWMissing(inputLine[c++]); bestStartPos[row] = parseIntWMissing(inputLine[c++]); endPosition[row] = parseIntWMissing(inputLine[c++]); divergence[row] = parseByteWMissing(inputLine[c++]); byte[] currVD=new byte[myMaxVariants]; byte[] currVO=new byte[myMaxVariants]; int numWithData=0; for (int j = 0; j < myMaxVariants; j++) { currVO[j] = parseByteWMissing(inputLine[c++]); currVD[j] = parseCharWMissing(inputLine[c++]); if(currVO[j]!=TOPMInterface.BYTE_MISSING) numWithData++; } variantDefs[row]=Arrays.copyOf(currVD, numWithData); variantOffsets[row]=Arrays.copyOf(currVO, numWithData); dcoP[row] = parseByteWMissing(inputLine[c++]); mapP[row] = parseByteWMissing(inputLine[c++]); if (row % 1000000 == 0) { System.out.println("Row Read:" + row); } } } catch (Exception e) { System.out.println("Catch in reading TagOnPhysicalMap file e=" + e); e.printStackTrace(); System.out.println("Line:"+Arrays.toString(inputLine)); } System.out.println("Number of tags in file:" + myNumTags); } @Override public int getReadIndexForPositionIndex(int posIndex) { return indicesOfSortByPosition[posIndex]; } @Override public int[] getPositionArray(int index) { int[] r = {bestChr[index], bestStrand[index], bestStartPos[index]}; return r; } // public int getReadIndex(byte chr, byte bestStrand, int posMin) { // // dep_ReadWithPositionInfo querySHP=new dep_ReadWithPositionInfo(bestChr, bestStrand, posMin); // // PositionComparator posCompare = new PositionComparator(); // // int hit1=Arrays.binarySearch(shp, querySHP, posCompare); // int hit1=-1; //redo // return hit1; // } public static byte parseCharWMissing(String s) { if (s.equals("*")) { return Byte.MIN_VALUE; } try{ byte r=NucleotideAlignmentConstants.getNucleotideAlleleByte(s); return r; } catch(IllegalArgumentException e) { int i = Integer.parseInt(s); if (i > 127) {return 127;} byte r=NucleotideAlignmentConstants.getNucleotideAlleleByte(String.valueOf((char)i)); return r; } } public static byte parseByteWMissing(String s) { if (s.equals("*")) { return Byte.MIN_VALUE; } int i; try { i = Integer.parseInt(s); if (i > 127) { return 127; } return (byte) i; } catch (NumberFormatException nf) { return Byte.MIN_VALUE; } } public static int parseIntWMissing(String s) { if (s.equals("*")) { return Integer.MIN_VALUE; } int i; try { i = Integer.parseInt(s); return i; } catch (NumberFormatException nf) { return Integer.MIN_VALUE; } } @Override public byte getMultiMaps(int index) { return multimaps[index]; } @Override public int getEndPosition(int index) { return endPosition[index]; } @Override public byte getDivergence(int index) { return divergence[index]; } @Override public byte getMapP(int index) { return mapP[index]; } @Override public byte getDcoP(int index) { return dcoP[index]; } @Override public void setChromoPosition(int index, int chromosome, byte strand, int positionMin, int positionMax) { this.bestChr[index] = chromosome; this.bestStrand[index] = strand; this.bestStartPos[index] = positionMin; this.endPosition[index] = positionMax; } @Override public void setDivergence(int index, byte divergence) { this.divergence[index] = divergence; } @Override public void setMapP(int index, byte mapP) { this.mapP[index] = mapP; } @Override public void setMapP(int index, double mapP) { if (Double.isInfinite(mapP)) { this.mapP[index] = Byte.MAX_VALUE; return; } if (Double.isNaN(mapP) || (mapP < 0) || (mapP > 1)) { this.mapP[index] = Byte.MIN_VALUE; return; } if (mapP < 1e-126) { this.mapP[index] = Byte.MAX_VALUE; return; } this.mapP[index] = (byte) (-Math.round(Math.log10(mapP))); } @Override public int addVariant(int tagIndex, byte offset, byte base) { for (int i = 0; i < myMaxVariants; i++) { if ((variantOffsets[tagIndex][i] == Byte.MIN_VALUE) && (variantDefs[tagIndex][i] == Byte.MIN_VALUE)) { variantOffsets[tagIndex][i] = offset; variantDefs[tagIndex][i] = base; return i; } } return -1; //no free space } /** * Decodes bitwise flags from the code in SAM field 3. The code is a 32-bit * integer, so I boolean AND the flag value with the code, and compare the * result with the flag value. If they are equal, that means all bits set in * the flag number were set in the code (i.e., that flag is turned on). */ private boolean flagSet(int code, int flag) { int flagValue = 1 << flag; //1<<flag is equivalent to 2^flag return ((code & flagValue) == flagValue); } /** * Reads SAM files output from BWA or bowtie2 */ public void readSAMFile(String inputFileName, int tagLengthInLong) { System.out.println("Reading SAM format tag alignment from: " + inputFileName); this.tagLengthInLong = tagLengthInLong; String inputStr = "Nothing has been read from the file yet"; int nHeaderLines = countTagsInSAMfile(inputFileName); // detects if the file is bowtie2, initializes topm matrices int tagIndex = Integer.MIN_VALUE; try { BufferedReader br; if (inputFileName.endsWith(".gz")) { br = new BufferedReader(new InputStreamReader(new MultiMemberGZIPInputStream(new FileInputStream(new File(inputFileName))))); } else { br = new BufferedReader(new FileReader(new File(inputFileName)), 65536); } for (int i = 0; i < nHeaderLines; i++) { br.readLine(); } // Skip over the header for (tagIndex = 0; tagIndex < myNumTags; tagIndex++) { inputStr = br.readLine(); parseSAMAlignment(inputStr, tagIndex); if (tagIndex % 1000000 == 0) { System.out.println("Read " + tagIndex + " tags."); } } br.close(); } catch (Exception e) { System.out.println("\n\nCatch in reading SAM alignment file at tag " + tagIndex + ":\n\t" + inputStr + "\nError: " + e + "\n\n"); e.printStackTrace(); System.exit(1); } } private int countTagsInSAMfile(String inputFileName) { mySAMFormat = SAMFormat.BWA; // format is BWA by default myNumTags = 0; int nHeaderLines = 0; String currLine = null; try { String[] inputLine; ArrayList<String> chrNames = new ArrayList<String>(); BufferedReader br; if (inputFileName.endsWith(".gz")) { br = new BufferedReader(new InputStreamReader(new MultiMemberGZIPInputStream(new FileInputStream(new File(inputFileName))))); } else { br = new BufferedReader(new FileReader(new File(inputFileName)), 65536); } while ((currLine = br.readLine()) != null) { inputLine = currLine.split("\\s"); if (inputLine[0].contains("@")) { //SAM files produced by Bowtie2 contain the string "@PG ID:bowtie2 PN:bowtie2 " if (inputLine[1].contains("bowtie2")) { mySAMFormat = SAMFormat.BOWTIE2; } nHeaderLines++; } else { String chr = inputLine[2]; if (!chrNames.contains(chr)) { chrNames.add(chr); } myNumTags++; if (myNumTags % 1000000 == 0) { System.out.println("Counted " + myNumTags + " tags."); } } } br.close(); System.out.println("Found " + myNumTags + " tags in SAM file. Assuming " + mySAMFormat + " file format."); } catch (Exception e) { System.out.println("Catch in counting lines of alignment file at line " + currLine + ": " + e); e.printStackTrace(); System.exit(1); } initMatrices(myNumTags); return nHeaderLines; } private void parseSAMAlignment(String inputStr, int tagIndex) { String[] inputLine = inputStr.split("\t"); int name = 0, flag = 1, chr = 2, pos = 3, cigar = 5, tagS = 9; // column indices in inputLine String nullS = this.getNullTag(); if ((Integer.parseInt(inputLine[flag]) & 4) == 4) { // bit 0x4 (= 2^2 = 4) is set: NO ALIGNMENT recordLackOfSAMAlign(tagIndex, inputLine[tagS], inputLine[name], nullS); } else { // aligns to one or more positions HashMap<String, Integer> SAMFields = parseOptionalFieldsFromSAMAlignment(inputLine); byte bestHits = (byte) Math.min(SAMFields.get("nBestHits"), Byte.MAX_VALUE); byte editDist = (byte) Math.min(SAMFields.get("editDist"), Byte.MAX_VALUE); byte currStrand = (Integer.parseInt(inputLine[flag]) == 16) ? (byte) -1 : (byte) 1; recordSAMAlign( tagIndex, inputLine[tagS], inputLine[name], nullS, bestHits, inputLine[chr], currStrand, Integer.parseInt(inputLine[pos]), inputLine[cigar], editDist); } } private HashMap<String, Integer> parseOptionalFieldsFromSAMAlignment(String[] inputLine) { HashMap<String, Integer> SAMFields = new HashMap<String, Integer>(); if (mySAMFormat == SAMFormat.BWA) { for (int field = 11; field < inputLine.length; field++) { // Loop through all the optional field of the SAM alignment if (inputLine[field].regionMatches(0, "X0", 0, 2)) { // X0 = SAM format for # of "high-quality" alignments of this query. Specific to BWA. SAMFields.put("nBestHits", Integer.parseInt(inputLine[field].split(":")[2])); } else if (inputLine[field].regionMatches(0, "NM", 0, 2)) { // NM = SAM format for edit distance to the reference. Common to BWA and Bowtie2. SAMFields.put("editDist", Integer.parseInt(inputLine[field].split(":")[2])); } } } else { // bowtie2 -M format for (int field = 11; field < inputLine.length; field++) { // Loop through all the optional field of the SAM alignment if (inputLine[field].regionMatches(0, "AS", 0, 2)) { // AS = SAM format for alignment score of the best alignment. Specific to bowtie2. SAMFields.put("bestScore", Integer.parseInt(inputLine[field].split(":")[2])); } else if (inputLine[field].regionMatches(0, "XS", 0, 2)) { // XS = SAM format for alignment score of 2nd best alignment. Specific to bowtie2. SAMFields.put("nextScore", Integer.parseInt(inputLine[field].split(":")[2])); } else if (inputLine[field].regionMatches(0, "NM", 0, 2)) { // NM = SAM format for edit distance to the reference. Common to BWA and Bowtie2. SAMFields.put("editDist", Integer.parseInt(inputLine[field].split(":")[2])); } } if (SAMFields.containsKey("bestScore")) { if (SAMFields.containsKey("nextScore")) { if (SAMFields.get("bestScore") > SAMFields.get("nextScore")) { SAMFields.put("nBestHits", 1); } else { SAMFields.put("nBestHits", 99); // 99 will stand for an unknown # of multiple hits } } else { SAMFields.put("nBestHits", 1); } } } return SAMFields; } private void recordLackOfSAMAlign(int tagIndex, String tagS, String tagName, String nullS) { recordTagFromSAMAlignment(tagIndex, tagS, tagName, nullS, (byte) 1); multimaps[tagIndex] = 0; // or should this be unknown = Byte.MIN_VALUE??? bestChr[tagIndex] = Integer.MIN_VALUE; bestStrand[tagIndex] = Byte.MIN_VALUE; bestStartPos[tagIndex] = Integer.MIN_VALUE; endPosition[tagIndex] = Integer.MIN_VALUE; divergence[tagIndex] = Byte.MIN_VALUE; for (int var = 0; var < myMaxVariants; var++) { variantOffsets[tagIndex][var] = Byte.MIN_VALUE; variantDefs[tagIndex][var] = Byte.MIN_VALUE; } dcoP[tagIndex] = Byte.MIN_VALUE; mapP[tagIndex] = Byte.MIN_VALUE; } private void recordSAMAlign(int tagIndex, String tagS, String tagName, String nullS, byte nBestHits, String chrS, byte strand, int pos, String cigar, byte editDist) { recordTagFromSAMAlignment(tagIndex, tagS, tagName, nullS, strand); multimaps[tagIndex] = nBestHits; if (nBestHits == 1) { bestChr[tagIndex] = parseChrString(chrS); this.bestStrand[tagIndex] = strand; recordStartEndPostionFromSAMAlign(tagIndex, strand, pos, cigar); } else { bestChr[tagIndex] = Integer.MIN_VALUE; this.bestStrand[tagIndex] = Byte.MIN_VALUE; bestStartPos[tagIndex] = Integer.MIN_VALUE; endPosition[tagIndex] = Integer.MIN_VALUE; } divergence[tagIndex] = editDist; for (int var = 0; var < myMaxVariants; var++) { variantOffsets[tagIndex][var] = Byte.MIN_VALUE; variantDefs[tagIndex][var] = Byte.MIN_VALUE; } dcoP[tagIndex] = Byte.MIN_VALUE; mapP[tagIndex] = Byte.MIN_VALUE; } private void recordTagFromSAMAlignment(int tagIndex, String tagS, String tagName, String nullS, byte strand) { if (strand == -1) { tagS = BaseEncoder.getReverseComplement(tagS); } if (tagS.length() < tagLengthInLong * 32) { // pad with polyA tagS = tagS + nullS; tagS = tagS.substring(0, (tagLengthInLong * 32)); } long[] tagSequence = BaseEncoder.getLongArrayFromSeq(tagS); for (int chunk = 0; chunk < tagLengthInLong; chunk++) { tags[chunk][tagIndex] = tagSequence[chunk]; } tagName = tagName.replaceFirst("count=[0-9]+", ""); tagName = tagName.replaceFirst("length=", ""); tagLength[tagIndex] = Byte.parseByte(tagName); } private int parseChrString(String chrS) { int chr = Integer.MIN_VALUE; chrS = chrS.replace("chr", ""); try { chr = Integer.parseInt(chrS); } catch (NumberFormatException e) { System.out.println("\n\nSAMConverterPlugin detected a non-numeric chromosome name: " + chrS + "\n\nPlease change the FASTA headers in your reference genome sequence to integers " + "(>1, >2, >3, etc.) OR to 'chr' followed by an integer (>chr1, >chr2, >chr3, etc.)\n\n"); System.exit(1); } return chr; } private void recordStartEndPostionFromSAMAlign(int tagIndex, byte strand, int pos, String cigar) { int[] alignSpan = SAMUtils.adjustCoordinates(cigar, pos); try { if (strand == 1) { bestStartPos[tagIndex] = alignSpan[0]; endPosition[tagIndex] = alignSpan[1]; } else if (strand == -1) { bestStartPos[tagIndex] = alignSpan[1]; endPosition[tagIndex] = alignSpan[0]; } else { throw new Exception("Unexpected value for strand: " + strand + "(expect 1 or -1)"); } } catch (Exception e) { System.out.println("Error in recordStartEndPostionFromSAMAlign: " + e); e.printStackTrace(); System.exit(1); } } @Override public void swap(int index1, int index2) { long tl; for (int i = 0; i < tagLengthInLong; i++) { tl = tags[i][index1]; tags[i][index1] = tags[i][index2]; tags[i][index2] = tl; } int tb; tb = tagLength[index1]; tagLength[index1] = tagLength[index2]; tagLength[index2] = (byte) tb; tb = multimaps[index1]; multimaps[index1] = multimaps[index2]; multimaps[index2] = (byte) tb; tb = bestChr[index1]; bestChr[index1] = bestChr[index2]; bestChr[index2] = tb; tb = bestStrand[index1]; bestStrand[index1] = bestStrand[index2]; bestStrand[index2] = (byte) tb; int ti; ti = bestStartPos[index1]; bestStartPos[index1] = bestStartPos[index2]; bestStartPos[index2] = ti; ti = endPosition[index1]; endPosition[index1] = endPosition[index2]; endPosition[index2] = ti; tb = divergence[index1]; divergence[index1] = divergence[index2]; divergence[index2] = (byte) tb; for (int j = 0; j < myMaxVariants; j++) { tb = variantOffsets[index1][j]; variantOffsets[index1][j] = variantOffsets[index2][j]; variantOffsets[index2][j] = (byte) tb; tb = variantDefs[index1][j]; variantDefs[index1][j] = variantDefs[index2][j]; variantDefs[index2][j] = (byte) tb; } tb = dcoP[index1]; dcoP[index1] = dcoP[index2]; dcoP[index2] = (byte) tb; tb = mapP[index1]; mapP[index1] = mapP[index2]; mapP[index2] = (byte) tb; } @Override public int compare(int index1, int index2) { for (int i = 0; i < tagLengthInLong; i++) { if (tags[i][index1] < tags[i][index2]) { return -1; } if (tags[i][index1] > tags[i][index2]) { return 1; } } if (bestChr[index1] < bestChr[index2]) { return -1; } if (bestChr[index1] > bestChr[index2]) { return 1; } if (bestStartPos[index1] < bestStartPos[index2]) { return -1; } if (bestStartPos[index1] > bestStartPos[index2]) { return 1; } if (bestStrand[index1] < bestStrand[index2]) { return -1; } if (bestStrand[index1] > bestStrand[index2]) { return 1; } return 0; } @Override public void setVariantDef(int tagIndex, int variantIndex, byte def) { variantDefs[tagIndex][variantIndex] = (byte) NucleotideAlignmentConstants.NUCLEOTIDE_ALLELES[0][def].charAt(0); } @Override public void setVariantPosOff(int tagIndex, int variantIndex, byte offset) { variantOffsets[tagIndex][variantIndex] = offset; } @Override public int getMaxNumVariants() { return myMaxVariants; } /** * First, find unique tags by concatenating them into a TagCountMutable * object and collapsing duplicate rows. */ private static TagsOnPhysicalMap uniqueTags(String[] filenames) { //Find dimensions of concatenated file int tagLengthInLong = 0, maxVariants = 0, tagNum = 0; for (String name : filenames) { TagsOnPhysicalMap file = new TagsOnPhysicalMap(name, true); tagNum += file.myNumTags; if (file.myMaxVariants > maxVariants) { maxVariants = file.myMaxVariants; } if (file.getTagSizeInLong() > tagLengthInLong) { tagLengthInLong = file.getTagSizeInLong(); } } //Create new concatenated file TagCountMutable tc = new TagCountMutable(tagLengthInLong, tagNum); for (String name : filenames) { TagsOnPhysicalMap file = new TagsOnPhysicalMap(name, true); for (int i = 0; i < file.myNumTags; i++) { tc.addReadCount(file.getTag(i), file.getTagLength(i), 1); } } //Reduce concatenated file to unique tags tc.collapseCounts(); tc.shrinkToCurrentRows(); TagsOnPhysicalMap result = new TagsOnPhysicalMap(tc); result.expandMaxVariants(maxVariants); result.clearVariants(); return result; } /** * Merges several TOPM files into one, removing duplicate rows. Variants * from matching tags are combined in the output file. If there are more * variants in the input files than can fit in the output, extra variants * are discarded with no particular order. */ public static TagsOnPhysicalMap merge(String[] filenames) { TagsOnPhysicalMap output = uniqueTags(filenames); System.out.println( "Output file will contain " + output.myNumTags + " unique tags, " + output.getTagSizeInLong() + " longs/tag, " + output.myMaxVariants + " variants. "); for (String name : filenames) { TagsOnPhysicalMap file = new TagsOnPhysicalMap(name, true); int varsAdded = 0, varsSkipped = 0; for (int inTag = 0; inTag < file.myNumTags; inTag++) { //Loop over tags in input //Find index of corresponding tag in output file, and copy attributes from input to output int outTag = output.getTagIndex(file.getTag(inTag)); copyTagAttributes(file, inTag, output, outTag); //For corresponding tags, compare variants for (int outVar = 0; outVar < output.myMaxVariants; outVar++) { byte outOff = output.getVariantPosOff(outTag, outVar); if (outOff != BYTE_MISSING) {//Skip filled output variants or re-initialize them varsSkipped++; continue; } for (int inVar = 0; inVar < file.myMaxVariants; inVar++) { byte offset = file.getVariantPosOff(inTag, outVar); byte def = file.getVariantDef(inTag, outVar); if (offset == BYTE_MISSING) { continue; //Skip blank input variants } //If we get here, output variant is blank and input variant is non-blank at the same tag & variant indices varsAdded++; output.setVariantPosOff(outTag, outVar, offset); output.setVariantDef(outTag, outVar, def); file.setVariantPosOff(inTag, inVar, Byte.MIN_VALUE); //Erase this variant so it isn't encountered again break; //Go to next output variant after copying } } } System.out.println(varsAdded + " variants added."); System.out.println(varsSkipped + " variants skipped."); } return output; } /** * Copies values of everything BUT tag sequence and variant data (i.e. tag * attributes) from one TOPM file to another. */ private static void copyTagAttributes(TagsOnPhysicalMap input, int inTag, TagsOnPhysicalMap output, int outTag) { output.tagLength[outTag] = input.tagLength[inTag]; output.multimaps[outTag] = input.multimaps[inTag]; output.bestChr[outTag] = input.bestChr[inTag]; output.bestStrand[outTag] = input.bestStrand[inTag]; output.bestStartPos[outTag] = input.bestStartPos[inTag]; output.endPosition[outTag] = input.endPosition[inTag]; output.divergence[outTag] = input.divergence[inTag]; output.dcoP[outTag] = input.dcoP[inTag]; output.mapP[outTag] = input.mapP[inTag]; } /** * Fills the variant definition & offset arrays with the value of * "byteMissing". */ public void clearVariants() { for (int i = 0; i < getTagCount(); i++) { Arrays.fill(variantDefs[i], BYTE_MISSING); Arrays.fill(variantOffsets[i], BYTE_MISSING); } } /** * Fills the variant definition & offset at the given indices with the value * of "byteMissing". */ private void clearVariant(int tag, int variant) { setVariantDef(tag, variant, BYTE_MISSING); setVariantPosOff(tag, variant, BYTE_MISSING); } /** * Clears variant sites that are not found in the supplied alignments. */ public void filter(String[] filenames) { HashMap<String, Integer> hapmapSites = new HashMap<String, Integer>(); //Map all site positions from all alignments to their index. for (String filename : filenames) { System.out.println("Filtering out sites from " + filename + "."); hapmapSites.putAll(hapmapSites(ImportUtils.readFromHapmap(filename, null))); } System.out.println("There are " + hapmapSites.size() + " sites in the hapmap files."); //Map all tag variant positions to their index. HashMap<String, Integer> topmSites = uniqueSites(); //Map tag variant positions to bases //Sites should be a subset of tag variants, so check that there are fewer of them. System.out.println("Found " + topmSites.size() + " unique sites in " + myNumTags + " tags in TOPM."); if (topmSites.size() < hapmapSites.size()) { System.out.println("Warning: more unique sites exist in hapmap file."); } //Next, check that each alignment site is present in If not, either there was no more room or something is wrong. HashSet<Integer> fullSites = fullTagPositions(); //Tags which already have the maximum number of variants ArrayList<String> insertedSites = new ArrayList<String>(); //Sites that don't correspond to a real tag ArrayList<String> skippedSites = new ArrayList<String>(); //Real sites that were skipped due to "full tags" int basePerTag = tagLengthInLong * 32; for (String hapmapSNP : hapmapSites.keySet().toArray(new String[hapmapSites.size()])) { int chr = Integer.parseInt(hapmapSNP.split("\\t")[0]); int pos = Integer.parseInt(hapmapSNP.split("\\t")[1]); if (topmSites.get(hapmapSNP) == null) { // System.out.print("Warning: SNP "+chr+":"+pos+" is not in TOPM. "); boolean inRange = false; for (int i = -basePerTag; i < basePerTag; i++) { if (fullSites.contains(i + pos)) { inRange = true; break; } } if (inRange) { skippedSites.add(hapmapSNP); // System.out.println("However, it is within range of a tag with the max. number of variants."); } else { insertedSites.add(hapmapSNP); System.out.println(); } hapmapSites.remove(hapmapSNP); continue; } } System.out.println("The following SNPs were not in the TOPM, but are within range of a tag with the max. number of variants:"); for (String site : skippedSites) { System.out.println(site); } System.out.println("The following SNPs were not in the TOPM, and do not correspond to any known tag:"); for (String site : insertedSites) { System.out.println(site); } //Remove any sites from the TOPM that are absent in the alignment int removedSites = 0; for (int tag = 0; tag < myNumTags; tag++) { int chr = getChromosome(tag); int pos = getStartPosition(tag); for (int variant = 0; variant < myMaxVariants; variant++) { byte off = getVariantPosOff(tag, variant); String site = chr + "\t" + (pos + off); if (!hapmapSites.containsKey(site)) { clearVariant(tag, variant); removedSites++; } } } topmSites = uniqueSites(); System.out.println("Removed " + removedSites + " TOPM sites not present in alignment and ignored " + insertedSites.size() + " alignment sites not present in TOPM."); System.out.println("There are " + topmSites.size() + " sites in the TOPM now, as compared to " + hapmapSites.size() + " sites in the alignment."); if (topmSites.size() != hapmapSites.size()) { System.out.println("Warning: number of filtered sites does not match number of alignment sites."); } } /** * Returns the start positions of tags whose variant arrays are full. */ public HashSet<Integer> fullTagPositions() { HashSet<Integer> result = new HashSet<Integer>(); for (int i = 0; i < myNumTags; i++) { boolean variantsFull = true; for (int j = 0; j < myMaxVariants; j++) { byte off = getVariantPosOff(i, j); if (off == Byte.MIN_VALUE) { variantsFull = false; break; } } if (variantsFull) { result.add(getStartPosition(i)); } } return result; } /** * Maps unique sites (i.e. bestChr and position) to the indices of the * tags in which they are found. */ public HashMap<String, Integer> uniqueSites() { HashMap<String, Integer> snps = new HashMap<String, Integer>(); for (int tag = 0; tag < myNumTags; tag++) { //Visit each tag in TOPM for (int variant = 0; variant < myMaxVariants; variant++) { //Visit each variant in TOPM byte off = getVariantPosOff(tag, variant); if (off == BYTE_MISSING) { continue; } int a = getStartPosition(tag); int b = getVariantPosOff(tag, variant); int c = a + b; String pos = getChromosome(tag) + "\t" + c; snps.put(pos, tag); } } return snps; } public static HashMap<String, Integer> hapmapSites(Alignment file) { HashMap<String, Integer> snps = new HashMap<String, Integer>(); for (int site = 0; site < file.getSiteCount(); site++) { //Visit each site String pos = (file.getLocusName(site) + "\t" + file.getPositionInLocus(site)); if (file.getPositionInLocus(site) > 2000000000) { System.out.println(pos); } snps.put(pos, site); } return snps; } /** * Returns an array whose indices are the number of mappings and whose * elements are the number of tags with that mapping. */ public int[] mappingDistribution() { int[] result = new int[128]; //Only up to 127 multiple mappings are stored. for (int i = 0; i < myNumTags; i++) { if (multimaps[i] > (result.length - 1)) { result[127]++; } if (multimaps[i] == BYTE_MISSING) { result[0]++; continue; } else { result[multimaps[i]]++; } } return result; } }
src/net/maizegenetics/gbs/maps/TagsOnPhysicalMap.java
package net.maizegenetics.gbs.maps; import cern.colt.GenericSorting; import cern.colt.Swapper; import cern.colt.function.IntComparator; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import net.maizegenetics.gbs.tagdist.AbstractTags; import net.maizegenetics.gbs.tagdist.TagCountMutable; import net.maizegenetics.gbs.tagdist.Tags; import net.maizegenetics.gbs.util.SAMUtils; import net.maizegenetics.gbs.util.BaseEncoder; import net.maizegenetics.pal.alignment.Alignment; import net.maizegenetics.pal.alignment.AlignmentUtils; import net.maizegenetics.pal.alignment.ImportUtils; import net.maizegenetics.pal.alignment.Locus; import net.maizegenetics.pal.alignment.NucleotideAlignmentConstants; import net.maizegenetics.util.MultiMemberGZIPInputStream; /** * Holds tag data compressed in long and a physical position. This can have two * variations either include redundant positions or only unique positions. If * redundant than tags that map to multiple regions should be placed adjacently * * Default 40 bytes per position. If we have 10,000,000 million positions then * this will be at 400M byte data structure. * * User: ed */ public class TagsOnPhysicalMap extends AbstractTagsOnPhysicalMap { int[] endPosition; // chromosomal position of the common adapter end of the tag (smaller than bestStartPos if tag matches minus bestStrand) // 4 bytes byte[] divergence; // number of diverging bp (edit distance) from reference, unknown = Byte.MIN_VALUE byte[] dcoP, mapP; //Round(Log2(P)), unknown Byte.MIN_VALUE boolean redundantTags = true; // this field has not been utilized yet public static enum SAMFormat { BWA, BOWTIE2 }; // Supported SAM formats (each program defines some custom features) private SAMFormat mySAMFormat = SAMFormat.BWA; // BWA by default public TagsOnPhysicalMap() { } public TagsOnPhysicalMap(String inFile, boolean binary) { if (binary) { readBinaryFile(new File(inFile)); } else { readTextFile(new File(inFile)); } initPhysicalSort(); } public TagsOnPhysicalMap(int rows) { initMatrices(rows); } public TagsOnPhysicalMap(int rows, int tagLengthInLong, int maxVariants) { this.tagLengthInLong = tagLengthInLong; this.myMaxVariants = maxVariants; initMatrices(rows); } public TagsOnPhysicalMap(Tags readList) { tagLengthInLong = readList.getTagSizeInLong(); initMatrices(readList.getTagCount()); for (int i = 0; i < readList.getTagCount(); i++) { for (int j = 0; j < tagLengthInLong; j++) { tags[j][i] = readList.getTag(i)[j]; } } } public TagsOnPhysicalMap(TagsOnPhysicalMap oldTOPM, boolean filterDuplicates) { this.tagLengthInLong = oldTOPM.tagLengthInLong; this.myMaxVariants = oldTOPM.myMaxVariants; oldTOPM.sortTable(true); int uniqueCnt = 1; for (int i = 1; i < oldTOPM.getSize(); i++) { if (!Arrays.equals(oldTOPM.getTag(i - 1), oldTOPM.getTag(i))) { uniqueCnt++; } } System.out.println("The Physical Map File has UniqueTags:" + uniqueCnt + " TotalLocations:" + oldTOPM.getSize()); initMatrices(uniqueCnt); this.myNumTags = uniqueCnt; uniqueCnt = 0; this.copyTagMapRow(oldTOPM, 0, 0, filterDuplicates); for (int i = 1; i < oldTOPM.getTagCount(); i++) { // System.out.println(this.getTag(uniqueCnt)[1]+":"+ oldTOPM.getTag(i)[1]); // System.out.println(":"+ oldTOPM.getTag(i)[1]); if (!Arrays.equals(this.getTag(uniqueCnt), oldTOPM.getTag(i))) { uniqueCnt++; // copyTagMapRow(oldTOPM, i, uniqueCnt, filterDuplicates); } else { // System.out.printf("i=%d uniqueCnt=%d %n",i, uniqueCnt); } copyTagMapRow(oldTOPM, i, uniqueCnt, filterDuplicates); } initPhysicalSort(); } void initMatrices(int rows) { tags = new long[tagLengthInLong][rows]; // 16 bytes tagLength = new byte[rows]; // length of tag (number of bases) // 1 byte multimaps = new byte[rows]; // number of locations this tagSet maps to, unknown = Byte.MIN_VALUE bestChr = new int[rows]; // 4 bytes bestStrand = new byte[rows]; // 1 = same sense as reference FASTA file. -1 = opposite sense. unknown = Byte.MIN_VALUE // 1 byte bestStartPos = new int[rows]; // chromosomal position of the barcoded end of the tag // 4 bytes endPosition = new int[rows]; // chromosomal position of the common adapter end of the tag (smaller than bestStartPos if tag matches minus bestStrand) // 4 bytes divergence = new byte[rows]; // number of diverging bp from reference, unknown = Byte.MIN_VALUE variantOffsets = new byte[rows][]; // offset from position minimum, maximum number of variants is defined above // myMaxVariants bytes variantDefs = new byte[rows][]; // allele state - A, C, G, T or some indel definition // myMaxVariants bytes dcoP = new byte[rows]; mapP = new byte[rows]; // Round(Log2(P)), unknown = Byte.MIN_VALUE; if these disagree with the location, then set the p to negative myNumTags = rows; // try{ // System.out.println("Sleeping after memory creation"); // Thread.sleep(100000); // } catch(Exception e) { // System.out.println(e); // } } public void expandMaxVariants(int newMaxVariants) { if (newMaxVariants <= this.myMaxVariants) { System.out.println("TagsOnPhysicalMap.expandMaxVariants(" + newMaxVariants + ") not performed because newMaxVariants (" + newMaxVariants + ") <= current maxVariants (" + this.myMaxVariants + ")"); return; } int oldMaxVariants = this.myMaxVariants; byte[][] newVariantPosOff = new byte[myNumTags][newMaxVariants]; byte[][] newVariantDef = new byte[myNumTags][newMaxVariants]; for (int t = 0; t < myNumTags; ++t) { for (int v = 0; v < this.myMaxVariants; ++v) { newVariantPosOff[t][v] = this.variantOffsets[t][v]; newVariantDef[t][v] = this.variantDefs[t][v]; } for (int v = this.myMaxVariants; v < newMaxVariants; ++v) { newVariantPosOff[t][v] = Byte.MIN_VALUE; newVariantDef[t][v] = Byte.MIN_VALUE; } } this.myMaxVariants = newMaxVariants; this.variantOffsets = newVariantPosOff; this.variantDefs = newVariantDef; System.out.println("TagsOnPhysicalMap maxVariants expanded from " + oldMaxVariants + " to " + newMaxVariants); } /** * This helps collapse identical reads from different regions of the genome * together. * * @param sourceTOPM * @param sourceRow * @param destRow * @param merge */ public void copyTagMapRow(TagsOnPhysicalMap sourceTOPM, int sourceRow, int destRow, boolean merge) { boolean overwrite = true; long[] ctag = sourceTOPM.getTag(sourceRow); if (Arrays.equals(ctag, this.getTag(destRow)) && merge) { overwrite = false; } for (int i = 0; i < tagLengthInLong; i++) { tags[i][destRow] = ctag[i]; } if (overwrite) { tagLength[destRow] = sourceTOPM.tagLength[sourceRow]; multimaps[destRow] = sourceTOPM.multimaps[sourceRow]; bestChr[destRow] = sourceTOPM.bestChr[sourceRow]; bestStrand[destRow] = sourceTOPM.bestStrand[sourceRow]; bestStartPos[destRow] = sourceTOPM.bestStartPos[sourceRow]; endPosition[destRow] = sourceTOPM.endPosition[sourceRow]; divergence[destRow] = sourceTOPM.divergence[sourceRow]; for (int j = 0; j < myMaxVariants; j++) { variantOffsets[destRow][j] = sourceTOPM.variantOffsets[sourceRow][j]; variantDefs[destRow][j] = sourceTOPM.variantOffsets[sourceRow][j]; } dcoP[destRow] = sourceTOPM.dcoP[sourceRow]; mapP[destRow] = sourceTOPM.mapP[sourceRow]; } else { //tagLength[destRow]=tagLength[sourceRow]; if ((bestChr[destRow] != sourceTOPM.bestChr[sourceRow]) || (bestStrand[destRow] != sourceTOPM.bestStrand[sourceRow]) || (bestStartPos[destRow] != sourceTOPM.bestStartPos[sourceRow]) || (endPosition[destRow] != sourceTOPM.endPosition[sourceRow])) { multimaps[destRow] += sourceTOPM.multimaps[sourceRow]; bestChr[destRow] = bestStrand[destRow] = Byte.MIN_VALUE; bestStartPos[destRow] = endPosition[destRow] = Integer.MIN_VALUE; } //dcoP[destRow]=dcoP[sourceRow]; //mapP[destRow]=mapP[sourceRow]; } } public long sortTable(boolean byHaplotype) { System.out.print("Starting Read Table Sort ..."); if (byHaplotype == false) { //TODO change the signature at some time System.out.print("ERROR: Position sorting has been eliminated ..."); return -1; } long time = System.currentTimeMillis(); GenericSorting.quickSort(0, tags[0].length, this, this); long totalTime = System.currentTimeMillis() - time; System.out.println("Done in " + totalTime + "ms"); initPhysicalSort(); return totalTime; } protected void readBinaryFile(File currentFile) { int tagsInput = 0; try { DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(currentFile), 65536)); System.out.println("File = " + currentFile); myNumTags = dis.readInt(); // myNumTags=100000; tagLengthInLong = dis.readInt(); myMaxVariants = dis.readInt(); initMatrices(myNumTags); for (int row = 0; row < myNumTags; row++) { for (int j = 0; j < tagLengthInLong; j++) { tags[j][row] = dis.readLong(); } tagLength[row] = dis.readByte(); multimaps[row] = dis.readByte(); bestChr[row] = dis.readInt(); bestStrand[row] = dis.readByte(); bestStartPos[row] = dis.readInt(); endPosition[row] = dis.readInt(); divergence[row] = dis.readByte(); byte[] currVD=new byte[myMaxVariants]; byte[] currVO=new byte[myMaxVariants]; int numWithData=0; for (int j = 0; j < myMaxVariants; j++) { currVO[j] = dis.readByte(); currVD[j] = dis.readByte(); if((currVD[j]>0xf)&&(AlignmentUtils.isHeterozygous(currVD[j]))) {//ascii bytes need to be converted to TASSEL 4 // System.out.printf("row:%d vd:%d %n", row, variantDefs[row][j]); currVD[j]=NucleotideAlignmentConstants.getNucleotideDiploidByte((char)currVD[j]); } if(currVO[j]!=TOPMInterface.BYTE_MISSING) numWithData++; } if(numWithData>0) { variantDefs[row]=Arrays.copyOf(currVD, numWithData); variantOffsets[row]=Arrays.copyOf(currVO, numWithData); } dcoP[row] = dis.readByte(); mapP[row] = dis.readByte(); tagsInput++; if (row % 1000000 == 0) { System.out.println("TagMapFile Row Read:" + row); } } dis.close(); } catch (Exception e) { System.out.println("Error tagsInput=" + tagsInput + " e=" + e); } System.out.println("Count of Tags=" + tagsInput); } public boolean variantsDefined(int tagIndex) { for (int i = 0; i < myMaxVariants; i++) { if ((variantOffsets[tagIndex][i] != Byte.MIN_VALUE) && (variantDefs[tagIndex][i] != Byte.MIN_VALUE)) { return true; } } return false; } public void readTextFile(File inFile) { System.out.println("Reading tag alignment from:" + inFile.toString()); String[] inputLine = {"NotRead"}; try { BufferedReader br = new BufferedReader(new FileReader(inFile), 65536); inputLine = br.readLine().split("\t"); //Parse header line (Number of tags, number of Long ints per tag, maximum variant bases per tag). this.myNumTags = Integer.parseInt(inputLine[0]); this.tagLengthInLong = Integer.parseInt(inputLine[1]); this.myMaxVariants = Integer.parseInt(inputLine[2]); // initMatrices(9000000); initMatrices(myNumTags); //Loop through remaining lines, store contents in a series of arrays indexed by row number for (int row = 0; row < myNumTags; row++) { inputLine = br.readLine().split("\t"); int c = 0; long[] tt = BaseEncoder.getLongArrayFromSeq(inputLine[c++]); for (int j = 0; j < tt.length; j++) { tags[j][row] = tt[j]; } tagLength[row] = parseByteWMissing(inputLine[c++]); multimaps[row] = parseByteWMissing(inputLine[c++]); bestChr[row] = parseIntWMissing(inputLine[c++]); bestStrand[row] = parseByteWMissing(inputLine[c++]); bestStartPos[row] = parseIntWMissing(inputLine[c++]); endPosition[row] = parseIntWMissing(inputLine[c++]); divergence[row] = parseByteWMissing(inputLine[c++]); byte[] currVD=new byte[myMaxVariants]; byte[] currVO=new byte[myMaxVariants]; int numWithData=0; for (int j = 0; j < myMaxVariants; j++) { currVO[j] = parseByteWMissing(inputLine[c++]); currVD[j] = parseCharWMissing(inputLine[c++]); if(currVO[j]!=TOPMInterface.BYTE_MISSING) numWithData++; } variantDefs[row]=Arrays.copyOf(currVD, numWithData); variantOffsets[row]=Arrays.copyOf(currVO, numWithData); dcoP[row] = parseByteWMissing(inputLine[c++]); mapP[row] = parseByteWMissing(inputLine[c++]); if (row % 1000000 == 0) { System.out.println("Row Read:" + row); } } } catch (Exception e) { System.out.println("Catch in reading TagOnPhysicalMap file e=" + e); e.printStackTrace(); System.out.println("Line:"+Arrays.toString(inputLine)); } System.out.println("Number of tags in file:" + myNumTags); } @Override public int getReadIndexForPositionIndex(int posIndex) { return indicesOfSortByPosition[posIndex]; } @Override public int[] getPositionArray(int index) { int[] r = {bestChr[index], bestStrand[index], bestStartPos[index]}; return r; } // public int getReadIndex(byte chr, byte bestStrand, int posMin) { // // dep_ReadWithPositionInfo querySHP=new dep_ReadWithPositionInfo(bestChr, bestStrand, posMin); // // PositionComparator posCompare = new PositionComparator(); // // int hit1=Arrays.binarySearch(shp, querySHP, posCompare); // int hit1=-1; //redo // return hit1; // } public static byte parseCharWMissing(String s) { if (s.equals("*")) { return Byte.MIN_VALUE; } try{ byte r=NucleotideAlignmentConstants.getNucleotideAlleleByte(s); return r; } catch(IllegalArgumentException e) { int i = Integer.parseInt(s); if (i > 127) {return 127;} byte r=NucleotideAlignmentConstants.getNucleotideAlleleByte(String.valueOf((char)i)); return r; } } public static byte parseByteWMissing(String s) { if (s.equals("*")) { return Byte.MIN_VALUE; } int i; try { i = Integer.parseInt(s); if (i > 127) { return 127; } return (byte) i; } catch (NumberFormatException nf) { return Byte.MIN_VALUE; } } public static int parseIntWMissing(String s) { if (s.equals("*")) { return Integer.MIN_VALUE; } int i; try { i = Integer.parseInt(s); return i; } catch (NumberFormatException nf) { return Integer.MIN_VALUE; } } @Override public byte getMultiMaps(int index) { return multimaps[index]; } @Override public int getEndPosition(int index) { return endPosition[index]; } @Override public byte getDivergence(int index) { return divergence[index]; } @Override public byte getMapP(int index) { return mapP[index]; } @Override public byte getDcoP(int index) { return dcoP[index]; } @Override public void setChromoPosition(int index, int chromosome, byte strand, int positionMin, int positionMax) { this.bestChr[index] = chromosome; this.bestStrand[index] = strand; this.bestStartPos[index] = positionMin; this.endPosition[index] = positionMax; } @Override public void setDivergence(int index, byte divergence) { this.divergence[index] = divergence; } @Override public void setMapP(int index, byte mapP) { this.mapP[index] = mapP; } @Override public void setMapP(int index, double mapP) { if (Double.isInfinite(mapP)) { this.mapP[index] = Byte.MAX_VALUE; return; } if (Double.isNaN(mapP) || (mapP < 0) || (mapP > 1)) { this.mapP[index] = Byte.MIN_VALUE; return; } if (mapP < 1e-126) { this.mapP[index] = Byte.MAX_VALUE; return; } this.mapP[index] = (byte) (-Math.round(Math.log10(mapP))); } @Override public int addVariant(int tagIndex, byte offset, byte base) { for (int i = 0; i < myMaxVariants; i++) { if ((variantOffsets[tagIndex][i] == Byte.MIN_VALUE) && (variantDefs[tagIndex][i] == Byte.MIN_VALUE)) { variantOffsets[tagIndex][i] = offset; variantDefs[tagIndex][i] = base; return i; } } return -1; //no free space } /** * Decodes bitwise flags from the code in SAM field 3. The code is a 32-bit * integer, so I boolean AND the flag value with the code, and compare the * result with the flag value. If they are equal, that means all bits set in * the flag number were set in the code (i.e., that flag is turned on). */ private boolean flagSet(int code, int flag) { int flagValue = 1 << flag; //1<<flag is equivalent to 2^flag return ((code & flagValue) == flagValue); } /** * Reads SAM files output from BWA or bowtie2 */ public void readSAMFile(String inputFileName, int tagLengthInLong) { System.out.println("Reading SAM format tag alignment from: " + inputFileName); this.tagLengthInLong = tagLengthInLong; String inputStr = "Nothing has been read from the file yet"; int nHeaderLines = countTagsInSAMfile(inputFileName); // detects if the file is bowtie2, initializes topm matrices int tagIndex = Integer.MIN_VALUE; try { BufferedReader br; if (inputFileName.endsWith(".gz")) { br = new BufferedReader(new InputStreamReader(new MultiMemberGZIPInputStream(new FileInputStream(new File(inputFileName))))); } else { br = new BufferedReader(new FileReader(new File(inputFileName)), 65536); } for (int i = 0; i < nHeaderLines; i++) { br.readLine(); } // Skip over the header for (tagIndex = 0; tagIndex < myNumTags; tagIndex++) { inputStr = br.readLine(); parseSAMAlignment(inputStr, tagIndex); if (tagIndex % 1000000 == 0) { System.out.println("Read " + tagIndex + " tags."); } } br.close(); } catch (Exception e) { System.out.println("\n\nCatch in reading SAM alignment file at tag " + tagIndex + ":\n\t" + inputStr + "\nError: " + e + "\n\n"); e.printStackTrace(); System.exit(1); } } private int countTagsInSAMfile(String inputFileName) { mySAMFormat = SAMFormat.BWA; // format is BWA by default myNumTags = 0; int nHeaderLines = 0; String currLine = null; try { String[] inputLine; ArrayList<String> chrNames = new ArrayList<String>(); BufferedReader br; if (inputFileName.endsWith(".gz")) { br = new BufferedReader(new InputStreamReader(new MultiMemberGZIPInputStream(new FileInputStream(new File(inputFileName))))); } else { br = new BufferedReader(new FileReader(new File(inputFileName)), 65536); } while ((currLine = br.readLine()) != null) { inputLine = currLine.split("\\s"); if (inputLine[0].contains("@")) { //SAM files produced by Bowtie2 contain the string "@PG ID:bowtie2 PN:bowtie2 " if (inputLine[1].contains("bowtie2")) { mySAMFormat = SAMFormat.BOWTIE2; } nHeaderLines++; } else { String chr = inputLine[2]; if (!chrNames.contains(chr)) { chrNames.add(chr); } myNumTags++; if (myNumTags % 1000000 == 0) { System.out.println("Counted " + myNumTags + " tags."); } } } br.close(); System.out.println("Found " + myNumTags + " tags in SAM file. Assuming " + mySAMFormat + " file format."); } catch (Exception e) { System.out.println("Catch in counting lines of alignment file at line " + currLine + ": " + e); e.printStackTrace(); System.exit(1); } initMatrices(myNumTags); return nHeaderLines; } private void parseSAMAlignment(String inputStr, int tagIndex) { String[] inputLine = inputStr.split("\t"); int name = 0, flag = 1, chr = 2, pos = 3, cigar = 5, tagS = 9; // column indices in inputLine String nullS = this.getNullTag(); if ((Integer.parseInt(inputLine[flag]) & 4) == 4) { // bit 0x4 (= 2^2 = 4) is set: NO ALIGNMENT recordLackOfSAMAlign(tagIndex, inputLine[tagS], inputLine[name], nullS); } else { // aligns to one or more positions HashMap<String, Integer> SAMFields = parseOptionalFieldsFromSAMAlignment(inputLine); byte bestHits = (byte) Math.min(SAMFields.get("nBestHits"), Byte.MAX_VALUE); byte editDist = (byte) Math.min(SAMFields.get("editDist"), Byte.MAX_VALUE); byte currStrand = (Integer.parseInt(inputLine[flag]) == 16) ? (byte) -1 : (byte) 1; recordSAMAlign( tagIndex, inputLine[tagS], inputLine[name], nullS, bestHits, inputLine[chr], currStrand, Integer.parseInt(inputLine[pos]), inputLine[cigar], editDist); } } private HashMap<String, Integer> parseOptionalFieldsFromSAMAlignment(String[] inputLine) { HashMap<String, Integer> SAMFields = new HashMap<String, Integer>(); if (mySAMFormat == SAMFormat.BWA) { for (int field = 11; field < inputLine.length; field++) { // Loop through all the optional field of the SAM alignment if (inputLine[field].regionMatches(0, "X0", 0, 2)) { // X0 = SAM format for # of "high-quality" alignments of this query. Specific to BWA. SAMFields.put("nBestHits", Integer.parseInt(inputLine[field].split(":")[2])); } else if (inputLine[field].regionMatches(0, "NM", 0, 2)) { // NM = SAM format for edit distance to the reference. Common to BWA and Bowtie2. SAMFields.put("editDist", Integer.parseInt(inputLine[field].split(":")[2])); } } } else { // bowtie2 -M format for (int field = 11; field < inputLine.length; field++) { // Loop through all the optional field of the SAM alignment if (inputLine[field].regionMatches(0, "AS", 0, 2)) { // AS = SAM format for alignment score of the best alignment. Specific to bowtie2. SAMFields.put("bestScore", Integer.parseInt(inputLine[field].split(":")[2])); } else if (inputLine[field].regionMatches(0, "XS", 0, 2)) { // XS = SAM format for alignment score of 2nd best alignment. Specific to bowtie2. SAMFields.put("nextScore", Integer.parseInt(inputLine[field].split(":")[2])); } else if (inputLine[field].regionMatches(0, "NM", 0, 2)) { // NM = SAM format for edit distance to the reference. Common to BWA and Bowtie2. SAMFields.put("editDist", Integer.parseInt(inputLine[field].split(":")[2])); } } if (SAMFields.containsKey("bestScore")) { if (SAMFields.containsKey("nextScore")) { if (SAMFields.get("bestScore") > SAMFields.get("nextScore")) { SAMFields.put("nBestHits", 1); } else { SAMFields.put("nBestHits", 99); // 99 will stand for an unknown # of multiple hits } } else { SAMFields.put("nBestHits", 1); } } } return SAMFields; } private void recordLackOfSAMAlign(int tagIndex, String tagS, String tagName, String nullS) { recordTagFromSAMAlignment(tagIndex, tagS, tagName, nullS, (byte) 1); multimaps[tagIndex] = 0; // or should this be unknown = Byte.MIN_VALUE??? bestChr[tagIndex] = Integer.MIN_VALUE; bestStrand[tagIndex] = Byte.MIN_VALUE; bestStartPos[tagIndex] = Integer.MIN_VALUE; endPosition[tagIndex] = Integer.MIN_VALUE; divergence[tagIndex] = Byte.MIN_VALUE; for (int var = 0; var < myMaxVariants; var++) { variantOffsets[tagIndex][var] = Byte.MIN_VALUE; variantDefs[tagIndex][var] = Byte.MIN_VALUE; } dcoP[tagIndex] = Byte.MIN_VALUE; mapP[tagIndex] = Byte.MIN_VALUE; } private void recordSAMAlign(int tagIndex, String tagS, String tagName, String nullS, byte nBestHits, String chrS, byte strand, int pos, String cigar, byte editDist) { recordTagFromSAMAlignment(tagIndex, tagS, tagName, nullS, strand); multimaps[tagIndex] = nBestHits; if (nBestHits == 1) { bestChr[tagIndex] = parseChrString(chrS); this.bestStrand[tagIndex] = strand; recordStartEndPostionFromSAMAlign(tagIndex, strand, pos, cigar); } else { bestChr[tagIndex] = Integer.MIN_VALUE; this.bestStrand[tagIndex] = Byte.MIN_VALUE; bestStartPos[tagIndex] = Integer.MIN_VALUE; endPosition[tagIndex] = Integer.MIN_VALUE; } divergence[tagIndex] = editDist; for (int var = 0; var < myMaxVariants; var++) { variantOffsets[tagIndex][var] = Byte.MIN_VALUE; variantDefs[tagIndex][var] = Byte.MIN_VALUE; } dcoP[tagIndex] = Byte.MIN_VALUE; mapP[tagIndex] = Byte.MIN_VALUE; } private void recordTagFromSAMAlignment(int tagIndex, String tagS, String tagName, String nullS, byte strand) { if (strand == -1) { tagS = BaseEncoder.getReverseComplement(tagS); } if (tagS.length() < tagLengthInLong * 32) { // pad with polyA tagS = tagS + nullS; tagS = tagS.substring(0, (tagLengthInLong * 32)); } long[] tagSequence = BaseEncoder.getLongArrayFromSeq(tagS); for (int chunk = 0; chunk < tagLengthInLong; chunk++) { tags[chunk][tagIndex] = tagSequence[chunk]; } tagName = tagName.replaceFirst("count=[0-9]+", ""); tagName = tagName.replaceFirst("length=", ""); tagLength[tagIndex] = Byte.parseByte(tagName); } private int parseChrString(String chrS) { int chr = Integer.MIN_VALUE; chrS = chrS.replace("chr", ""); try { chr = Integer.parseInt(chrS); } catch (NumberFormatException e) { System.out.println("\n\nSAMConverterPlugin detected a non-numeric chromosome name: " + chrS + "\n\nPlease change the FASTA headers in your reference genome sequence to integers " + "(>1, >2, >3, etc.) OR to 'chr' followed by an integer (>chr1, >chr2, >chr3, etc.)\n\n"); System.exit(1); } return chr; } private void recordStartEndPostionFromSAMAlign(int tagIndex, byte strand, int pos, String cigar) { int[] alignSpan = SAMUtils.adjustCoordinates(cigar, pos); try { if (strand == 1) { bestStartPos[tagIndex] = alignSpan[0]; endPosition[tagIndex] = alignSpan[1]; } else if (strand == -1) { bestStartPos[tagIndex] = alignSpan[1]; endPosition[tagIndex] = alignSpan[0]; } else { throw new Exception("Unexpected value for strand: " + strand + "(expect 1 or -1)"); } } catch (Exception e) { System.out.println("Error in recordStartEndPostionFromSAMAlign: " + e); e.printStackTrace(); System.exit(1); } } @Override public void swap(int index1, int index2) { long tl; for (int i = 0; i < tagLengthInLong; i++) { tl = tags[i][index1]; tags[i][index1] = tags[i][index2]; tags[i][index2] = tl; } int tb; tb = tagLength[index1]; tagLength[index1] = tagLength[index2]; tagLength[index2] = (byte) tb; tb = multimaps[index1]; multimaps[index1] = multimaps[index2]; multimaps[index2] = (byte) tb; tb = bestChr[index1]; bestChr[index1] = bestChr[index2]; bestChr[index2] = tb; tb = bestStrand[index1]; bestStrand[index1] = bestStrand[index2]; bestStrand[index2] = (byte) tb; int ti; ti = bestStartPos[index1]; bestStartPos[index1] = bestStartPos[index2]; bestStartPos[index2] = ti; ti = endPosition[index1]; endPosition[index1] = endPosition[index2]; endPosition[index2] = ti; tb = divergence[index1]; divergence[index1] = divergence[index2]; divergence[index2] = (byte) tb; for (int j = 0; j < myMaxVariants; j++) { tb = variantOffsets[index1][j]; variantOffsets[index1][j] = variantOffsets[index2][j]; variantOffsets[index2][j] = (byte) tb; tb = variantDefs[index1][j]; variantDefs[index1][j] = variantDefs[index2][j]; variantDefs[index2][j] = (byte) tb; } tb = dcoP[index1]; dcoP[index1] = dcoP[index2]; dcoP[index2] = (byte) tb; tb = mapP[index1]; mapP[index1] = mapP[index2]; mapP[index2] = (byte) tb; } @Override public int compare(int index1, int index2) { for (int i = 0; i < tagLengthInLong; i++) { if (tags[i][index1] < tags[i][index2]) { return -1; } if (tags[i][index1] > tags[i][index2]) { return 1; } } if (bestChr[index1] < bestChr[index2]) { return -1; } if (bestChr[index1] > bestChr[index2]) { return 1; } if (bestStartPos[index1] < bestStartPos[index2]) { return -1; } if (bestStartPos[index1] > bestStartPos[index2]) { return 1; } if (bestStrand[index1] < bestStrand[index2]) { return -1; } if (bestStrand[index1] > bestStrand[index2]) { return 1; } return 0; } @Override public void setVariantDef(int tagIndex, int variantIndex, byte def) { variantDefs[tagIndex][variantIndex] = (byte) NucleotideAlignmentConstants.NUCLEOTIDE_ALLELES[0][def].charAt(0); } @Override public void setVariantPosOff(int tagIndex, int variantIndex, byte offset) { variantOffsets[tagIndex][variantIndex] = offset; } @Override public int getMaxNumVariants() { return myMaxVariants; } /** * First, find unique tags by concatenating them into a TagCountMutable * object and collapsing duplicate rows. */ private static TagsOnPhysicalMap uniqueTags(String[] filenames) { //Find dimensions of concatenated file int tagLengthInLong = 0, maxVariants = 0, tagNum = 0; for (String name : filenames) { TagsOnPhysicalMap file = new TagsOnPhysicalMap(name, true); tagNum += file.myNumTags; if (file.myMaxVariants > maxVariants) { maxVariants = file.myMaxVariants; } if (file.getTagSizeInLong() > tagLengthInLong) { tagLengthInLong = file.getTagSizeInLong(); } } //Create new concatenated file TagCountMutable tc = new TagCountMutable(tagLengthInLong, tagNum); for (String name : filenames) { TagsOnPhysicalMap file = new TagsOnPhysicalMap(name, true); for (int i = 0; i < file.myNumTags; i++) { tc.addReadCount(file.getTag(i), file.getTagLength(i), 1); } } //Reduce concatenated file to unique tags tc.collapseCounts(); tc.shrinkToCurrentRows(); TagsOnPhysicalMap result = new TagsOnPhysicalMap(tc); result.expandMaxVariants(maxVariants); result.clearVariants(); return result; } /** * Merges several TOPM files into one, removing duplicate rows. Variants * from matching tags are combined in the output file. If there are more * variants in the input files than can fit in the output, extra variants * are discarded with no particular order. */ public static TagsOnPhysicalMap merge(String[] filenames) { TagsOnPhysicalMap output = uniqueTags(filenames); System.out.println( "Output file will contain " + output.myNumTags + " unique tags, " + output.getTagSizeInLong() + " longs/tag, " + output.myMaxVariants + " variants. "); for (String name : filenames) { TagsOnPhysicalMap file = new TagsOnPhysicalMap(name, true); int varsAdded = 0, varsSkipped = 0; for (int inTag = 0; inTag < file.myNumTags; inTag++) { //Loop over tags in input //Find index of corresponding tag in output file, and copy attributes from input to output int outTag = output.getTagIndex(file.getTag(inTag)); copyTagAttributes(file, inTag, output, outTag); //For corresponding tags, compare variants for (int outVar = 0; outVar < output.myMaxVariants; outVar++) { byte outOff = output.getVariantPosOff(outTag, outVar); if (outOff != BYTE_MISSING) {//Skip filled output variants or re-initialize them varsSkipped++; continue; } for (int inVar = 0; inVar < file.myMaxVariants; inVar++) { byte offset = file.getVariantPosOff(inTag, outVar); byte def = file.getVariantDef(inTag, outVar); if (offset == BYTE_MISSING) { continue; //Skip blank input variants } //If we get here, output variant is blank and input variant is non-blank at the same tag & variant indices varsAdded++; output.setVariantPosOff(outTag, outVar, offset); output.setVariantDef(outTag, outVar, def); file.setVariantPosOff(inTag, inVar, Byte.MIN_VALUE); //Erase this variant so it isn't encountered again break; //Go to next output variant after copying } } } System.out.println(varsAdded + " variants added."); System.out.println(varsSkipped + " variants skipped."); } return output; } /** * Copies values of everything BUT tag sequence and variant data (i.e. tag * attributes) from one TOPM file to another. */ private static void copyTagAttributes(TagsOnPhysicalMap input, int inTag, TagsOnPhysicalMap output, int outTag) { output.tagLength[outTag] = input.tagLength[inTag]; output.multimaps[outTag] = input.multimaps[inTag]; output.bestChr[outTag] = input.bestChr[inTag]; output.bestStrand[outTag] = input.bestStrand[inTag]; output.bestStartPos[outTag] = input.bestStartPos[inTag]; output.endPosition[outTag] = input.endPosition[inTag]; output.divergence[outTag] = input.divergence[inTag]; output.dcoP[outTag] = input.dcoP[inTag]; output.mapP[outTag] = input.mapP[inTag]; } /** * Fills the variant definition & offset arrays with the value of * "byteMissing". */ public void clearVariants() { for (int i = 0; i < getTagCount(); i++) { Arrays.fill(variantDefs[i], BYTE_MISSING); Arrays.fill(variantOffsets[i], BYTE_MISSING); } } /** * Fills the variant definition & offset at the given indices with the value * of "byteMissing". */ private void clearVariant(int tag, int variant) { setVariantDef(tag, variant, BYTE_MISSING); setVariantPosOff(tag, variant, BYTE_MISSING); } /** * Clears variant sites that are not found in the supplied alignments. */ public void filter(String[] filenames) { HashMap<String, Integer> hapmapSites = new HashMap<String, Integer>(); //Map all site positions from all alignments to their index. for (String filename : filenames) { System.out.println("Filtering out sites from " + filename + "."); hapmapSites.putAll(hapmapSites(ImportUtils.readFromHapmap(filename, null))); } System.out.println("There are " + hapmapSites.size() + " sites in the hapmap files."); //Map all tag variant positions to their index. HashMap<String, Integer> topmSites = uniqueSites(); //Map tag variant positions to bases //Sites should be a subset of tag variants, so check that there are fewer of them. System.out.println("Found " + topmSites.size() + " unique sites in " + myNumTags + " tags in TOPM."); if (topmSites.size() < hapmapSites.size()) { System.out.println("Warning: more unique sites exist in hapmap file."); } //Next, check that each alignment site is present in If not, either there was no more room or something is wrong. HashSet<Integer> fullSites = fullTagPositions(); //Tags which already have the maximum number of variants ArrayList<String> insertedSites = new ArrayList<String>(); //Sites that don't correspond to a real tag ArrayList<String> skippedSites = new ArrayList<String>(); //Real sites that were skipped due to "full tags" int basePerTag = tagLengthInLong * 32; for (String hapmapSNP : hapmapSites.keySet().toArray(new String[hapmapSites.size()])) { int chr = Integer.parseInt(hapmapSNP.split("\\t")[0]); int pos = Integer.parseInt(hapmapSNP.split("\\t")[1]); if (topmSites.get(hapmapSNP) == null) { // System.out.print("Warning: SNP "+chr+":"+pos+" is not in TOPM. "); boolean inRange = false; for (int i = -basePerTag; i < basePerTag; i++) { if (fullSites.contains(i + pos)) { inRange = true; break; } } if (inRange) { skippedSites.add(hapmapSNP); // System.out.println("However, it is within range of a tag with the max. number of variants."); } else { insertedSites.add(hapmapSNP); System.out.println(); } hapmapSites.remove(hapmapSNP); continue; } } System.out.println("The following SNPs were not in the TOPM, but are within range of a tag with the max. number of variants:"); for (String site : skippedSites) { System.out.println(site); } System.out.println("The following SNPs were not in the TOPM, and do not correspond to any known tag:"); for (String site : insertedSites) { System.out.println(site); } //Remove any sites from the TOPM that are absent in the alignment int removedSites = 0; for (int tag = 0; tag < myNumTags; tag++) { int chr = getChromosome(tag); int pos = getStartPosition(tag); for (int variant = 0; variant < myMaxVariants; variant++) { byte off = getVariantPosOff(tag, variant); String site = chr + "\t" + (pos + off); if (!hapmapSites.containsKey(site)) { clearVariant(tag, variant); removedSites++; } } } topmSites = uniqueSites(); System.out.println("Removed " + removedSites + " TOPM sites not present in alignment and ignored " + insertedSites.size() + " alignment sites not present in TOPM."); System.out.println("There are " + topmSites.size() + " sites in the TOPM now, as compared to " + hapmapSites.size() + " sites in the alignment."); if (topmSites.size() != hapmapSites.size()) { System.out.println("Warning: number of filtered sites does not match number of alignment sites."); } } /** * Returns the start positions of tags whose variant arrays are full. */ public HashSet<Integer> fullTagPositions() { HashSet<Integer> result = new HashSet<Integer>(); for (int i = 0; i < myNumTags; i++) { boolean variantsFull = true; for (int j = 0; j < myMaxVariants; j++) { byte off = getVariantPosOff(i, j); if (off == Byte.MIN_VALUE) { variantsFull = false; break; } } if (variantsFull) { result.add(getStartPosition(i)); } } return result; } /** * Maps unique sites (i.e. bestChr and position) to the indices of the * tags in which they are found. */ public HashMap<String, Integer> uniqueSites() { HashMap<String, Integer> snps = new HashMap<String, Integer>(); for (int tag = 0; tag < myNumTags; tag++) { //Visit each tag in TOPM for (int variant = 0; variant < myMaxVariants; variant++) { //Visit each variant in TOPM byte off = getVariantPosOff(tag, variant); if (off == BYTE_MISSING) { continue; } int a = getStartPosition(tag); int b = getVariantPosOff(tag, variant); int c = a + b; String pos = getChromosome(tag) + "\t" + c; snps.put(pos, tag); } } return snps; } public static HashMap<String, Integer> hapmapSites(Alignment file) { HashMap<String, Integer> snps = new HashMap<String, Integer>(); for (int site = 0; site < file.getSiteCount(); site++) { //Visit each site String pos = (file.getLocusName(site) + "\t" + file.getPositionInLocus(site)); if (file.getPositionInLocus(site) > 2000000000) { System.out.println(pos); } snps.put(pos, site); } return snps; } /** * Returns an array whose indices are the number of mappings and whose * elements are the number of tags with that mapping. */ public int[] mappingDistribution() { int[] result = new int[128]; //Only up to 127 multiple mappings are stored. for (int i = 0; i < myNumTags; i++) { if (multimaps[i] > (result.length - 1)) { result[127]++; } if (multimaps[i] == BYTE_MISSING) { result[0]++; continue; } else { result[multimaps[i]]++; } } return result; } }
Fixed translation from Tassel3 to Tassel4 encodings
src/net/maizegenetics/gbs/maps/TagsOnPhysicalMap.java
Fixed translation from Tassel3 to Tassel4 encodings
<ide><path>rc/net/maizegenetics/gbs/maps/TagsOnPhysicalMap.java <ide> currVD[j] = dis.readByte(); <ide> if((currVD[j]>0xf)&&(AlignmentUtils.isHeterozygous(currVD[j]))) {//ascii bytes need to be converted to TASSEL 4 <ide> // System.out.printf("row:%d vd:%d %n", row, variantDefs[row][j]); <del> currVD[j]=NucleotideAlignmentConstants.getNucleotideDiploidByte((char)currVD[j]); <add> currVD[j]=NucleotideAlignmentConstants.getNucleotideAlleleByte(String.valueOf((char)currVD[j])); <ide> } <ide> if(currVO[j]!=TOPMInterface.BYTE_MISSING) numWithData++; <ide> }
Java
apache-2.0
8738fee7894cc7f805b0f8beca30a5aa491f956b
0
DaanHoogland/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,mufaddalq/cloudstack-datera-driver,jcshen007/cloudstack,jcshen007/cloudstack,DaanHoogland/cloudstack,resmo/cloudstack,mufaddalq/cloudstack-datera-driver,DaanHoogland/cloudstack,resmo/cloudstack,DaanHoogland/cloudstack,DaanHoogland/cloudstack,mufaddalq/cloudstack-datera-driver,wido/cloudstack,mufaddalq/cloudstack-datera-driver,resmo/cloudstack,wido/cloudstack,jcshen007/cloudstack,GabrielBrascher/cloudstack,GabrielBrascher/cloudstack,GabrielBrascher/cloudstack,mufaddalq/cloudstack-datera-driver,GabrielBrascher/cloudstack,mufaddalq/cloudstack-datera-driver,resmo/cloudstack,jcshen007/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,wido/cloudstack,DaanHoogland/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,GabrielBrascher/cloudstack,resmo/cloudstack,resmo/cloudstack,jcshen007/cloudstack,wido/cloudstack,DaanHoogland/cloudstack,resmo/cloudstack,wido/cloudstack
// 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 com.cloud.hypervisor.kvm.storage; import java.net.URI; import java.net.URISyntaxException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.HashMap; import java.util.UUID; import com.cloud.hypervisor.kvm.resource.KVMHABase; import com.cloud.hypervisor.kvm.resource.KVMHABase.PoolType; import com.cloud.hypervisor.kvm.resource.KVMHAMonitor; import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk.PhysicalDiskFormat; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.StorageLayer; import com.cloud.utils.exception.CloudRuntimeException; public class KVMStoragePoolManager { private StorageAdaptor _storageAdaptor; private KVMHAMonitor _haMonitor; private final Map<String, Object> _storagePools = new ConcurrentHashMap<String, Object>(); private final Map<String, StorageAdaptor> _storageMapper = new HashMap<String, StorageAdaptor>(); private StorageAdaptor getStorageAdaptor(StoragePoolType type) { // type can be null: LibVirtComputingResource:3238 if (type == null) { return _storageMapper.get("libvirt"); } StorageAdaptor adaptor = _storageMapper.get(type.toString()); if (adaptor == null) { // LibvirtStorageAdaptor is selected by default adaptor = _storageMapper.get("libvirt"); } return adaptor; } private void addStoragePool(String uuid) { synchronized (_storagePools) { if (!_storagePools.containsKey(uuid)) { _storagePools.put(uuid, new Object()); } } } public KVMStoragePoolManager(StorageLayer storagelayer, KVMHAMonitor monitor) { this._storageAdaptor = new LibvirtStorageAdaptor(storagelayer); this._haMonitor = monitor; this._storageMapper.put("libvirt", new LibvirtStorageAdaptor(storagelayer)); // add other storage adaptors here // this._storageMapper.put("newadaptor", new NewStorageAdaptor(storagelayer)); } public KVMStoragePool getStoragePool(StoragePoolType type, String uuid) { StorageAdaptor adaptor = getStorageAdaptor(type); return adaptor.getStoragePool(uuid); } public KVMStoragePool getStoragePoolByURI(String uri) { URI storageUri = null; try { storageUri = new URI(uri); } catch (URISyntaxException e) { throw new CloudRuntimeException(e.toString()); } String sourcePath = null; String uuid = null; String sourceHost = ""; StoragePoolType protocol = null; if (storageUri.getScheme().equalsIgnoreCase("nfs")) { sourcePath = storageUri.getPath(); sourcePath = sourcePath.replace("//", "/"); sourceHost = storageUri.getHost(); uuid = UUID.nameUUIDFromBytes( new String(sourceHost + sourcePath).getBytes()).toString(); protocol = StoragePoolType.NetworkFilesystem; } return createStoragePool(uuid, sourceHost, 0, sourcePath, "", protocol); } public KVMStoragePool createStoragePool( String name, String host, int port, String path, String userInfo, StoragePoolType type) { StorageAdaptor adaptor = getStorageAdaptor(type); KVMStoragePool pool = adaptor.createStoragePool(name, host, port, path, userInfo, type); // LibvirtStorageAdaptor-specific statement if (type == StoragePoolType.NetworkFilesystem) { KVMHABase.NfsStoragePool nfspool = new KVMHABase.NfsStoragePool( pool.getUuid(), host, path, pool.getLocalPath(), PoolType.PrimaryStorage); _haMonitor.addStoragePool(nfspool); } addStoragePool(pool.getUuid()); return pool; } public boolean deleteStoragePool(StoragePoolType type, String uuid) { StorageAdaptor adaptor = getStorageAdaptor(type); _haMonitor.removeStoragePool(uuid); adaptor.deleteStoragePool(uuid); _storagePools.remove(uuid); return true; } public boolean deleteVbdByPath(StoragePoolType type, String diskPath) { StorageAdaptor adaptor = getStorageAdaptor(type); return adaptor.deleteVbdByPath(diskPath); } public KVMPhysicalDisk createDiskFromTemplate(KVMPhysicalDisk template, String name, KVMStoragePool destPool) { StorageAdaptor adaptor = getStorageAdaptor(destPool.getType()); // LibvirtStorageAdaptor-specific statement if (destPool.getType() == StoragePoolType.RBD) { return adaptor.createDiskFromTemplate(template, name, KVMPhysicalDisk.PhysicalDiskFormat.RAW, template.getSize(), destPool); } else if (destPool.getType() == StoragePoolType.CLVM) { return adaptor.createDiskFromTemplate(template, name, KVMPhysicalDisk.PhysicalDiskFormat.RAW, template.getSize(), destPool); } else { return adaptor.createDiskFromTemplate(template, name, KVMPhysicalDisk.PhysicalDiskFormat.QCOW2, template.getSize(), destPool); } } public KVMPhysicalDisk createTemplateFromDisk(KVMPhysicalDisk disk, String name, PhysicalDiskFormat format, long size, KVMStoragePool destPool) { StorageAdaptor adaptor = getStorageAdaptor(destPool.getType()); return adaptor.createTemplateFromDisk(disk, name, format, size, destPool); } public KVMPhysicalDisk copyPhysicalDisk(KVMPhysicalDisk disk, String name, KVMStoragePool destPool) { StorageAdaptor adaptor = getStorageAdaptor(destPool.getType()); return adaptor.copyPhysicalDisk(disk, name, destPool); } public KVMPhysicalDisk createDiskFromSnapshot(KVMPhysicalDisk snapshot, String snapshotName, String name, KVMStoragePool destPool) { StorageAdaptor adaptor = getStorageAdaptor(destPool.getType()); return adaptor.createDiskFromSnapshot(snapshot, snapshotName, name, destPool); } }
plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/KVMStoragePoolManager.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 com.cloud.hypervisor.kvm.storage; import java.net.URI; import java.net.URISyntaxException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.HashMap; import java.util.UUID; import com.cloud.hypervisor.kvm.resource.KVMHABase; import com.cloud.hypervisor.kvm.resource.KVMHABase.PoolType; import com.cloud.hypervisor.kvm.resource.KVMHAMonitor; import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk.PhysicalDiskFormat; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.StorageLayer; import com.cloud.utils.exception.CloudRuntimeException; public class KVMStoragePoolManager { private StorageAdaptor _storageAdaptor; private KVMHAMonitor _haMonitor; private final Map<String, Object> _storagePools = new ConcurrentHashMap<String, Object>(); private final Map<String, StorageAdaptor> _storageMapper = new HashMap<String, StorageAdaptor>(); private StorageAdaptor getStorageAdaptor(StoragePoolType type) { StorageAdaptor adaptor = _storageMapper.get(type.toString()); if (adaptor == null) { // LibvirtStorageAdaptor is selected by default adaptor = _storageMapper.get("libvirt"); } return adaptor; } private void addStoragePool(String uuid) { synchronized (_storagePools) { if (!_storagePools.containsKey(uuid)) { _storagePools.put(uuid, new Object()); } } } public KVMStoragePoolManager(StorageLayer storagelayer, KVMHAMonitor monitor) { this._storageAdaptor = new LibvirtStorageAdaptor(storagelayer); this._haMonitor = monitor; this._storageMapper.put("libvirt", new LibvirtStorageAdaptor(storagelayer)); // add other storage adaptors here // this._storageMapper.put("newadaptor", new NewStorageAdaptor(storagelayer)); } public KVMStoragePool getStoragePool(StoragePoolType type, String uuid) { StorageAdaptor adaptor = getStorageAdaptor(type); return adaptor.getStoragePool(uuid); } public KVMStoragePool getStoragePoolByURI(String uri) { URI storageUri = null; try { storageUri = new URI(uri); } catch (URISyntaxException e) { throw new CloudRuntimeException(e.toString()); } String sourcePath = null; String uuid = null; String sourceHost = ""; StoragePoolType protocol = null; if (storageUri.getScheme().equalsIgnoreCase("nfs")) { sourcePath = storageUri.getPath(); sourcePath = sourcePath.replace("//", "/"); sourceHost = storageUri.getHost(); uuid = UUID.nameUUIDFromBytes( new String(sourceHost + sourcePath).getBytes()).toString(); protocol = StoragePoolType.NetworkFilesystem; } return createStoragePool(uuid, sourceHost, 0, sourcePath, "", protocol); } public KVMStoragePool createStoragePool( String name, String host, int port, String path, String userInfo, StoragePoolType type) { StorageAdaptor adaptor = getStorageAdaptor(type); KVMStoragePool pool = adaptor.createStoragePool(name, host, port, path, userInfo, type); // LibvirtStorageAdaptor-specific statement if (type == StoragePoolType.NetworkFilesystem) { KVMHABase.NfsStoragePool nfspool = new KVMHABase.NfsStoragePool( pool.getUuid(), host, path, pool.getLocalPath(), PoolType.PrimaryStorage); _haMonitor.addStoragePool(nfspool); } addStoragePool(pool.getUuid()); return pool; } public boolean deleteStoragePool(StoragePoolType type, String uuid) { StorageAdaptor adaptor = getStorageAdaptor(type); _haMonitor.removeStoragePool(uuid); adaptor.deleteStoragePool(uuid); _storagePools.remove(uuid); return true; } public boolean deleteVbdByPath(StoragePoolType type, String diskPath) { StorageAdaptor adaptor = getStorageAdaptor(type); return adaptor.deleteVbdByPath(diskPath); } public KVMPhysicalDisk createDiskFromTemplate(KVMPhysicalDisk template, String name, KVMStoragePool destPool) { StorageAdaptor adaptor = getStorageAdaptor(destPool.getType()); // LibvirtStorageAdaptor-specific statement if (destPool.getType() == StoragePoolType.RBD) { return adaptor.createDiskFromTemplate(template, name, KVMPhysicalDisk.PhysicalDiskFormat.RAW, template.getSize(), destPool); } else if (destPool.getType() == StoragePoolType.CLVM) { return adaptor.createDiskFromTemplate(template, name, KVMPhysicalDisk.PhysicalDiskFormat.RAW, template.getSize(), destPool); } else { return adaptor.createDiskFromTemplate(template, name, KVMPhysicalDisk.PhysicalDiskFormat.QCOW2, template.getSize(), destPool); } } public KVMPhysicalDisk createTemplateFromDisk(KVMPhysicalDisk disk, String name, PhysicalDiskFormat format, long size, KVMStoragePool destPool) { StorageAdaptor adaptor = getStorageAdaptor(destPool.getType()); return adaptor.createTemplateFromDisk(disk, name, format, size, destPool); } public KVMPhysicalDisk copyPhysicalDisk(KVMPhysicalDisk disk, String name, KVMStoragePool destPool) { StorageAdaptor adaptor = getStorageAdaptor(destPool.getType()); return adaptor.copyPhysicalDisk(disk, name, destPool); } public KVMPhysicalDisk createDiskFromSnapshot(KVMPhysicalDisk snapshot, String snapshotName, String name, KVMStoragePool destPool) { StorageAdaptor adaptor = getStorageAdaptor(destPool.getType()); return adaptor.createDiskFromSnapshot(snapshot, snapshotName, name, destPool); } }
Summary: small fix causing trouble when shutting down virtual machines
plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/KVMStoragePoolManager.java
Summary: small fix causing trouble when shutting down virtual machines
<ide><path>lugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/KVMStoragePoolManager.java <ide> private final Map<String, StorageAdaptor> _storageMapper = new HashMap<String, StorageAdaptor>(); <ide> <ide> private StorageAdaptor getStorageAdaptor(StoragePoolType type) { <add> // type can be null: LibVirtComputingResource:3238 <add> if (type == null) { <add> return _storageMapper.get("libvirt"); <add> } <ide> StorageAdaptor adaptor = _storageMapper.get(type.toString()); <ide> if (adaptor == null) { <ide> // LibvirtStorageAdaptor is selected by default
Java
apache-2.0
c9a7b8b247e7a1d9e3c007ba98691895806d608d
0
izonder/intellij-community,da1z/intellij-community,vladmm/intellij-community,holmes/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,supersven/intellij-community,xfournet/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,supersven/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,semonte/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,ryano144/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,izonder/intellij-community,samthor/intellij-community,semonte/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,fnouama/intellij-community,ernestp/consulo,ibinti/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,adedayo/intellij-community,petteyg/intellij-community,FHannes/intellij-community,xfournet/intellij-community,semonte/intellij-community,dslomov/intellij-community,slisson/intellij-community,da1z/intellij-community,vvv1559/intellij-community,da1z/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,robovm/robovm-studio,supersven/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,ibinti/intellij-community,clumsy/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,consulo/consulo,xfournet/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,kool79/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,fnouama/intellij-community,apixandru/intellij-community,diorcety/intellij-community,allotria/intellij-community,kool79/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,FHannes/intellij-community,hurricup/intellij-community,allotria/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,jagguli/intellij-community,retomerz/intellij-community,kdwink/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,consulo/consulo,holmes/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,izonder/intellij-community,vladmm/intellij-community,signed/intellij-community,ahb0327/intellij-community,kool79/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,robovm/robovm-studio,consulo/consulo,dslomov/intellij-community,samthor/intellij-community,retomerz/intellij-community,semonte/intellij-community,robovm/robovm-studio,blademainer/intellij-community,ryano144/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,dslomov/intellij-community,amith01994/intellij-community,dslomov/intellij-community,blademainer/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,ernestp/consulo,MER-GROUP/intellij-community,da1z/intellij-community,vladmm/intellij-community,adedayo/intellij-community,kdwink/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,signed/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,suncycheng/intellij-community,signed/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,caot/intellij-community,samthor/intellij-community,kdwink/intellij-community,kdwink/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,caot/intellij-community,clumsy/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,consulo/consulo,orekyuu/intellij-community,supersven/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,FHannes/intellij-community,blademainer/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,caot/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,signed/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,ernestp/consulo,supersven/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,signed/intellij-community,amith01994/intellij-community,retomerz/intellij-community,asedunov/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,vladmm/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,signed/intellij-community,wreckJ/intellij-community,caot/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,caot/intellij-community,FHannes/intellij-community,samthor/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,vladmm/intellij-community,slisson/intellij-community,retomerz/intellij-community,jagguli/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,diorcety/intellij-community,ibinti/intellij-community,dslomov/intellij-community,izonder/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,da1z/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,slisson/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,izonder/intellij-community,caot/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,kool79/intellij-community,diorcety/intellij-community,samthor/intellij-community,caot/intellij-community,allotria/intellij-community,jagguli/intellij-community,amith01994/intellij-community,consulo/consulo,Distrotech/intellij-community,ryano144/intellij-community,blademainer/intellij-community,asedunov/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,kool79/intellij-community,caot/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,asedunov/intellij-community,slisson/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,asedunov/intellij-community,hurricup/intellij-community,holmes/intellij-community,allotria/intellij-community,petteyg/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,allotria/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,semonte/intellij-community,samthor/intellij-community,signed/intellij-community,amith01994/intellij-community,samthor/intellij-community,diorcety/intellij-community,slisson/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,asedunov/intellij-community,FHannes/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,diorcety/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,clumsy/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,ryano144/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,fitermay/intellij-community,apixandru/intellij-community,slisson/intellij-community,da1z/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,semonte/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,samthor/intellij-community,kool79/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,vladmm/intellij-community,robovm/robovm-studio,kdwink/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,retomerz/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,izonder/intellij-community,ryano144/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,ibinti/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,semonte/intellij-community,blademainer/intellij-community,jagguli/intellij-community,apixandru/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,jagguli/intellij-community,allotria/intellij-community,ahb0327/intellij-community,signed/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,ernestp/consulo,fnouama/intellij-community,youdonghai/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,ernestp/consulo,nicolargo/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,signed/intellij-community,slisson/intellij-community,FHannes/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,da1z/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,allotria/intellij-community,xfournet/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,holmes/intellij-community,robovm/robovm-studio,ryano144/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,clumsy/intellij-community,holmes/intellij-community,asedunov/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,supersven/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,amith01994/intellij-community,petteyg/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,supersven/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,blademainer/intellij-community,ernestp/consulo,fitermay/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,asedunov/intellij-community,apixandru/intellij-community,petteyg/intellij-community,kool79/intellij-community,slisson/intellij-community,kdwink/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,consulo/consulo,blademainer/intellij-community,clumsy/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,da1z/intellij-community,gnuhub/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,Lekanich/intellij-community
/* * Copyright 2000-2013 JetBrains s.r.o. * * 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.intellij.openapi.vfs.newvfs.persistent; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ex.ApplicationEx; import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.ShutDownTracker; import com.intellij.openapi.util.io.*; import com.intellij.openapi.vfs.*; import com.intellij.openapi.vfs.newvfs.*; import com.intellij.openapi.vfs.newvfs.events.*; import com.intellij.openapi.vfs.newvfs.impl.FakeVirtualFile; import com.intellij.openapi.vfs.newvfs.impl.VirtualDirectoryImpl; import com.intellij.openapi.vfs.newvfs.impl.VirtualFileSystemEntry; import com.intellij.util.ArrayUtil; import com.intellij.util.Function; import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.ConcurrentIntObjectMap; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.StripedLockIntObjectConcurrentHashMap; import com.intellij.util.io.ReplicatorInputStream; import com.intellij.util.messages.MessageBus; import gnu.trove.*; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import java.io.*; import java.util.*; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * @author max */ public class PersistentFSImpl extends PersistentFS implements ApplicationComponent { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vfs.newvfs.persistent.PersistentFS"); private final MessageBus myEventsBus; private final ReadWriteLock myRootsLock = new ReentrantReadWriteLock(); private final Map<String, VirtualFileSystemEntry> myRoots = new THashMap<String, VirtualFileSystemEntry>(FileUtil.PATH_HASHING_STRATEGY); private final TIntObjectHashMap<VirtualFileSystemEntry> myRootsById = new TIntObjectHashMap<VirtualFileSystemEntry>(); private final ConcurrentIntObjectMap<VirtualFileSystemEntry> myIdToDirCache = new StripedLockIntObjectConcurrentHashMap<VirtualFileSystemEntry>(); private final Object myInputLock = new Object(); @Nullable private volatile VirtualFileSystemEntry myFakeRoot; private boolean myShutDown = false; public PersistentFSImpl(@NotNull final MessageBus bus) { myEventsBus = bus; ShutDownTracker.getInstance().registerShutdownTask(new Runnable() { @Override public void run() { performShutdown(); } }); } @Override public void disposeComponent() { performShutdown(); } private synchronized void performShutdown() { if (!myShutDown) { myShutDown = true; LOG.info("VFS dispose started"); FSRecords.dispose(); LOG.info("VFS dispose completed"); } } @Override @NonNls @NotNull public String getComponentName() { return "app.component.PersistentFS"; } @Override public void initComponent() { FSRecords.connect(); } @Override public boolean areChildrenLoaded(@NotNull final VirtualFile dir) { return areChildrenLoaded(getFileId(dir)); } @Override public long getCreationTimestamp() { return FSRecords.getCreationTimestamp(); } @NotNull private static NewVirtualFileSystem getDelegate(@NotNull VirtualFile file) { return (NewVirtualFileSystem)file.getFileSystem(); } @Override public boolean wereChildrenAccessed(@NotNull final VirtualFile dir) { return FSRecords.wereChildrenAccessed(getFileId(dir)); } @Override @NotNull public String[] list(@NotNull final VirtualFile file) { int id = getFileId(file); FSRecords.NameId[] nameIds = FSRecords.listAll(id); if (!areChildrenLoaded(id)) { nameIds = persistAllChildren(file, id, nameIds); } return ContainerUtil.map2Array(nameIds, String.class, new Function<FSRecords.NameId, String>() { @Override public String fun(FSRecords.NameId id) { return id.name; } }); } @Override @NotNull public String[] listPersisted(@NotNull VirtualFile parent) { return listPersisted(FSRecords.list(getFileId(parent))); } @NotNull private static String[] listPersisted(@NotNull int[] childrenIds) { String[] names = ArrayUtil.newStringArray(childrenIds.length); for (int i = 0; i < childrenIds.length; i++) { names[i] = FSRecords.getName(childrenIds[i]); } return names; } @NotNull private static FSRecords.NameId[] persistAllChildren(@NotNull final VirtualFile file, final int id, @NotNull FSRecords.NameId[] current) { final NewVirtualFileSystem fs = replaceWithNativeFS(getDelegate(file)); String[] delegateNames = VfsUtil.filterNames(fs.list(file)); if (delegateNames.length == 0 && current.length > 0) { return current; } THashMap<String, FSRecords.NameId> result = new THashMap<String, FSRecords.NameId>(); if (current.length == 0) { for (String name : delegateNames) { result.put(name, new FSRecords.NameId(-1, name)); } } else { for (FSRecords.NameId nameId : current) { result.put(nameId.name, nameId); } for (String name : delegateNames) { if (!result.containsKey(name)) { result.put(name, new FSRecords.NameId(-1, name)); } } } final TIntArrayList childrenIds = new TIntArrayList(result.size()); final List<FSRecords.NameId> nameIds = ContainerUtil.newArrayListWithExpectedSize(result.size()); result.forEachValue(new TObjectProcedure<FSRecords.NameId>() { @Override public boolean execute(FSRecords.NameId nameId) { if (nameId.id < 0) { FakeVirtualFile child = new FakeVirtualFile(file, nameId.name); FileAttributes attributes = fs.getAttributes(child); if (attributes != null) { int childId = createAndFillRecord(fs, child, id, attributes); nameId = new FSRecords.NameId(childId, nameId.name); } } if (nameId.id > 0) { childrenIds.add(nameId.id); nameIds.add(nameId); } return true; } }); FSRecords.updateList(id, childrenIds.toNativeArray()); setChildrenCached(id); return nameIds.toArray(new FSRecords.NameId[nameIds.size()]); } public static void setChildrenCached(int id) { int flags = FSRecords.getFlags(id); FSRecords.setFlags(id, flags | CHILDREN_CACHED_FLAG, true); } @Override @NotNull public FSRecords.NameId[] listAll(@NotNull VirtualFile parent) { final int parentId = getFileId(parent); FSRecords.NameId[] nameIds = FSRecords.listAll(parentId); if (!areChildrenLoaded(parentId)) { return persistAllChildren(parent, parentId, nameIds); } return nameIds; } private static boolean areChildrenLoaded(final int parentId) { return (FSRecords.getFlags(parentId) & CHILDREN_CACHED_FLAG) != 0; } @Override @Nullable public DataInputStream readAttribute(@NotNull final VirtualFile file, @NotNull final FileAttribute att) { return FSRecords.readAttributeWithLock(getFileId(file), att.getId()); } @Override @NotNull public DataOutputStream writeAttribute(@NotNull final VirtualFile file, @NotNull final FileAttribute att) { return FSRecords.writeAttribute(getFileId(file), att.getId(), att.isFixedSize()); } @Nullable private static DataInputStream readContent(@NotNull VirtualFile file) { return FSRecords.readContent(getFileId(file)); } @Nullable private static DataInputStream readContentById(int contentId) { return FSRecords.readContentById(contentId); } @NotNull private static DataOutputStream writeContent(@NotNull VirtualFile file, boolean readOnly) { return FSRecords.writeContent(getFileId(file), readOnly); } private static void writeContent(@NotNull VirtualFile file, ByteSequence content, boolean readOnly) throws IOException { FSRecords.writeContent(getFileId(file), content, readOnly); } @Override public int storeUnlinkedContent(@NotNull byte[] bytes) { return FSRecords.storeUnlinkedContent(bytes); } @Override public int getModificationCount(@NotNull final VirtualFile file) { return FSRecords.getModCount(getFileId(file)); } @Override public int getCheapFileSystemModificationCount() { return FSRecords.getLocalModCount(); } @Override public int getFilesystemModificationCount() { return FSRecords.getModCount(); } private static boolean writeAttributesToRecord(final int id, final int parentId, @NotNull VirtualFile file, @NotNull NewVirtualFileSystem fs, @NotNull FileAttributes attributes) { String name = file.getName(); if (!name.isEmpty()) { if (namesEqual(fs, name, FSRecords.getName(id))) return false; // TODO: Handle root attributes change. } else { if (areChildrenLoaded(id)) return false; // TODO: hack } FSRecords.setParent(id, parentId); FSRecords.setName(id, name); FSRecords.setTimestamp(id, attributes.lastModified); FSRecords.setLength(id, attributes.isDirectory() ? -1L : attributes.length); FSRecords.setFlags(id, (attributes.isDirectory() ? IS_DIRECTORY_FLAG : 0) | (attributes.isWritable() ? 0 : IS_READ_ONLY) | (attributes.isSymLink() ? IS_SYMLINK : 0) | (attributes.isSpecial() ? IS_SPECIAL : 0), true); return true; } @Override public int getFileAttributes(int id) { assert id > 0; //noinspection MagicConstant return FSRecords.getFlags(id); } @Override public boolean isDirectory(@NotNull final VirtualFile file) { return isDirectory(getFileAttributes(getFileId(file))); } private static int getParent(final int id) { assert id > 0; return FSRecords.getParent(id); } private static boolean namesEqual(@NotNull VirtualFileSystem fs, @NotNull String n1, String n2) { return ((NewVirtualFileSystem)fs).isCaseSensitive() ? n1.equals(n2) : n1.equalsIgnoreCase(n2); } @Override public boolean exists(@NotNull final VirtualFile fileOrDirectory) { return ((VirtualFileWithId)fileOrDirectory).getId() > 0; } @Override public long getTimeStamp(@NotNull final VirtualFile file) { return FSRecords.getTimestamp(getFileId(file)); } @Override public void setTimeStamp(@NotNull final VirtualFile file, final long modStamp) throws IOException { final int id = getFileId(file); FSRecords.setTimestamp(id, modStamp); getDelegate(file).setTimeStamp(file, modStamp); } private static int getFileId(@NotNull VirtualFile file) { final int id = ((VirtualFileWithId)file).getId(); if (id <= 0) { throw new InvalidVirtualFileAccessException(file); } return id; } @Override public boolean isSymLink(@NotNull VirtualFile file) { return isSymLink(getFileAttributes(getFileId(file))); } @Override public String resolveSymLink(@NotNull VirtualFile file) { throw new UnsupportedOperationException(); } @Override public boolean isSpecialFile(@NotNull VirtualFile file) { return isSpecialFile(getFileAttributes(getFileId(file))); } @Override public boolean isWritable(@NotNull final VirtualFile file) { return (getFileAttributes(getFileId(file)) & IS_READ_ONLY) == 0; } @Override public void setWritable(@NotNull final VirtualFile file, final boolean writableFlag) throws IOException { getDelegate(file).setWritable(file, writableFlag); processEvent(new VFilePropertyChangeEvent(this, file, VirtualFile.PROP_WRITABLE, isWritable(file), writableFlag, false)); } @Override public int getId(@NotNull final VirtualFile parent, @NotNull final String childName, @NotNull final NewVirtualFileSystem fs) { int parentId = getFileId(parent); if (parent == myFakeRoot) { // children of the fake root must be the FS roots only myRootsLock.readLock().lock(); try { String rootUrl = fs.getProtocol() + "://" + VfsImplUtil.normalize(fs, childName); VirtualFileSystemEntry root = myRoots.get(rootUrl); return root == null ? 0 : root.getId(); } finally { myRootsLock.readLock().unlock(); } } int[] children = FSRecords.list(parentId); if (children.length > 0) { // fast path, check that some child has same nameId as given name, this avoid O(N) on retrieving names for processing non-cached children int nameId = FSRecords.getNameId(childName); for (final int childId : children) { if (nameId == FSRecords.getNameId(childId)) { return childId; } } // for case sensitive system the above check is exhaustive in consistent state of vfs } for (final int childId : children) { if (namesEqual(fs, childName, FSRecords.getName(childId))) return childId; } final VirtualFile fake = new FakeVirtualFile(parent, childName); final FileAttributes attributes = fs.getAttributes(fake); if (attributes != null) { final int child = createAndFillRecord(fs, fake, parentId, attributes); FSRecords.updateList(parentId, ArrayUtil.append(children, child)); return child; } return 0; } @Override public long getLength(@NotNull final VirtualFile file) { long len; if (mustReloadContent(file)) { len = reloadLengthFromDelegate(file, getDelegate(file)); } else { final int id = getFileId(file); len = FSRecords.getLength(id); } return len; } @Override public VirtualFile copyFile(final Object requestor, @NotNull final VirtualFile file, @NotNull final VirtualFile newParent, @NotNull final String copyName) throws IOException { getDelegate(file).copyFile(requestor, file, newParent, copyName); processEvent(new VFileCopyEvent(requestor, file, newParent, copyName)); final VirtualFile child = newParent.findChild(copyName); if (child == null) { throw new IOException("Cannot create child"); } return child; } @Override public VirtualFile createChildDirectory(final Object requestor, @NotNull final VirtualFile parent, @NotNull final String dir) throws IOException { getDelegate(parent).createChildDirectory(requestor, parent, dir); processEvent(new VFileCreateEvent(requestor, parent, dir, true, false)); final VirtualFile child = parent.findChild(dir); if (child == null) { throw new IOException("Cannot create child directory '" + dir + "' at " + parent.getPath()); } return child; } @Override public VirtualFile createChildFile(final Object requestor, @NotNull final VirtualFile parent, @NotNull final String file) throws IOException { getDelegate(parent).createChildFile(requestor, parent, file); processEvent(new VFileCreateEvent(requestor, parent, file, false, false)); final VirtualFile child = parent.findChild(file); if (child == null) { throw new IOException("Cannot create child file '" + file + "' at " + parent.getPath()); } return child; } @Override public void deleteFile(final Object requestor, @NotNull final VirtualFile file) throws IOException { final NewVirtualFileSystem delegate = getDelegate(file); delegate.deleteFile(requestor, file); if (!delegate.exists(file)) { processEvent(new VFileDeleteEvent(requestor, file, false)); } } @Override public void renameFile(final Object requestor, @NotNull final VirtualFile file, @NotNull final String newName) throws IOException { getDelegate(file).renameFile(requestor, file, newName); processEvent(new VFilePropertyChangeEvent(requestor, file, VirtualFile.PROP_NAME, file.getName(), newName, false)); } @Override @NotNull public byte[] contentsToByteArray(@NotNull final VirtualFile file) throws IOException { return contentsToByteArray(file, true); } @Override @NotNull public byte[] contentsToByteArray(@NotNull final VirtualFile file, boolean cacheContent) throws IOException { InputStream contentStream = null; boolean reloadFromDelegate; boolean outdated; int fileId; synchronized (myInputLock) { fileId = getFileId(file); outdated = checkFlag(fileId, MUST_RELOAD_CONTENT) || FSRecords.getLength(fileId) == -1L; reloadFromDelegate = outdated || (contentStream = readContent(file)) == null; } if (reloadFromDelegate) { final NewVirtualFileSystem delegate = getDelegate(file); final byte[] content; if (outdated) { // in this case, file can have out-of-date length. so, update it first (it's needed for correct contentsToByteArray() work) // see IDEA-90813 for possible bugs FSRecords.setLength(fileId, delegate.getLength(file)); content = delegate.contentsToByteArray(file); } else { // a bit of optimization content = delegate.contentsToByteArray(file); FSRecords.setLength(fileId, content.length); } ApplicationEx application = (ApplicationEx)ApplicationManager.getApplication(); // we should cache every local files content // because the local history feature is currently depends on this cache, // perforce offline mode as well if ((!delegate.isReadOnly() || // do not cache archive content unless asked cacheContent && !application.isInternal() && !application.isUnitTestMode()) && content.length <= PersistentFSConstants.FILE_LENGTH_TO_CACHE_THRESHOLD) { synchronized (myInputLock) { writeContent(file, new ByteSequence(content), delegate.isReadOnly()); setFlag(file, MUST_RELOAD_CONTENT, false); } } return content; } else { try { final int length = (int)file.getLength(); assert length >= 0 : file; return FileUtil.loadBytes(contentStream, length); } catch (IOException e) { throw FSRecords.handleError(e); } } } @Override @NotNull public byte[] contentsToByteArray(int contentId) throws IOException { final DataInputStream stream = readContentById(contentId); assert stream != null : contentId; return FileUtil.loadBytes(stream); } @Override @NotNull public InputStream getInputStream(@NotNull final VirtualFile file) throws IOException { synchronized (myInputLock) { InputStream contentStream; if (mustReloadContent(file) || (contentStream = readContent(file)) == null) { NewVirtualFileSystem delegate = getDelegate(file); long len = reloadLengthFromDelegate(file, delegate); InputStream nativeStream = delegate.getInputStream(file); if (len > PersistentFSConstants.FILE_LENGTH_TO_CACHE_THRESHOLD) return nativeStream; return createReplicator(file, nativeStream, len, delegate.isReadOnly()); } else { return contentStream; } } } private static long reloadLengthFromDelegate(@NotNull VirtualFile file, @NotNull NewVirtualFileSystem delegate) { final long len = delegate.getLength(file); FSRecords.setLength(getFileId(file), len); return len; } private InputStream createReplicator(@NotNull final VirtualFile file, final InputStream nativeStream, final long fileLength, final boolean readOnly) throws IOException { if (nativeStream instanceof BufferExposingByteArrayInputStream) { // optimization BufferExposingByteArrayInputStream byteStream = (BufferExposingByteArrayInputStream )nativeStream; byte[] bytes = byteStream.getInternalBuffer(); storeContentToStorage(fileLength, file, readOnly, bytes, bytes.length); return nativeStream; } @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") final BufferExposingByteArrayOutputStream cache = new BufferExposingByteArrayOutputStream((int)fileLength); return new ReplicatorInputStream(nativeStream, cache) { @Override public void close() throws IOException { super.close(); storeContentToStorage(fileLength, file, readOnly, cache.getInternalBuffer(), cache.size()); } }; } private void storeContentToStorage(long fileLength, @NotNull VirtualFile file, boolean readOnly, @NotNull byte[] bytes, int bytesLength) throws IOException { synchronized (myInputLock) { if (bytesLength == fileLength) { writeContent(file, new ByteSequence(bytes, 0, bytesLength), readOnly); setFlag(file, MUST_RELOAD_CONTENT, false); } else { setFlag(file, MUST_RELOAD_CONTENT, true); } } } private static boolean mustReloadContent(@NotNull VirtualFile file) { int fileId = getFileId(file); return checkFlag(fileId, MUST_RELOAD_CONTENT) || FSRecords.getLength(fileId) == -1L; } @Override @NotNull public OutputStream getOutputStream(@NotNull final VirtualFile file, final Object requestor, final long modStamp, final long timeStamp) throws IOException { final VFileContentChangeEvent event = new VFileContentChangeEvent(requestor, file, file.getModificationStamp(), modStamp, false); final List<VFileContentChangeEvent> events = Collections.singletonList(event); final BulkFileListener publisher = myEventsBus.syncPublisher(VirtualFileManager.VFS_CHANGES); publisher.before(events); return new ByteArrayOutputStream() { private boolean closed; // protection against user calling .close() twice @Override public void close() throws IOException { if (closed) return; super.close(); NewVirtualFileSystem delegate = getDelegate(file); OutputStream ioFileStream = delegate.getOutputStream(file, requestor, modStamp, timeStamp); // FSRecords.ContentOutputStream already buffered, no need to wrap in BufferedStream OutputStream persistenceStream = writeContent(file, delegate.isReadOnly()); try { persistenceStream.write(buf, 0, count); } finally { try { ioFileStream.write(buf, 0, count); } finally { closed = true; persistenceStream.close(); ioFileStream.close(); executeTouch(file, false, event.getModificationStamp()); publisher.after(events); } } } }; } @Override public int acquireContent(@NotNull VirtualFile file) { return FSRecords.acquireFileContent(getFileId(file)); } @Override public void releaseContent(int contentId) { FSRecords.releaseContent(contentId); } @Override public int getCurrentContentId(@NotNull VirtualFile file) { return FSRecords.getContentId(getFileId(file)); } @Override public void moveFile(final Object requestor, @NotNull final VirtualFile file, @NotNull final VirtualFile newParent) throws IOException { getDelegate(file).moveFile(requestor, file, newParent); processEvent(new VFileMoveEvent(requestor, file, newParent)); } private void processEvent(@NotNull VFileEvent event) { processEvents(Collections.singletonList(event)); } private static class EventWrapper { private final VFileDeleteEvent event; private final int id; private EventWrapper(final VFileDeleteEvent event, final int id) { this.event = event; this.id = id; } } @NotNull private static final Comparator<EventWrapper> DEPTH_COMPARATOR = new Comparator<EventWrapper>() { @Override public int compare(@NotNull final EventWrapper o1, @NotNull final EventWrapper o2) { return o1.event.getFileDepth() - o2.event.getFileDepth(); } }; @NotNull private static List<VFileEvent> validateEvents(@NotNull List<VFileEvent> events) { final List<EventWrapper> deletionEvents = ContainerUtil.newArrayList(); for (int i = 0, size = events.size(); i < size; i++) { final VFileEvent event = events.get(i); if (event instanceof VFileDeleteEvent && event.isValid()) { deletionEvents.add(new EventWrapper((VFileDeleteEvent)event, i)); } } ContainerUtil.quickSort(deletionEvents, DEPTH_COMPARATOR); final TIntHashSet invalidIDs = new TIntHashSet(deletionEvents.size()); final List<VirtualFile> dirsToBeDeleted = new ArrayList<VirtualFile>(); nextEvent: for (EventWrapper wrapper : deletionEvents) { final VirtualFile candidate = wrapper.event.getFile(); for (VirtualFile file : dirsToBeDeleted) { if (VfsUtilCore.isAncestor(file, candidate, false)) { invalidIDs.add(wrapper.id); continue nextEvent; } } if (candidate.isDirectory()) { dirsToBeDeleted.add(candidate); } } final List<VFileEvent> filtered = ContainerUtil.newArrayListWithCapacity(events.size() - invalidIDs.size()); for (int i = 0, size = events.size(); i < size; i++) { final VFileEvent event = events.get(i); if (event.isValid() && !(event instanceof VFileDeleteEvent && invalidIDs.contains(i))) { filtered.add(event); } } return filtered; } @Override public void processEvents(@NotNull List<VFileEvent> events) { ApplicationManager.getApplication().assertWriteAccessAllowed(); List<VFileEvent> validated = validateEvents(events); BulkFileListener publisher = myEventsBus.syncPublisher(VirtualFileManager.VFS_CHANGES); publisher.before(validated); for (VFileEvent event : validated) { applyEvent(event); } publisher.after(validated); } @Override @Nullable public VirtualFileSystemEntry findRoot(@NotNull String basePath, @NotNull NewVirtualFileSystem fs) { String rootUrl = fs.getProtocol() + "://" + VfsImplUtil.normalize(fs, basePath); VirtualFileSystemEntry root; myRootsLock.readLock().lock(); try { root = basePath.isEmpty() ? myFakeRoot : myRoots.get(rootUrl); if (root != null) return root; } finally { myRootsLock.readLock().unlock(); } myRootsLock.writeLock().lock(); try { root = basePath.isEmpty() ? myFakeRoot : myRoots.get(rootUrl); if (root != null) return root; int rootId = FSRecords.findRootRecord(rootUrl); root = myRootsById.get(rootId); if (root != null) return root; if (basePath.isEmpty()) { // fake super-root root = new VirtualDirectoryImpl("", null, fs, rootId, 0) { @SuppressWarnings("NonSynchronizedMethodOverridesSynchronizedMethod") @Override @NotNull public VirtualFile[] getChildren() { return getRoots(getFileSystem()); } @Override public VirtualFileSystemEntry findChild(@NotNull String name) { if (name.isEmpty()) return null; return findRoot(name, getFileSystem()); } }; } else if (fs instanceof JarFileSystem) { // optimization: for jar roots do not store base path in the myName field, use local FS file's getPath() String parentPath = basePath.substring(0, basePath.indexOf(JarFileSystem.JAR_SEPARATOR)); VirtualFile parentLocalFile = LocalFileSystem.getInstance().findFileByPath(parentPath); if (parentLocalFile == null) return null; // check one more time since the findFileByPath could have created the root (by reentering the findRoot) root = myRoots.get(rootUrl); if (root != null) return root; root = myRootsById.get(rootId); if (root != null) return root; root = new JarRoot(fs, rootId, parentLocalFile); } else { root = new VirtualDirectoryImpl(basePath, null, fs, rootId, 0); } final FileAttributes attributes = fs.getAttributes(root); if (attributes == null) { return null; } final boolean newRoot = writeAttributesToRecord(rootId, 0, root, fs, attributes); if (!newRoot) { if (attributes.lastModified != FSRecords.getTimestamp(rootId)) { root.markDirtyRecursively(); } } if (basePath.isEmpty()) { myFakeRoot = root; } else { myRoots.put(rootUrl, root); myRootsById.put(rootId, root); if (rootId != root.getId()) throw new AssertionError(); } return root; } finally { myRootsLock.writeLock().unlock(); } } @Override public void clearIdCache() { myIdToDirCache.clear(); } private static final int DEPTH_LIMIT = 75; @Override @Nullable public NewVirtualFile findFileById(final int id) { return findFileById(id, false, null, 0); } @Override public NewVirtualFile findFileByIdIfCached(final int id) { return findFileById(id, true, null, 0); } @Nullable private VirtualFileSystemEntry findFileById(int id, boolean cachedOnly, TIntArrayList visited, int mask) { VirtualFileSystemEntry cached = myIdToDirCache.get(id); if (cached != null) return cached; if (visited != null && (visited.size() >= DEPTH_LIMIT || (mask & id) == id && visited.contains(id))) { @NonNls String sb = "Dead loop detected in persistent FS (id=" + id + " cached-only=" + cachedOnly + "):"; for (int i = 0; i < visited.size(); i++) { int _id = visited.get(i); sb += "\n " + _id + " '" + getName(_id) + "' " + String.format("%02x", getFileAttributes(_id)) + ' ' + myIdToDirCache.containsKey(_id); } LOG.error(sb); return null; } if (visited == null) visited = new TIntArrayList(DEPTH_LIMIT); visited.add(id); int parentId = getParent(id); VirtualFileSystemEntry result; if (parentId == 0) { myRootsLock.readLock().lock(); try { result = myRootsById.get(id); } finally { myRootsLock.readLock().unlock(); } } else { VirtualFileSystemEntry parentFile = findFileById(parentId, cachedOnly, visited, mask |= id); if (parentFile instanceof VirtualDirectoryImpl) { result = ((VirtualDirectoryImpl)parentFile).findChildById(id, cachedOnly); } else { result = null; } } if (result != null && result.isDirectory()) { VirtualFileSystemEntry old = myIdToDirCache.put(id, result); if (old != null) result = old; } return result; } @Override @NotNull public VirtualFile[] getRoots() { myRootsLock.readLock().lock(); try { Collection<VirtualFileSystemEntry> roots = myRoots.values(); return VfsUtilCore.toVirtualFileArray(roots); } finally { myRootsLock.readLock().unlock(); } } @Override @NotNull public VirtualFile[] getRoots(@NotNull final NewVirtualFileSystem fs) { final List<VirtualFile> roots = new ArrayList<VirtualFile>(); myRootsLock.readLock().lock(); try { for (NewVirtualFile root : myRoots.values()) { if (root.getFileSystem() == fs) { roots.add(root); } } } finally { myRootsLock.readLock().unlock(); } return VfsUtilCore.toVirtualFileArray(roots); } @Override @NotNull public VirtualFile[] getLocalRoots() { final List<VirtualFile> roots = new ArrayList<VirtualFile>(); myRootsLock.readLock().lock(); try { for (NewVirtualFile root : myRoots.values()) { if (root.isInLocalFileSystem()) { roots.add(root); } } } finally { myRootsLock.readLock().unlock(); } return VfsUtilCore.toVirtualFileArray(roots); } private VirtualFileSystemEntry applyEvent(@NotNull VFileEvent event) { try { if (event instanceof VFileCreateEvent) { final VFileCreateEvent createEvent = (VFileCreateEvent)event; return executeCreateChild(createEvent.getParent(), createEvent.getChildName()); } else if (event instanceof VFileDeleteEvent) { final VFileDeleteEvent deleteEvent = (VFileDeleteEvent)event; executeDelete(deleteEvent.getFile()); } else if (event instanceof VFileContentChangeEvent) { final VFileContentChangeEvent contentUpdateEvent = (VFileContentChangeEvent)event; executeTouch(contentUpdateEvent.getFile(), contentUpdateEvent.isFromRefresh(), contentUpdateEvent.getModificationStamp()); } else if (event instanceof VFileCopyEvent) { final VFileCopyEvent copyEvent = (VFileCopyEvent)event; return executeCreateChild(copyEvent.getNewParent(), copyEvent.getNewChildName()); } else if (event instanceof VFileMoveEvent) { final VFileMoveEvent moveEvent = (VFileMoveEvent)event; executeMove(moveEvent.getFile(), moveEvent.getNewParent()); } else if (event instanceof VFilePropertyChangeEvent) { final VFilePropertyChangeEvent propertyChangeEvent = (VFilePropertyChangeEvent)event; if (VirtualFile.PROP_NAME.equals(propertyChangeEvent.getPropertyName())) { executeRename(propertyChangeEvent.getFile(), (String)propertyChangeEvent.getNewValue()); } else if (VirtualFile.PROP_WRITABLE.equals(propertyChangeEvent.getPropertyName())) { executeSetWritable(propertyChangeEvent.getFile(), ((Boolean)propertyChangeEvent.getNewValue()).booleanValue()); } } } catch (Exception e) { // Exception applying single event should not prevent other events from applying. LOG.error(e); } return null; } @NotNull @NonNls public String toString() { return "PersistentFS"; } private static VirtualFileSystemEntry executeCreateChild(@NotNull VirtualFile parent, @NotNull String name) { final NewVirtualFileSystem delegate = getDelegate(parent); final VirtualFile fake = new FakeVirtualFile(parent, name); final FileAttributes attributes = delegate.getAttributes(fake); if (attributes != null) { final int parentId = getFileId(parent); final int childId = createAndFillRecord(delegate, fake, parentId, attributes); appendIdToParentList(parentId, childId); assert parent instanceof VirtualDirectoryImpl : parent; final VirtualDirectoryImpl dir = (VirtualDirectoryImpl)parent; VirtualFileSystemEntry child = dir.createChild(name, childId, dir.getFileSystem()); dir.addChild(child); return child; } return null; } private static int createAndFillRecord(@NotNull NewVirtualFileSystem delegateSystem, @NotNull VirtualFile delegateFile, int parentId, @NotNull FileAttributes attributes) { final int childId = FSRecords.createRecord(); writeAttributesToRecord(childId, parentId, delegateFile, delegateSystem, attributes); return childId; } private static void appendIdToParentList(final int parentId, final int childId) { int[] childrenList = FSRecords.list(parentId); childrenList = ArrayUtil.append(childrenList, childId); FSRecords.updateList(parentId, childrenList); } private void executeDelete(@NotNull VirtualFile file) { if (!file.exists()) { LOG.error("Deleting a file, which does not exist: " + file.getPath()); return; } clearIdCache(); int id = getFileId(file); FSRecords.deleteRecordRecursively(id); final VirtualFile parent = file.getParent(); final int parentId = parent == null ? 0 : getFileId(parent); if (parentId == 0) { myRootsLock.writeLock().lock(); try { String rootUrl = file.getUrl(); myRoots.remove(rootUrl); myRootsById.remove(id); FSRecords.deleteRootRecord(id); } finally { myRootsLock.writeLock().unlock(); } } else { removeIdFromParentList(parentId, id, parent, file); VirtualDirectoryImpl directory = (VirtualDirectoryImpl)file.getParent(); assert directory != null : file; directory.removeChild(file); } invalidateSubtree(file); } private static void invalidateSubtree(@NotNull VirtualFile file) { final VirtualFileSystemEntry impl = (VirtualFileSystemEntry)file; impl.invalidate(); for (VirtualFile child : impl.getCachedChildren()) { invalidateSubtree(child); } } private static void removeIdFromParentList(final int parentId, final int id, @NotNull VirtualFile parent, VirtualFile file) { int[] childList = FSRecords.list(parentId); int index = ArrayUtil.indexOf(childList, id); if (index == -1) { throw new RuntimeException("Cannot find child (" + id + ")" + file + "\n\tin (" + parentId + ")" + parent + "\n\tactual children:" + Arrays.toString(childList)); } childList = ArrayUtil.remove(childList, index); FSRecords.updateList(parentId, childList); } private static void executeRename(@NotNull VirtualFile file, @NotNull final String newName) { ((VirtualFileSystemEntry)file).setNewName(newName); final int id = getFileId(file); FSRecords.setName(id, newName); } private static void executeSetWritable(@NotNull VirtualFile file, final boolean writableFlag) { setFlag(file, IS_READ_ONLY, !writableFlag); } private static void setFlag(@NotNull VirtualFile file, int mask, boolean value) { setFlag(getFileId(file), mask, value); } private static void setFlag(final int id, final int mask, final boolean value) { int oldFlags = FSRecords.getFlags(id); int flags = value ? oldFlags | mask : oldFlags & ~mask; if (oldFlags != flags) { FSRecords.setFlags(id, flags, true); } } private static boolean checkFlag(int fileId, int mask) { return (FSRecords.getFlags(fileId) & mask) != 0; } private static void executeTouch(@NotNull VirtualFile file, boolean reloadContentFromDelegate, long newModificationStamp) { if (reloadContentFromDelegate) { setFlag(file, MUST_RELOAD_CONTENT, true); } final NewVirtualFileSystem delegate = getDelegate(file); final FileAttributes attributes = delegate.getAttributes(file); FSRecords.setLength(getFileId(file), attributes != null ? attributes.length : DEFAULT_LENGTH); FSRecords.setTimestamp(getFileId(file), attributes != null ? attributes.lastModified : DEFAULT_TIMESTAMP); ((VirtualFileSystemEntry)file).setModificationStamp(newModificationStamp); } private void executeMove(@NotNull VirtualFile file, @NotNull VirtualFile newParent) { clearIdCache(); final int fileId = getFileId(file); final int newParentId = getFileId(newParent); final int oldParentId = getFileId(file.getParent()); removeIdFromParentList(oldParentId, fileId, file.getParent(), file); appendIdToParentList(newParentId, fileId); ((VirtualFileSystemEntry)file).setParent(newParent); FSRecords.setParent(fileId, newParentId); } @Override public String getName(int id) { assert id > 0; return FSRecords.getName(id); } @TestOnly public void cleanPersistedContents() { try { final int[] roots = FSRecords.listRoots(); for (int root : roots) { cleanPersistedContentsRecursively(root); } } catch (IOException e) { throw new RuntimeException(e); } } @TestOnly private void cleanPersistedContentsRecursively(int id) { if (isDirectory(getFileAttributes(id))) { for (int child : FSRecords.list(id)) { cleanPersistedContentsRecursively(child); } } else { setFlag(id, MUST_RELOAD_CONTENT, true); } } private static class JarRoot extends VirtualDirectoryImpl { private final VirtualFile myParentLocalFile; private JarRoot(@NotNull NewVirtualFileSystem fs, int rootId, @NotNull VirtualFile parentLocalFile) { super("", null, fs, rootId, 0); myParentLocalFile = parentLocalFile; } @NotNull @Override public String getName() { return myParentLocalFile.getName(); } @Override protected String rawName() { return myParentLocalFile.getPath() + JarFileSystem.JAR_SEPARATOR; } @Override public void setParent(@NotNull VirtualFile newParent) { throw new IncorrectOperationException(); } } }
platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/PersistentFSImpl.java
/* * Copyright 2000-2013 JetBrains s.r.o. * * 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.intellij.openapi.vfs.newvfs.persistent; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ex.ApplicationEx; import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.ShutDownTracker; import com.intellij.openapi.util.io.*; import com.intellij.openapi.vfs.*; import com.intellij.openapi.vfs.newvfs.*; import com.intellij.openapi.vfs.newvfs.events.*; import com.intellij.openapi.vfs.newvfs.impl.FakeVirtualFile; import com.intellij.openapi.vfs.newvfs.impl.VirtualDirectoryImpl; import com.intellij.openapi.vfs.newvfs.impl.VirtualFileSystemEntry; import com.intellij.util.ArrayUtil; import com.intellij.util.Function; import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.ConcurrentIntObjectMap; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.StripedLockIntObjectConcurrentHashMap; import com.intellij.util.io.ReplicatorInputStream; import com.intellij.util.messages.MessageBus; import gnu.trove.*; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import java.io.*; import java.util.*; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * @author max */ public class PersistentFSImpl extends PersistentFS implements ApplicationComponent { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vfs.newvfs.persistent.PersistentFS"); private final MessageBus myEventsBus; private final ReadWriteLock myRootsLock = new ReentrantReadWriteLock(); private final Map<String, VirtualFileSystemEntry> myRoots = new THashMap<String, VirtualFileSystemEntry>(FileUtil.PATH_HASHING_STRATEGY); private final TIntObjectHashMap<VirtualFileSystemEntry> myRootsById = new TIntObjectHashMap<VirtualFileSystemEntry>(); private final ConcurrentIntObjectMap<VirtualFileSystemEntry> myIdToDirCache = new StripedLockIntObjectConcurrentHashMap<VirtualFileSystemEntry>(); private final Object myInputLock = new Object(); @Nullable private VirtualFileSystemEntry myFakeRoot; private boolean myShutDown = false; public PersistentFSImpl(@NotNull final MessageBus bus) { myEventsBus = bus; ShutDownTracker.getInstance().registerShutdownTask(new Runnable() { @Override public void run() { performShutdown(); } }); } @Override public void disposeComponent() { performShutdown(); } private synchronized void performShutdown() { if (!myShutDown) { myShutDown = true; LOG.info("VFS dispose started"); FSRecords.dispose(); LOG.info("VFS dispose completed"); } } @Override @NonNls @NotNull public String getComponentName() { return "app.component.PersistentFS"; } @Override public void initComponent() { FSRecords.connect(); } @Override public boolean areChildrenLoaded(@NotNull final VirtualFile dir) { return areChildrenLoaded(getFileId(dir)); } @Override public long getCreationTimestamp() { return FSRecords.getCreationTimestamp(); } @NotNull private static NewVirtualFileSystem getDelegate(@NotNull VirtualFile file) { return (NewVirtualFileSystem)file.getFileSystem(); } @Override public boolean wereChildrenAccessed(@NotNull final VirtualFile dir) { return FSRecords.wereChildrenAccessed(getFileId(dir)); } @Override @NotNull public String[] list(@NotNull final VirtualFile file) { int id = getFileId(file); FSRecords.NameId[] nameIds = FSRecords.listAll(id); if (!areChildrenLoaded(id)) { nameIds = persistAllChildren(file, id, nameIds); } return ContainerUtil.map2Array(nameIds, String.class, new Function<FSRecords.NameId, String>() { @Override public String fun(FSRecords.NameId id) { return id.name; } }); } @Override @NotNull public String[] listPersisted(@NotNull VirtualFile parent) { return listPersisted(FSRecords.list(getFileId(parent))); } @NotNull private static String[] listPersisted(@NotNull int[] childrenIds) { String[] names = ArrayUtil.newStringArray(childrenIds.length); for (int i = 0; i < childrenIds.length; i++) { names[i] = FSRecords.getName(childrenIds[i]); } return names; } @NotNull private static FSRecords.NameId[] persistAllChildren(@NotNull final VirtualFile file, final int id, @NotNull FSRecords.NameId[] current) { final NewVirtualFileSystem fs = replaceWithNativeFS(getDelegate(file)); String[] delegateNames = VfsUtil.filterNames(fs.list(file)); if (delegateNames.length == 0 && current.length > 0) { return current; } THashMap<String, FSRecords.NameId> result = new THashMap<String, FSRecords.NameId>(); if (current.length == 0) { for (String name : delegateNames) { result.put(name, new FSRecords.NameId(-1, name)); } } else { for (FSRecords.NameId nameId : current) { result.put(nameId.name, nameId); } for (String name : delegateNames) { if (!result.containsKey(name)) { result.put(name, new FSRecords.NameId(-1, name)); } } } final TIntArrayList childrenIds = new TIntArrayList(result.size()); final List<FSRecords.NameId> nameIds = ContainerUtil.newArrayListWithExpectedSize(result.size()); result.forEachValue(new TObjectProcedure<FSRecords.NameId>() { @Override public boolean execute(FSRecords.NameId nameId) { if (nameId.id < 0) { FakeVirtualFile child = new FakeVirtualFile(file, nameId.name); FileAttributes attributes = fs.getAttributes(child); if (attributes != null) { int childId = createAndFillRecord(fs, child, id, attributes); nameId = new FSRecords.NameId(childId, nameId.name); } } if (nameId.id > 0) { childrenIds.add(nameId.id); nameIds.add(nameId); } return true; } }); FSRecords.updateList(id, childrenIds.toNativeArray()); setChildrenCached(id); return nameIds.toArray(new FSRecords.NameId[nameIds.size()]); } public static void setChildrenCached(int id) { int flags = FSRecords.getFlags(id); FSRecords.setFlags(id, flags | CHILDREN_CACHED_FLAG, true); } @Override @NotNull public FSRecords.NameId[] listAll(@NotNull VirtualFile parent) { final int parentId = getFileId(parent); FSRecords.NameId[] nameIds = FSRecords.listAll(parentId); if (!areChildrenLoaded(parentId)) { return persistAllChildren(parent, parentId, nameIds); } return nameIds; } private static boolean areChildrenLoaded(final int parentId) { return (FSRecords.getFlags(parentId) & CHILDREN_CACHED_FLAG) != 0; } @Override @Nullable public DataInputStream readAttribute(@NotNull final VirtualFile file, @NotNull final FileAttribute att) { return FSRecords.readAttributeWithLock(getFileId(file), att.getId()); } @Override @NotNull public DataOutputStream writeAttribute(@NotNull final VirtualFile file, @NotNull final FileAttribute att) { return FSRecords.writeAttribute(getFileId(file), att.getId(), att.isFixedSize()); } @Nullable private static DataInputStream readContent(@NotNull VirtualFile file) { return FSRecords.readContent(getFileId(file)); } @Nullable private static DataInputStream readContentById(int contentId) { return FSRecords.readContentById(contentId); } @NotNull private static DataOutputStream writeContent(@NotNull VirtualFile file, boolean readOnly) { return FSRecords.writeContent(getFileId(file), readOnly); } private static void writeContent(@NotNull VirtualFile file, ByteSequence content, boolean readOnly) throws IOException { FSRecords.writeContent(getFileId(file), content, readOnly); } @Override public int storeUnlinkedContent(@NotNull byte[] bytes) { return FSRecords.storeUnlinkedContent(bytes); } @Override public int getModificationCount(@NotNull final VirtualFile file) { return FSRecords.getModCount(getFileId(file)); } @Override public int getCheapFileSystemModificationCount() { return FSRecords.getLocalModCount(); } @Override public int getFilesystemModificationCount() { return FSRecords.getModCount(); } private static boolean writeAttributesToRecord(final int id, final int parentId, @NotNull VirtualFile file, @NotNull NewVirtualFileSystem fs, @NotNull FileAttributes attributes) { String name = file.getName(); if (!name.isEmpty()) { if (namesEqual(fs, name, FSRecords.getName(id))) return false; // TODO: Handle root attributes change. } else { if (areChildrenLoaded(id)) return false; // TODO: hack } FSRecords.setParent(id, parentId); FSRecords.setName(id, name); FSRecords.setTimestamp(id, attributes.lastModified); FSRecords.setLength(id, attributes.isDirectory() ? -1L : attributes.length); FSRecords.setFlags(id, (attributes.isDirectory() ? IS_DIRECTORY_FLAG : 0) | (attributes.isWritable() ? 0 : IS_READ_ONLY) | (attributes.isSymLink() ? IS_SYMLINK : 0) | (attributes.isSpecial() ? IS_SPECIAL : 0), true); return true; } @Override public int getFileAttributes(int id) { assert id > 0; //noinspection MagicConstant return FSRecords.getFlags(id); } @Override public boolean isDirectory(@NotNull final VirtualFile file) { return isDirectory(getFileAttributes(getFileId(file))); } private static int getParent(final int id) { assert id > 0; return FSRecords.getParent(id); } private static boolean namesEqual(@NotNull VirtualFileSystem fs, @NotNull String n1, String n2) { return ((NewVirtualFileSystem)fs).isCaseSensitive() ? n1.equals(n2) : n1.equalsIgnoreCase(n2); } @Override public boolean exists(@NotNull final VirtualFile fileOrDirectory) { return ((VirtualFileWithId)fileOrDirectory).getId() > 0; } @Override public long getTimeStamp(@NotNull final VirtualFile file) { return FSRecords.getTimestamp(getFileId(file)); } @Override public void setTimeStamp(@NotNull final VirtualFile file, final long modStamp) throws IOException { final int id = getFileId(file); FSRecords.setTimestamp(id, modStamp); getDelegate(file).setTimeStamp(file, modStamp); } private static int getFileId(@NotNull VirtualFile file) { final int id = ((VirtualFileWithId)file).getId(); if (id <= 0) { throw new InvalidVirtualFileAccessException(file); } return id; } @Override public boolean isSymLink(@NotNull VirtualFile file) { return isSymLink(getFileAttributes(getFileId(file))); } @Override public String resolveSymLink(@NotNull VirtualFile file) { throw new UnsupportedOperationException(); } @Override public boolean isSpecialFile(@NotNull VirtualFile file) { return isSpecialFile(getFileAttributes(getFileId(file))); } @Override public boolean isWritable(@NotNull final VirtualFile file) { return (getFileAttributes(getFileId(file)) & IS_READ_ONLY) == 0; } @Override public void setWritable(@NotNull final VirtualFile file, final boolean writableFlag) throws IOException { getDelegate(file).setWritable(file, writableFlag); processEvent(new VFilePropertyChangeEvent(this, file, VirtualFile.PROP_WRITABLE, isWritable(file), writableFlag, false)); } @Override public int getId(@NotNull final VirtualFile parent, @NotNull final String childName, @NotNull final NewVirtualFileSystem fs) { int parentId = getFileId(parent); if (parent == myFakeRoot) { // children of the fake root must be the FS roots only myRootsLock.readLock().lock(); try { String rootUrl = fs.getProtocol() + "://" + VfsImplUtil.normalize(fs, childName); VirtualFileSystemEntry root = myRoots.get(rootUrl); return root == null ? 0 : root.getId(); } finally { myRootsLock.readLock().unlock(); } } int[] children = FSRecords.list(parentId); if (children.length > 0) { // fast path, check that some child has same nameId as given name, this avoid O(N) on retrieving names for processing non-cached children int nameId = FSRecords.getNameId(childName); for (final int childId : children) { if (nameId == FSRecords.getNameId(childId)) { return childId; } } // for case sensitive system the above check is exhaustive in consistent state of vfs } for (final int childId : children) { if (namesEqual(fs, childName, FSRecords.getName(childId))) return childId; } final VirtualFile fake = new FakeVirtualFile(parent, childName); final FileAttributes attributes = fs.getAttributes(fake); if (attributes != null) { final int child = createAndFillRecord(fs, fake, parentId, attributes); FSRecords.updateList(parentId, ArrayUtil.append(children, child)); return child; } return 0; } @Override public long getLength(@NotNull final VirtualFile file) { long len; if (mustReloadContent(file)) { len = reloadLengthFromDelegate(file, getDelegate(file)); } else { final int id = getFileId(file); len = FSRecords.getLength(id); } return len; } @Override public VirtualFile copyFile(final Object requestor, @NotNull final VirtualFile file, @NotNull final VirtualFile newParent, @NotNull final String copyName) throws IOException { getDelegate(file).copyFile(requestor, file, newParent, copyName); processEvent(new VFileCopyEvent(requestor, file, newParent, copyName)); final VirtualFile child = newParent.findChild(copyName); if (child == null) { throw new IOException("Cannot create child"); } return child; } @Override public VirtualFile createChildDirectory(final Object requestor, @NotNull final VirtualFile parent, @NotNull final String dir) throws IOException { getDelegate(parent).createChildDirectory(requestor, parent, dir); processEvent(new VFileCreateEvent(requestor, parent, dir, true, false)); final VirtualFile child = parent.findChild(dir); if (child == null) { throw new IOException("Cannot create child directory '" + dir + "' at " + parent.getPath()); } return child; } @Override public VirtualFile createChildFile(final Object requestor, @NotNull final VirtualFile parent, @NotNull final String file) throws IOException { getDelegate(parent).createChildFile(requestor, parent, file); processEvent(new VFileCreateEvent(requestor, parent, file, false, false)); final VirtualFile child = parent.findChild(file); if (child == null) { throw new IOException("Cannot create child file '" + file + "' at " + parent.getPath()); } return child; } @Override public void deleteFile(final Object requestor, @NotNull final VirtualFile file) throws IOException { final NewVirtualFileSystem delegate = getDelegate(file); delegate.deleteFile(requestor, file); if (!delegate.exists(file)) { processEvent(new VFileDeleteEvent(requestor, file, false)); } } @Override public void renameFile(final Object requestor, @NotNull final VirtualFile file, @NotNull final String newName) throws IOException { getDelegate(file).renameFile(requestor, file, newName); processEvent(new VFilePropertyChangeEvent(requestor, file, VirtualFile.PROP_NAME, file.getName(), newName, false)); } @Override @NotNull public byte[] contentsToByteArray(@NotNull final VirtualFile file) throws IOException { return contentsToByteArray(file, true); } @Override @NotNull public byte[] contentsToByteArray(@NotNull final VirtualFile file, boolean cacheContent) throws IOException { InputStream contentStream = null; boolean reloadFromDelegate; boolean outdated; int fileId; synchronized (myInputLock) { fileId = getFileId(file); outdated = checkFlag(fileId, MUST_RELOAD_CONTENT) || FSRecords.getLength(fileId) == -1L; reloadFromDelegate = outdated || (contentStream = readContent(file)) == null; } if (reloadFromDelegate) { final NewVirtualFileSystem delegate = getDelegate(file); final byte[] content; if (outdated) { // in this case, file can have out-of-date length. so, update it first (it's needed for correct contentsToByteArray() work) // see IDEA-90813 for possible bugs FSRecords.setLength(fileId, delegate.getLength(file)); content = delegate.contentsToByteArray(file); } else { // a bit of optimization content = delegate.contentsToByteArray(file); FSRecords.setLength(fileId, content.length); } ApplicationEx application = (ApplicationEx)ApplicationManager.getApplication(); // we should cache every local files content // because the local history feature is currently depends on this cache, // perforce offline mode as well if ((!delegate.isReadOnly() || // do not cache archive content unless asked cacheContent && !application.isInternal() && !application.isUnitTestMode()) && content.length <= PersistentFSConstants.FILE_LENGTH_TO_CACHE_THRESHOLD) { synchronized (myInputLock) { writeContent(file, new ByteSequence(content), delegate.isReadOnly()); setFlag(file, MUST_RELOAD_CONTENT, false); } } return content; } else { try { final int length = (int)file.getLength(); assert length >= 0 : file; return FileUtil.loadBytes(contentStream, length); } catch (IOException e) { throw FSRecords.handleError(e); } } } @Override @NotNull public byte[] contentsToByteArray(int contentId) throws IOException { final DataInputStream stream = readContentById(contentId); assert stream != null : contentId; return FileUtil.loadBytes(stream); } @Override @NotNull public InputStream getInputStream(@NotNull final VirtualFile file) throws IOException { synchronized (myInputLock) { InputStream contentStream; if (mustReloadContent(file) || (contentStream = readContent(file)) == null) { NewVirtualFileSystem delegate = getDelegate(file); long len = reloadLengthFromDelegate(file, delegate); InputStream nativeStream = delegate.getInputStream(file); if (len > PersistentFSConstants.FILE_LENGTH_TO_CACHE_THRESHOLD) return nativeStream; return createReplicator(file, nativeStream, len, delegate.isReadOnly()); } else { return contentStream; } } } private static long reloadLengthFromDelegate(@NotNull VirtualFile file, @NotNull NewVirtualFileSystem delegate) { final long len = delegate.getLength(file); FSRecords.setLength(getFileId(file), len); return len; } private InputStream createReplicator(@NotNull final VirtualFile file, final InputStream nativeStream, final long fileLength, final boolean readOnly) throws IOException { if (nativeStream instanceof BufferExposingByteArrayInputStream) { // optimization BufferExposingByteArrayInputStream byteStream = (BufferExposingByteArrayInputStream )nativeStream; byte[] bytes = byteStream.getInternalBuffer(); storeContentToStorage(fileLength, file, readOnly, bytes, bytes.length); return nativeStream; } @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") final BufferExposingByteArrayOutputStream cache = new BufferExposingByteArrayOutputStream((int)fileLength); return new ReplicatorInputStream(nativeStream, cache) { @Override public void close() throws IOException { super.close(); storeContentToStorage(fileLength, file, readOnly, cache.getInternalBuffer(), cache.size()); } }; } private void storeContentToStorage(long fileLength, @NotNull VirtualFile file, boolean readOnly, @NotNull byte[] bytes, int bytesLength) throws IOException { synchronized (myInputLock) { if (bytesLength == fileLength) { writeContent(file, new ByteSequence(bytes, 0, bytesLength), readOnly); setFlag(file, MUST_RELOAD_CONTENT, false); } else { setFlag(file, MUST_RELOAD_CONTENT, true); } } } private static boolean mustReloadContent(@NotNull VirtualFile file) { int fileId = getFileId(file); return checkFlag(fileId, MUST_RELOAD_CONTENT) || FSRecords.getLength(fileId) == -1L; } @Override @NotNull public OutputStream getOutputStream(@NotNull final VirtualFile file, final Object requestor, final long modStamp, final long timeStamp) throws IOException { final VFileContentChangeEvent event = new VFileContentChangeEvent(requestor, file, file.getModificationStamp(), modStamp, false); final List<VFileContentChangeEvent> events = Collections.singletonList(event); final BulkFileListener publisher = myEventsBus.syncPublisher(VirtualFileManager.VFS_CHANGES); publisher.before(events); return new ByteArrayOutputStream() { private boolean closed; // protection against user calling .close() twice @Override public void close() throws IOException { if (closed) return; super.close(); NewVirtualFileSystem delegate = getDelegate(file); OutputStream ioFileStream = delegate.getOutputStream(file, requestor, modStamp, timeStamp); // FSRecords.ContentOutputStream already buffered, no need to wrap in BufferedStream OutputStream persistenceStream = writeContent(file, delegate.isReadOnly()); try { persistenceStream.write(buf, 0, count); } finally { try { ioFileStream.write(buf, 0, count); } finally { closed = true; persistenceStream.close(); ioFileStream.close(); executeTouch(file, false, event.getModificationStamp()); publisher.after(events); } } } }; } @Override public int acquireContent(@NotNull VirtualFile file) { return FSRecords.acquireFileContent(getFileId(file)); } @Override public void releaseContent(int contentId) { FSRecords.releaseContent(contentId); } @Override public int getCurrentContentId(@NotNull VirtualFile file) { return FSRecords.getContentId(getFileId(file)); } @Override public void moveFile(final Object requestor, @NotNull final VirtualFile file, @NotNull final VirtualFile newParent) throws IOException { getDelegate(file).moveFile(requestor, file, newParent); processEvent(new VFileMoveEvent(requestor, file, newParent)); } private void processEvent(@NotNull VFileEvent event) { processEvents(Collections.singletonList(event)); } private static class EventWrapper { private final VFileDeleteEvent event; private final int id; private EventWrapper(final VFileDeleteEvent event, final int id) { this.event = event; this.id = id; } } @NotNull private static final Comparator<EventWrapper> DEPTH_COMPARATOR = new Comparator<EventWrapper>() { @Override public int compare(@NotNull final EventWrapper o1, @NotNull final EventWrapper o2) { return o1.event.getFileDepth() - o2.event.getFileDepth(); } }; @NotNull private static List<VFileEvent> validateEvents(@NotNull List<VFileEvent> events) { final List<EventWrapper> deletionEvents = ContainerUtil.newArrayList(); for (int i = 0, size = events.size(); i < size; i++) { final VFileEvent event = events.get(i); if (event instanceof VFileDeleteEvent && event.isValid()) { deletionEvents.add(new EventWrapper((VFileDeleteEvent)event, i)); } } ContainerUtil.quickSort(deletionEvents, DEPTH_COMPARATOR); final TIntHashSet invalidIDs = new TIntHashSet(deletionEvents.size()); final List<VirtualFile> dirsToBeDeleted = new ArrayList<VirtualFile>(); nextEvent: for (EventWrapper wrapper : deletionEvents) { final VirtualFile candidate = wrapper.event.getFile(); for (VirtualFile file : dirsToBeDeleted) { if (VfsUtilCore.isAncestor(file, candidate, false)) { invalidIDs.add(wrapper.id); continue nextEvent; } } if (candidate.isDirectory()) { dirsToBeDeleted.add(candidate); } } final List<VFileEvent> filtered = ContainerUtil.newArrayListWithCapacity(events.size() - invalidIDs.size()); for (int i = 0, size = events.size(); i < size; i++) { final VFileEvent event = events.get(i); if (event.isValid() && !(event instanceof VFileDeleteEvent && invalidIDs.contains(i))) { filtered.add(event); } } return filtered; } @Override public void processEvents(@NotNull List<VFileEvent> events) { ApplicationManager.getApplication().assertWriteAccessAllowed(); List<VFileEvent> validated = validateEvents(events); BulkFileListener publisher = myEventsBus.syncPublisher(VirtualFileManager.VFS_CHANGES); publisher.before(validated); for (VFileEvent event : validated) { applyEvent(event); } publisher.after(validated); } @Override @Nullable public VirtualFileSystemEntry findRoot(@NotNull String basePath, @NotNull NewVirtualFileSystem fs) { String rootUrl = fs.getProtocol() + "://" + VfsImplUtil.normalize(fs, basePath); VirtualFileSystemEntry root; myRootsLock.readLock().lock(); try { root = basePath.isEmpty() ? myFakeRoot : myRoots.get(rootUrl); if (root != null) return root; } finally { myRootsLock.readLock().unlock(); } myRootsLock.writeLock().lock(); try { root = basePath.isEmpty() ? myFakeRoot : myRoots.get(rootUrl); if (root != null) return root; int rootId = FSRecords.findRootRecord(rootUrl); root = myRootsById.get(rootId); if (root != null) return root; if (basePath.isEmpty()) { // fake super-root root = new VirtualDirectoryImpl("", null, fs, rootId, 0) { @SuppressWarnings("NonSynchronizedMethodOverridesSynchronizedMethod") @Override @NotNull public VirtualFile[] getChildren() { return getRoots(getFileSystem()); } @Override public VirtualFileSystemEntry findChild(@NotNull String name) { if (name.isEmpty()) return null; return findRoot(name, getFileSystem()); } }; } else if (fs instanceof JarFileSystem) { // optimization: for jar roots do not store base path in the myName field, use local FS file's getPath() String parentPath = basePath.substring(0, basePath.indexOf(JarFileSystem.JAR_SEPARATOR)); VirtualFile parentLocalFile = LocalFileSystem.getInstance().findFileByPath(parentPath); if (parentLocalFile == null) return null; // check one more time since the findFileByPath could have created the root (by reentering the findRoot) root = myRoots.get(rootUrl); if (root != null) return root; root = myRootsById.get(rootId); if (root != null) return root; root = new JarRoot(fs, rootId, parentLocalFile); } else { root = new VirtualDirectoryImpl(basePath, null, fs, rootId, 0); } final FileAttributes attributes = fs.getAttributes(root); if (attributes == null) { return null; } final boolean newRoot = writeAttributesToRecord(rootId, 0, root, fs, attributes); if (!newRoot) { if (attributes.lastModified != FSRecords.getTimestamp(rootId)) { root.markDirtyRecursively(); } } if (basePath.isEmpty()) { myFakeRoot = root; } else { myRoots.put(rootUrl, root); myRootsById.put(rootId, root); if (rootId != root.getId()) throw new AssertionError(); } return root; } finally { myRootsLock.writeLock().unlock(); } } @Override public void clearIdCache() { myIdToDirCache.clear(); } private static final int DEPTH_LIMIT = 75; @Override @Nullable public NewVirtualFile findFileById(final int id) { return findFileById(id, false, null, 0); } @Override public NewVirtualFile findFileByIdIfCached(final int id) { return findFileById(id, true, null, 0); } @Nullable private VirtualFileSystemEntry findFileById(int id, boolean cachedOnly, TIntArrayList visited, int mask) { VirtualFileSystemEntry cached = myIdToDirCache.get(id); if (cached != null) return cached; if (visited != null && (visited.size() >= DEPTH_LIMIT || (mask & id) == id && visited.contains(id))) { @NonNls String sb = "Dead loop detected in persistent FS (id=" + id + " cached-only=" + cachedOnly + "):"; for (int i = 0; i < visited.size(); i++) { int _id = visited.get(i); sb += "\n " + _id + " '" + getName(_id) + "' " + String.format("%02x", getFileAttributes(_id)) + ' ' + myIdToDirCache.containsKey(_id); } LOG.error(sb); return null; } if (visited == null) visited = new TIntArrayList(DEPTH_LIMIT); visited.add(id); int parentId = getParent(id); VirtualFileSystemEntry result; if (parentId == 0) { myRootsLock.readLock().lock(); try { result = myRootsById.get(id); } finally { myRootsLock.readLock().unlock(); } } else { VirtualFileSystemEntry parentFile = findFileById(parentId, cachedOnly, visited, mask |= id); if (parentFile instanceof VirtualDirectoryImpl) { result = ((VirtualDirectoryImpl)parentFile).findChildById(id, cachedOnly); } else { result = null; } } if (result != null && result.isDirectory()) { VirtualFileSystemEntry old = myIdToDirCache.put(id, result); if (old != null) result = old; } return result; } @Override @NotNull public VirtualFile[] getRoots() { myRootsLock.readLock().lock(); try { Collection<VirtualFileSystemEntry> roots = myRoots.values(); return VfsUtilCore.toVirtualFileArray(roots); } finally { myRootsLock.readLock().unlock(); } } @Override @NotNull public VirtualFile[] getRoots(@NotNull final NewVirtualFileSystem fs) { final List<VirtualFile> roots = new ArrayList<VirtualFile>(); myRootsLock.readLock().lock(); try { for (NewVirtualFile root : myRoots.values()) { if (root.getFileSystem() == fs) { roots.add(root); } } } finally { myRootsLock.readLock().unlock(); } return VfsUtilCore.toVirtualFileArray(roots); } @Override @NotNull public VirtualFile[] getLocalRoots() { final List<VirtualFile> roots = new ArrayList<VirtualFile>(); myRootsLock.readLock().lock(); try { for (NewVirtualFile root : myRoots.values()) { if (root.isInLocalFileSystem()) { roots.add(root); } } } finally { myRootsLock.readLock().unlock(); } return VfsUtilCore.toVirtualFileArray(roots); } private VirtualFileSystemEntry applyEvent(@NotNull VFileEvent event) { try { if (event instanceof VFileCreateEvent) { final VFileCreateEvent createEvent = (VFileCreateEvent)event; return executeCreateChild(createEvent.getParent(), createEvent.getChildName()); } else if (event instanceof VFileDeleteEvent) { final VFileDeleteEvent deleteEvent = (VFileDeleteEvent)event; executeDelete(deleteEvent.getFile()); } else if (event instanceof VFileContentChangeEvent) { final VFileContentChangeEvent contentUpdateEvent = (VFileContentChangeEvent)event; executeTouch(contentUpdateEvent.getFile(), contentUpdateEvent.isFromRefresh(), contentUpdateEvent.getModificationStamp()); } else if (event instanceof VFileCopyEvent) { final VFileCopyEvent copyEvent = (VFileCopyEvent)event; return executeCreateChild(copyEvent.getNewParent(), copyEvent.getNewChildName()); } else if (event instanceof VFileMoveEvent) { final VFileMoveEvent moveEvent = (VFileMoveEvent)event; executeMove(moveEvent.getFile(), moveEvent.getNewParent()); } else if (event instanceof VFilePropertyChangeEvent) { final VFilePropertyChangeEvent propertyChangeEvent = (VFilePropertyChangeEvent)event; if (VirtualFile.PROP_NAME.equals(propertyChangeEvent.getPropertyName())) { executeRename(propertyChangeEvent.getFile(), (String)propertyChangeEvent.getNewValue()); } else if (VirtualFile.PROP_WRITABLE.equals(propertyChangeEvent.getPropertyName())) { executeSetWritable(propertyChangeEvent.getFile(), ((Boolean)propertyChangeEvent.getNewValue()).booleanValue()); } } } catch (Exception e) { // Exception applying single event should not prevent other events from applying. LOG.error(e); } return null; } @NotNull @NonNls public String toString() { return "PersistentFS"; } private static VirtualFileSystemEntry executeCreateChild(@NotNull VirtualFile parent, @NotNull String name) { final NewVirtualFileSystem delegate = getDelegate(parent); final VirtualFile fake = new FakeVirtualFile(parent, name); final FileAttributes attributes = delegate.getAttributes(fake); if (attributes != null) { final int parentId = getFileId(parent); final int childId = createAndFillRecord(delegate, fake, parentId, attributes); appendIdToParentList(parentId, childId); assert parent instanceof VirtualDirectoryImpl : parent; final VirtualDirectoryImpl dir = (VirtualDirectoryImpl)parent; VirtualFileSystemEntry child = dir.createChild(name, childId, dir.getFileSystem()); dir.addChild(child); return child; } return null; } private static int createAndFillRecord(@NotNull NewVirtualFileSystem delegateSystem, @NotNull VirtualFile delegateFile, int parentId, @NotNull FileAttributes attributes) { final int childId = FSRecords.createRecord(); writeAttributesToRecord(childId, parentId, delegateFile, delegateSystem, attributes); return childId; } private static void appendIdToParentList(final int parentId, final int childId) { int[] childrenList = FSRecords.list(parentId); childrenList = ArrayUtil.append(childrenList, childId); FSRecords.updateList(parentId, childrenList); } private void executeDelete(@NotNull VirtualFile file) { if (!file.exists()) { LOG.error("Deleting a file, which does not exist: " + file.getPath()); return; } clearIdCache(); int id = getFileId(file); FSRecords.deleteRecordRecursively(id); final VirtualFile parent = file.getParent(); final int parentId = parent == null ? 0 : getFileId(parent); if (parentId == 0) { myRootsLock.writeLock().lock(); try { String rootUrl = file.getUrl(); myRoots.remove(rootUrl); myRootsById.remove(id); FSRecords.deleteRootRecord(id); } finally { myRootsLock.writeLock().unlock(); } } else { removeIdFromParentList(parentId, id, parent, file); VirtualDirectoryImpl directory = (VirtualDirectoryImpl)file.getParent(); assert directory != null : file; directory.removeChild(file); } invalidateSubtree(file); } private static void invalidateSubtree(@NotNull VirtualFile file) { final VirtualFileSystemEntry impl = (VirtualFileSystemEntry)file; impl.invalidate(); for (VirtualFile child : impl.getCachedChildren()) { invalidateSubtree(child); } } private static void removeIdFromParentList(final int parentId, final int id, @NotNull VirtualFile parent, VirtualFile file) { int[] childList = FSRecords.list(parentId); int index = ArrayUtil.indexOf(childList, id); if (index == -1) { throw new RuntimeException("Cannot find child (" + id + ")" + file + "\n\tin (" + parentId + ")" + parent + "\n\tactual children:" + Arrays.toString(childList)); } childList = ArrayUtil.remove(childList, index); FSRecords.updateList(parentId, childList); } private static void executeRename(@NotNull VirtualFile file, @NotNull final String newName) { ((VirtualFileSystemEntry)file).setNewName(newName); final int id = getFileId(file); FSRecords.setName(id, newName); } private static void executeSetWritable(@NotNull VirtualFile file, final boolean writableFlag) { setFlag(file, IS_READ_ONLY, !writableFlag); } private static void setFlag(@NotNull VirtualFile file, int mask, boolean value) { setFlag(getFileId(file), mask, value); } private static void setFlag(final int id, final int mask, final boolean value) { int oldFlags = FSRecords.getFlags(id); int flags = value ? oldFlags | mask : oldFlags & ~mask; if (oldFlags != flags) { FSRecords.setFlags(id, flags, true); } } private static boolean checkFlag(int fileId, int mask) { return (FSRecords.getFlags(fileId) & mask) != 0; } private static void executeTouch(@NotNull VirtualFile file, boolean reloadContentFromDelegate, long newModificationStamp) { if (reloadContentFromDelegate) { setFlag(file, MUST_RELOAD_CONTENT, true); } final NewVirtualFileSystem delegate = getDelegate(file); final FileAttributes attributes = delegate.getAttributes(file); FSRecords.setLength(getFileId(file), attributes != null ? attributes.length : DEFAULT_LENGTH); FSRecords.setTimestamp(getFileId(file), attributes != null ? attributes.lastModified : DEFAULT_TIMESTAMP); ((VirtualFileSystemEntry)file).setModificationStamp(newModificationStamp); } private void executeMove(@NotNull VirtualFile file, @NotNull VirtualFile newParent) { clearIdCache(); final int fileId = getFileId(file); final int newParentId = getFileId(newParent); final int oldParentId = getFileId(file.getParent()); removeIdFromParentList(oldParentId, fileId, file.getParent(), file); appendIdToParentList(newParentId, fileId); ((VirtualFileSystemEntry)file).setParent(newParent); FSRecords.setParent(fileId, newParentId); } @Override public String getName(int id) { assert id > 0; return FSRecords.getName(id); } @TestOnly public void cleanPersistedContents() { try { final int[] roots = FSRecords.listRoots(); for (int root : roots) { cleanPersistedContentsRecursively(root); } } catch (IOException e) { throw new RuntimeException(e); } } @TestOnly private void cleanPersistedContentsRecursively(int id) { if (isDirectory(getFileAttributes(id))) { for (int child : FSRecords.list(id)) { cleanPersistedContentsRecursively(child); } } else { setFlag(id, MUST_RELOAD_CONTENT, true); } } private static class JarRoot extends VirtualDirectoryImpl { private final VirtualFile myParentLocalFile; private JarRoot(@NotNull NewVirtualFileSystem fs, int rootId, @NotNull VirtualFile parentLocalFile) { super("", null, fs, rootId, 0); myParentLocalFile = parentLocalFile; } @NotNull @Override public String getName() { return myParentLocalFile.getName(); } @Override protected String rawName() { return myParentLocalFile.getPath() + JarFileSystem.JAR_SEPARATOR; } @Override public void setParent(@NotNull VirtualFile newParent) { throw new IncorrectOperationException(); } } }
volatile
platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/PersistentFSImpl.java
volatile
<ide><path>latform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/PersistentFSImpl.java <ide> private final ConcurrentIntObjectMap<VirtualFileSystemEntry> myIdToDirCache = new StripedLockIntObjectConcurrentHashMap<VirtualFileSystemEntry>(); <ide> private final Object myInputLock = new Object(); <ide> <del> @Nullable private VirtualFileSystemEntry myFakeRoot; <add> @Nullable private volatile VirtualFileSystemEntry myFakeRoot; <ide> private boolean myShutDown = false; <ide> <ide> public PersistentFSImpl(@NotNull final MessageBus bus) {
Java
apache-2.0
9ac6c40172ced32cfcbdccaf5b17a18fbe390653
0
stumoodie/MetabolicNotationSubsystem,stumoodie/MetabolicNotationSubsystem
package uk.ac.ed.inf.Metabolic.parser; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import org.pathwayeditor.businessobjectsAPI.ILink; import org.pathwayeditor.businessobjectsAPI.IMapObject; import org.pathwayeditor.businessobjectsAPI.IRootMapObject; import org.pathwayeditor.businessobjectsAPI.IShape; import org.pathwayeditor.businessobjectsAPI.Location; import org.pathwayeditor.contextadapter.publicapi.IValidationRuleDefinition; import org.pathwayeditor.contextadapter.toolkit.ndom.GeometryUtils; import org.pathwayeditor.contextadapter.toolkit.ndom.ModelObject; import org.pathwayeditor.contextadapter.toolkit.ndom.NdomException; import uk.ac.ed.inf.Metabolic.ndomAPI.ERelType; import uk.ac.ed.inf.Metabolic.ndomAPI.IReaction; public class MetabolicNDOMFactory extends NDOMFactory { private Map<IShape, MetabolicMolecule> shape2Molecule = new HashMap<IShape, MetabolicMolecule>(); Map<MetabolicReaction, IShape> reaction2Shape = new HashMap<MetabolicReaction, IShape>(); LinkedList<Map<String, MetabolicCompound>> name2Compound = new LinkedList<Map<String, MetabolicCompound>>(); List<ILink> prodLinks; public MetabolicNDOMFactory(IRootMapObject rmo) { super(rmo); } public MetabolicNDOMFactory() { super(); } @Override protected void semanticValidation() { checkOrphanCompounds(); checkOrphanReactions(); } void checkOrphanReactions() { for (IReaction r : ndom.getReactionList()) { if ((r.getSubstrateList().size() == 0)) { IValidationRuleDefinition rd = getReportBuilder() .getRuleStore().getRuleById( MetabolicRuleLoader.ORPHAN_PROCESS_ERROR_ID); IShape el = reaction2Shape.get(r); getReportBuilder().setRuleFailed(el, rd, "Reaction has no substrates"); } if ((r.getProductList().size() == 0)) { IValidationRuleDefinition rd = getReportBuilder() .getRuleStore().getRuleById( MetabolicRuleLoader.ORPHAN_PROCESS_ERROR_ID); IShape el = reaction2Shape.get(r); getReportBuilder().setRuleFailed(el, rd, "Reaction has no products"); } } } void checkOrphanCompounds() { // ModelProcessor proc=new ModelProcessor(ndom); for(Entry<IShape,MetabolicMolecule> e:shape2Molecule.entrySet()){ IShape el=e.getKey(); MetabolicMolecule c=e.getValue(); if((c.getInhibitoryRelationList().size()+c.getActivatoryRelationList().size()+c.getCatalyticRelationList().size()+c.getSinkList().size()+c.getSourceList().size())==0){ IValidationRuleDefinition rd = getReportBuilder() .getRuleStore().getRuleById( MetabolicRuleLoader.ORPHAN_COMPOUND_ERROR_ID); getReportBuilder().setRuleFailed(el, rd, "Reaction has no products"); } } } protected void rmo() { name2Compound.addFirst(new HashMap<String, MetabolicCompound>()); super.rmo(); name2Compound.removeFirst(); } void processProdLinks(MetabolicReaction r) { if (r.isReversible()) { IShape s = reaction2Shape.get(r); // Set<ILink> substr = new HashSet<ILink>(); // Set<ILink> prod = new HashSet<ILink>(); Location srcLoc = null; // double srcAngle; for (ILink l : prodLinks) { if (srcLoc == null) { // first link srcLoc = GeometryUtils.getSrcLocation(l, s); substrate(l, r); } else { // all consequitive links Location newLoc = GeometryUtils.getSrcLocation(l, s); if (GeometryUtils.getAngle(srcLoc, newLoc) > 0) { substrate(l, r); } else { productsIrr(l, r); } } } } prodLinks = null; } @Override protected void products(ILink el, MetabolicReaction r) { if (r.isReversible()) { prodLinks.add(el); } else { productsIrr(el, r); } } private void productsIrr(ILink el, MetabolicReaction r) { // TODO separate substrates from products MetabolicRelation rel = production(el); r.addProduct(rel); IShape targ = el.getTarget(); MetabolicMolecule mol = shape2Molecule.get(targ); if (mol == null) { IValidationRuleDefinition rd = getReportBuilder().getRuleStore() .getRuleById(MetabolicRuleLoader.NOT_REGISTERED_ERROR_ID); getReportBuilder() .setRuleFailed(el, rd, "Molecule in Production relation is not registered in the model"); // error("Molecule in Production relation is not registered in the // model"); } try { mol.addSource(rel); String vn = rel.getVarName(); String id = mol.getId(); updateKL(r, vn, id); } catch (NdomException e) { report(e); e.printStackTrace(); } } void updateKL(MetabolicReaction r, String vn, String id) { String kineticLaw = r.getKineticLaw(); if (kineticLaw != null) { kineticLaw = kineticLaw.replaceAll(vn, id); r.setKineticLaw(kineticLaw); } } @Override protected void substrate(ILink el, MetabolicReaction r) { IShape targ =null; MetabolicRelation rel = null; if (r.isReversible()){ if( "Consume".equals(el.getObjectType().getTypeName())) { // error("Consumption link to reversible reaction"); IValidationRuleDefinition rd = getReportBuilder() .getRuleStore() .getRuleById( MetabolicRuleLoader.CONSUMPTION_TO_REVERSIBLE_ERROR_ID); getReportBuilder().setRuleFailed(el, rd, "Consumption link to reversible reaction"); return; }else{ rel = consumptionRev(el); targ = el.getTarget(); } }else{ rel = consumption(el); targ = el.getSource(); } r.addSubstrate(rel); MetabolicMolecule mol = shape2Molecule.get(targ); if (mol == null) { IValidationRuleDefinition rd = getReportBuilder().getRuleStore() .getRuleById(MetabolicRuleLoader.NOT_REGISTERED_ERROR_ID); getReportBuilder() .setRuleFailed(el, rd, "Molecule in Consumption relation is not registered in the model"); // error("Molecule in Consumption relation is not registered in the // model"); } try { mol.addSink(rel); String vn = rel.getVarName(); String id = mol.getId(); updateKL(r, vn, id); } catch (NdomException e) { report(e); e.printStackTrace(); } } private MetabolicRelation consumptionRev(ILink el) { MetabolicRelation rel = relation(el, ERelType.Consumption); rel.setRole(el.getSrcPort().getPropertyByName("ROLE").getValue()); // rel.setStoichiometry(getInt(el.getTargetPort().getPropertyByName( // "STOICH").getValue(), "Wrong stoichiometry\t")); setStoichiometry(el, el.getSrcPort(),rel); return rel; } @Override protected void activate(ILink el, MetabolicReaction r) { MetabolicRelation rel = activation(el); if (r == null) { IValidationRuleDefinition rd = getReportBuilder().getRuleStore() .getRuleById(MetabolicRuleLoader.NOT_REGISTERED_ERROR_ID); getReportBuilder() .setRuleFailed(el, rd, "Reaction for Activation relation is not registered in the model"); // error("Reaction for Activation relation is not registered in the // model"); } r.addActivator(rel); IShape src = el.getSource(); MetabolicMolecule mol = shape2Molecule.get(src); if (mol == null) { IValidationRuleDefinition rd = getReportBuilder().getRuleStore() .getRuleById(MetabolicRuleLoader.NOT_REGISTERED_ERROR_ID); getReportBuilder() .setRuleFailed(el, rd, "Molecule for Activation relation is not registered in the model"); } try { mol.addActivatoryRelation(rel); } catch (NdomException e) { report(e); e.printStackTrace(); } } @Override protected void inhibit(ILink el, MetabolicReaction r) { MetabolicRelation rel = inhibition(el); if (r == null) { IValidationRuleDefinition rd = getReportBuilder().getRuleStore() .getRuleById(MetabolicRuleLoader.NOT_REGISTERED_ERROR_ID); getReportBuilder() .setRuleFailed(el, rd, "Reaction for Inhibiton relation is not registered in the model"); } r.addInhibitor(rel); IShape src = el.getSource(); MetabolicMolecule mol = shape2Molecule.get(src); if (mol == null) { IValidationRuleDefinition rd = getReportBuilder().getRuleStore() .getRuleById(MetabolicRuleLoader.NOT_REGISTERED_ERROR_ID); getReportBuilder() .setRuleFailed(el, rd, "Molecule for Inhibiton relation is not registered in the model"); } try { mol.addInhibitoryRelation(rel); } catch (NdomException e) { report(e); e.printStackTrace(); } } @Override protected void catalysis(ILink el, MetabolicReaction r) { MetabolicRelation rel = catalysis(el); r.addCatalyst(rel); IShape src = el.getSource(); MetabolicMolecule mol = shape2Molecule.get(src); if (mol == null) { IValidationRuleDefinition rd = getReportBuilder().getRuleStore() .getRuleById(MetabolicRuleLoader.NOT_REGISTERED_ERROR_ID); getReportBuilder() .setRuleFailed(el, rd, "Molecule for Catalysis relation is not registered in the model"); } try { mol.addCatalyticRelation(rel); } catch (NdomException e) { report(e); e.printStackTrace(); } } @Override protected void macromolecule(MetabolicCompartment comaprtment, IMapObject mapObject) { MetabolicMacromolecule m = macromolecule(mapObject); shape2Molecule.put((IShape) mapObject, m); comaprtment.addMacromolecule(m); } @Override protected void macromolecule(MetabolicMacromolecule parent, IMapObject mapObject) { MetabolicMacromolecule m = macromolecule(mapObject); shape2Molecule.put((IShape) mapObject, m); parent.addSubunit(m); } @Override protected void compound(MetabolicMacromolecule m, IMapObject mapObject) { MetabolicCompound comp = compound(mapObject); m.addCompound(comp); shape2Molecule.put((IShape) mapObject, comp); } @Override protected void compound(MetabolicCompartment compartment, IMapObject mapObject) { MetabolicCompound comp = compound(mapObject); if (name2Compound.getFirst().containsKey(comp.getName())) { MetabolicCompound comp1 = name2Compound.getFirst().get( comp.getName()); compareCompounds(comp1, comp, compartment, mapObject); comp = comp1; } else { name2Compound.getFirst().put(comp.getName(), comp); compartment.addCompound(comp); } comp.setCloneNumber(comp.getCloneNumber() + 1); shape2Molecule.put((IShape) mapObject, comp); } /** * Check external references for two compound definitions. Validate that two * compounds, having the same name have the same set of references to * external databases. * * @param comp1 * reference compound * @param comp * compound under creation */ private void compareCompounds(MetabolicCompound comp1, MetabolicCompound comp, ModelObject parent, IMapObject mapObject) { String name = comp1.getASCIIName(); // TODO replace with rules if (!comp1.getDescription().equals(comp.getDescription())) { IValidationRuleDefinition rd = getReportBuilder().getRuleStore() .getRuleById(MetabolicRuleLoader.COMP_DEF_ERROR_ID); getReportBuilder().setRuleFailed( mapObject, rd, "Compound " + name + "has two sets of Descriptions: '" + comp1.getDescription() + "' and '" + comp.getDescription() + "'"); } if (!comp1.getDetailedDescription().equals( comp.getDetailedDescription())) { IValidationRuleDefinition rd = getReportBuilder().getRuleStore() .getRuleById(MetabolicRuleLoader.COMP_DEF_ERROR_ID); getReportBuilder().setRuleFailed( mapObject, rd, "Compound " + name + "has two sets of DetailedDescription: '" + comp1.getDetailedDescription() + "' and '" + comp.getDetailedDescription() + "'"); } if (!comp1.getCID().equals(comp.getCID())) { IValidationRuleDefinition rd = getReportBuilder().getRuleStore() .getRuleById(MetabolicRuleLoader.COMP_DEF_ERROR_ID); getReportBuilder().setRuleFailed( mapObject, rd, "Compound " + name + "has two sets of CID: '" + comp1.getCID() + "' and '" + comp.getCID() + "'"); } if (!comp1.getChEBIId().equals(comp.getChEBIId())) { IValidationRuleDefinition rd = getReportBuilder().getRuleStore() .getRuleById(MetabolicRuleLoader.COMP_DEF_ERROR_ID); getReportBuilder().setRuleFailed( mapObject, rd, "Compound " + name + "has two sets of ChEBIId: '" + comp1.getChEBIId() + "' and '" + comp.getChEBIId() + "'"); } if (!comp1.getInChI().equals(comp.getInChI())) { IValidationRuleDefinition rd = getReportBuilder().getRuleStore() .getRuleById(MetabolicRuleLoader.COMP_DEF_ERROR_ID); getReportBuilder().setRuleFailed( mapObject, rd, "Compound " + name + "has two sets of InChI: '" + comp1.getInChI() + "' and '" + comp.getInChI() + "'"); } if (comp1.getIC() != (comp.getIC())) { IValidationRuleDefinition rd = getReportBuilder().getRuleStore() .getRuleById(MetabolicRuleLoader.COMP_DEF_ERROR_ID); getReportBuilder().setRuleFailed( mapObject, rd, "Compound " + name + "has two sets of getIC: '" + comp1.getIC() + "' and '" + comp.getIC() + "'"); } if (!comp1.getPubChemId().equals(comp.getPubChemId())) { IValidationRuleDefinition rd = getReportBuilder().getRuleStore() .getRuleById(MetabolicRuleLoader.COMP_DEF_ERROR_ID); getReportBuilder().setRuleFailed( mapObject, rd, "Compound " + name + "has two sets of PubChemId: '" + comp1.getPubChemId() + "' and '" + comp.getPubChemId() + "'"); } if (!comp1.getSmiles().equals(comp.getSmiles())) { IValidationRuleDefinition rd = getReportBuilder().getRuleStore() .getRuleById(MetabolicRuleLoader.COMP_DEF_ERROR_ID); getReportBuilder().setRuleFailed( mapObject, rd, "Compound " + name + "has two sets of Smiles: '" + comp1.getSmiles() + "' and '" + comp.getSmiles() + "'"); } } @Override protected void compartment(MetabolicCompartment parent, IMapObject mapObject) { MetabolicCompartment compartment = compartment(mapObject); try { name2Compound.addFirst(new HashMap<String, MetabolicCompound>()); parent.addChildCompartment(compartment); List<IMapObject> ch = mapObject.getChildren(); for (IMapObject el : ch) { String ot = el.getObjectType().getTypeName(); if ("Compartment".equals(ot)) { compartment(compartment, el); } else if ("Process".equals(ot)) { process(compartment, el); } else if ("Compound".equals(ot)) { compound(compartment, el); } else if ("Macromolecule".equals(ot)) { macromolecule(compartment, el); } } name2Compound.removeFirst(); } catch (NdomException e) { report(e); e.printStackTrace(); } } @Override protected void connectivity() { for (MetabolicReaction r : reaction2Shape.keySet()) { IShape s = reaction2Shape.get(r); prodLinks = new ArrayList<ILink>(); Set<ILink> lset = s.getSourceLinks(); if (lset.size() == 0) { } for (ILink el : lset) { String ot = el.getObjectType().getTypeName(); if ("Produce".equals(ot)) { products(el, r); } } lset = s.getTargetLinks(); int nsubstr = 0; for (ILink el : lset) { String ot = el.getObjectType().getTypeName(); if ("Consume".equals(ot)) { substrate(el, r); nsubstr++; } else if ("Activation".equals(ot)) { activate(el, r); } else if ("Catalysis".equals(ot)) { catalysis(el, r); } else if ("Inhibition".equals(ot)) { inhibit(el, r); } } if (nsubstr == 0 && !r.isReversible()) { // TODO replace with rules IValidationRuleDefinition rd = getReportBuilder() .getRuleStore().getRuleById( MetabolicRuleLoader.RE_DEF_ERROR_ID); getReportBuilder().setRuleFailed( s, rd, "Reaction is not reversible and do not have substrates \t" + s.getId()); } processProdLinks(r); } } @Override protected void process(ModelObject parent, IMapObject mapObject) { MetabolicReaction re = process(mapObject); // checkParameters(re); ndom.addReaction(re); reaction2Shape.put(re, (IShape) mapObject); } /** * @deprecated replaced by * {@link NDOMFactory#setReParam(IMapObject, MetabolicReaction)} * @param re * process node; */ void checkParameters(MetabolicReaction re) { // String parameters = re.getParameters(); // //TODO replace with rules // if(parameters.trim().length()>0 && // !parameters.matches("^(\\s*\\w+\\s*=\\s*[0-9eE\\-+.]+\\s*;)+$")){ // // !parameters.matches("^(\\s*\\w+\\s*=\\s*[0-9eE-+.]+\\s*;)+$")){ // error("Invalid parameter definition"+parameters); // } } } /* * $Log: MetabolicNDOMFactory.java,v $ Revision 1.8 2008/07/15 11:14:32 smoodie * Refactored so code compiles with new Toolkit framework. * * Revision 1.7 2008/06/24 10:07:40 radams moved rule builder upt oAbstractNDOM * parsers * * Revision 1.6 2008/06/23 14:42:35 radams added report builder to parser * * Revision 1.5 2008/06/23 14:22:34 radams added report builder to parser * * Revision 1.4 2008/06/20 22:48:19 radams imports * * Revision 1.3 2008/06/09 13:26:29 asorokin Bug fixes for SBML export * * Revision 1.2 2008/06/02 15:14:31 asorokin KineticLaw parameters parsing and * validation * * Revision 1.1 2008/06/02 10:31:42 asorokin Reference to Service provider from * all Service interfaces * */
src/uk/ac/ed/inf/Metabolic/parser/MetabolicNDOMFactory.java
package uk.ac.ed.inf.Metabolic.parser; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import org.pathwayeditor.businessobjectsAPI.ILink; import org.pathwayeditor.businessobjectsAPI.IMapObject; import org.pathwayeditor.businessobjectsAPI.IRootMapObject; import org.pathwayeditor.businessobjectsAPI.IShape; import org.pathwayeditor.businessobjectsAPI.Location; import org.pathwayeditor.contextadapter.publicapi.IValidationRuleDefinition; import org.pathwayeditor.contextadapter.toolkit.ndom.GeometryUtils; import org.pathwayeditor.contextadapter.toolkit.ndom.ModelObject; import org.pathwayeditor.contextadapter.toolkit.ndom.NdomException; import uk.ac.ed.inf.Metabolic.excelexport.ModelProcessor; import uk.ac.ed.inf.Metabolic.ndomAPI.ERelType; import uk.ac.ed.inf.Metabolic.ndomAPI.ICompound; import uk.ac.ed.inf.Metabolic.ndomAPI.IModel; import uk.ac.ed.inf.Metabolic.ndomAPI.IReaction; public class MetabolicNDOMFactory extends NDOMFactory { private Map<IShape, MetabolicMolecule> shape2Molecule = new HashMap<IShape, MetabolicMolecule>(); Map<MetabolicReaction, IShape> reaction2Shape = new HashMap<MetabolicReaction, IShape>(); LinkedList<Map<String, MetabolicCompound>> name2Compound = new LinkedList<Map<String, MetabolicCompound>>(); List<ILink> prodLinks; public MetabolicNDOMFactory(IRootMapObject rmo) { super(rmo); } public MetabolicNDOMFactory() { super(); } @Override protected void semanticValidation() { checkOrphanCompounds(); checkOrphanReactions(); } void checkOrphanReactions() { for (IReaction r : ndom.getReactionList()) { if ((r.getSubstrateList().size() == 0)) { IValidationRuleDefinition rd = getReportBuilder() .getRuleStore().getRuleById( MetabolicRuleLoader.ORPHAN_PROCESS_ERROR_ID); IShape el = reaction2Shape.get(r); getReportBuilder().setRuleFailed(el, rd, "Reaction has no substrates"); } if ((r.getProductList().size() == 0)) { IValidationRuleDefinition rd = getReportBuilder() .getRuleStore().getRuleById( MetabolicRuleLoader.ORPHAN_PROCESS_ERROR_ID); IShape el = reaction2Shape.get(r); getReportBuilder().setRuleFailed(el, rd, "Reaction has no products"); } } } void checkOrphanCompounds() { ModelProcessor proc=new ModelProcessor(ndom); for(Entry<IShape,MetabolicMolecule> e:shape2Molecule.entrySet()){ IShape el=e.getKey(); MetabolicMolecule c=e.getValue(); if((c.getInhibitoryRelationList().size()+c.getActivatoryRelationList().size()+c.getCatalyticRelationList().size()+c.getSinkList().size()+c.getSourceList().size())==0){ IValidationRuleDefinition rd = getReportBuilder() .getRuleStore().getRuleById( MetabolicRuleLoader.ORPHAN_COMPOUND_ERROR_ID); getReportBuilder().setRuleFailed(el, rd, "Reaction has no products"); } } } protected void rmo() { name2Compound.addFirst(new HashMap<String, MetabolicCompound>()); super.rmo(); name2Compound.removeFirst(); } void processProdLinks(MetabolicReaction r) { if (r.isReversible()) { IShape s = reaction2Shape.get(r); // Set<ILink> substr = new HashSet<ILink>(); // Set<ILink> prod = new HashSet<ILink>(); Location srcLoc = null; // double srcAngle; for (ILink l : prodLinks) { if (srcLoc == null) { // first link srcLoc = GeometryUtils.getSrcLocation(l, s); substrate(l, r); } else { // all consequitive links Location newLoc = GeometryUtils.getSrcLocation(l, s); if (GeometryUtils.getAngle(srcLoc, newLoc) > 0) { substrate(l, r); } else { productsIrr(l, r); } } } } prodLinks = null; } @Override protected void products(ILink el, MetabolicReaction r) { if (r.isReversible()) { prodLinks.add(el); } else { productsIrr(el, r); } } private void productsIrr(ILink el, MetabolicReaction r) { // TODO separate substrates from products MetabolicRelation rel = production(el); r.addProduct(rel); IShape targ = el.getTarget(); MetabolicMolecule mol = shape2Molecule.get(targ); if (mol == null) { IValidationRuleDefinition rd = getReportBuilder().getRuleStore() .getRuleById(MetabolicRuleLoader.NOT_REGISTERED_ERROR_ID); getReportBuilder() .setRuleFailed(el, rd, "Molecule in Production relation is not registered in the model"); // error("Molecule in Production relation is not registered in the // model"); } try { mol.addSource(rel); String vn = rel.getVarName(); String id = mol.getId(); updateKL(r, vn, id); } catch (NdomException e) { report(e); e.printStackTrace(); } } void updateKL(MetabolicReaction r, String vn, String id) { String kineticLaw = r.getKineticLaw(); if (kineticLaw != null) { kineticLaw = kineticLaw.replaceAll(vn, id); r.setKineticLaw(kineticLaw); } } @Override protected void substrate(ILink el, MetabolicReaction r) { IShape targ =null; MetabolicRelation rel = null; if (r.isReversible()){ if( "Consume".equals(el.getObjectType().getTypeName())) { // error("Consumption link to reversible reaction"); IValidationRuleDefinition rd = getReportBuilder() .getRuleStore() .getRuleById( MetabolicRuleLoader.CONSUMPTION_TO_REVERSIBLE_ERROR_ID); getReportBuilder().setRuleFailed(el, rd, "Consumption link to reversible reaction"); return; }else{ rel = consumptionRev(el); targ = el.getTarget(); } }else{ rel = consumption(el); targ = el.getSource(); } r.addSubstrate(rel); MetabolicMolecule mol = shape2Molecule.get(targ); if (mol == null) { IValidationRuleDefinition rd = getReportBuilder().getRuleStore() .getRuleById(MetabolicRuleLoader.NOT_REGISTERED_ERROR_ID); getReportBuilder() .setRuleFailed(el, rd, "Molecule in Consumption relation is not registered in the model"); // error("Molecule in Consumption relation is not registered in the // model"); } try { mol.addSink(rel); String vn = rel.getVarName(); String id = mol.getId(); updateKL(r, vn, id); } catch (NdomException e) { report(e); e.printStackTrace(); } } private MetabolicRelation consumptionRev(ILink el) { MetabolicRelation rel = relation(el, ERelType.Consumption); rel.setRole(el.getSrcPort().getPropertyByName("ROLE").getValue()); // rel.setStoichiometry(getInt(el.getTargetPort().getPropertyByName( // "STOICH").getValue(), "Wrong stoichiometry\t")); setStoichiometry(el, el.getSrcPort(),rel); return rel; } @Override protected void activate(ILink el, MetabolicReaction r) { MetabolicRelation rel = activation(el); if (r == null) { IValidationRuleDefinition rd = getReportBuilder().getRuleStore() .getRuleById(MetabolicRuleLoader.NOT_REGISTERED_ERROR_ID); getReportBuilder() .setRuleFailed(el, rd, "Reaction for Activation relation is not registered in the model"); // error("Reaction for Activation relation is not registered in the // model"); } r.addActivator(rel); IShape src = el.getSource(); MetabolicMolecule mol = shape2Molecule.get(src); if (mol == null) { IValidationRuleDefinition rd = getReportBuilder().getRuleStore() .getRuleById(MetabolicRuleLoader.NOT_REGISTERED_ERROR_ID); getReportBuilder() .setRuleFailed(el, rd, "Molecule for Activation relation is not registered in the model"); } try { mol.addActivatoryRelation(rel); } catch (NdomException e) { report(e); e.printStackTrace(); } } @Override protected void inhibit(ILink el, MetabolicReaction r) { MetabolicRelation rel = inhibition(el); if (r == null) { IValidationRuleDefinition rd = getReportBuilder().getRuleStore() .getRuleById(MetabolicRuleLoader.NOT_REGISTERED_ERROR_ID); getReportBuilder() .setRuleFailed(el, rd, "Reaction for Inhibiton relation is not registered in the model"); } r.addInhibitor(rel); IShape src = el.getSource(); MetabolicMolecule mol = shape2Molecule.get(src); if (mol == null) { IValidationRuleDefinition rd = getReportBuilder().getRuleStore() .getRuleById(MetabolicRuleLoader.NOT_REGISTERED_ERROR_ID); getReportBuilder() .setRuleFailed(el, rd, "Molecule for Inhibiton relation is not registered in the model"); } try { mol.addInhibitoryRelation(rel); } catch (NdomException e) { report(e); e.printStackTrace(); } } @Override protected void catalysis(ILink el, MetabolicReaction r) { MetabolicRelation rel = catalysis(el); r.addCatalyst(rel); IShape src = el.getSource(); MetabolicMolecule mol = shape2Molecule.get(src); if (mol == null) { IValidationRuleDefinition rd = getReportBuilder().getRuleStore() .getRuleById(MetabolicRuleLoader.NOT_REGISTERED_ERROR_ID); getReportBuilder() .setRuleFailed(el, rd, "Molecule for Catalysis relation is not registered in the model"); } try { mol.addCatalyticRelation(rel); } catch (NdomException e) { report(e); e.printStackTrace(); } } @Override protected void macromolecule(MetabolicCompartment comaprtment, IMapObject mapObject) { MetabolicMacromolecule m = macromolecule(mapObject); shape2Molecule.put((IShape) mapObject, m); comaprtment.addMacromolecule(m); } @Override protected void macromolecule(MetabolicMacromolecule parent, IMapObject mapObject) { MetabolicMacromolecule m = macromolecule(mapObject); shape2Molecule.put((IShape) mapObject, m); parent.addSubunit(m); } @Override protected void compound(MetabolicMacromolecule m, IMapObject mapObject) { MetabolicCompound comp = compound(mapObject); m.addCompound(comp); shape2Molecule.put((IShape) mapObject, comp); } @Override protected void compound(MetabolicCompartment compartment, IMapObject mapObject) { MetabolicCompound comp = compound(mapObject); if (name2Compound.getFirst().containsKey(comp.getName())) { MetabolicCompound comp1 = name2Compound.getFirst().get( comp.getName()); compareCompounds(comp1, comp, compartment, mapObject); comp = comp1; } else { name2Compound.getFirst().put(comp.getName(), comp); compartment.addCompound(comp); } comp.setCloneNumber(comp.getCloneNumber() + 1); shape2Molecule.put((IShape) mapObject, comp); } /** * Check external references for two compound definitions. Validate that two * compounds, having the same name have the same set of references to * external databases. * * @param comp1 * reference compound * @param comp * compound under creation */ private void compareCompounds(MetabolicCompound comp1, MetabolicCompound comp, ModelObject parent, IMapObject mapObject) { String name = comp1.getASCIIName(); // TODO replace with rules if (!comp1.getDescription().equals(comp.getDescription())) { IValidationRuleDefinition rd = getReportBuilder().getRuleStore() .getRuleById(MetabolicRuleLoader.COMP_DEF_ERROR_ID); getReportBuilder().setRuleFailed( mapObject, rd, "Compound " + name + "has two sets of Descriptions: '" + comp1.getDescription() + "' and '" + comp.getDescription() + "'"); } if (!comp1.getDetailedDescription().equals( comp.getDetailedDescription())) { IValidationRuleDefinition rd = getReportBuilder().getRuleStore() .getRuleById(MetabolicRuleLoader.COMP_DEF_ERROR_ID); getReportBuilder().setRuleFailed( mapObject, rd, "Compound " + name + "has two sets of DetailedDescription: '" + comp1.getDetailedDescription() + "' and '" + comp.getDetailedDescription() + "'"); } if (!comp1.getCID().equals(comp.getCID())) { IValidationRuleDefinition rd = getReportBuilder().getRuleStore() .getRuleById(MetabolicRuleLoader.COMP_DEF_ERROR_ID); getReportBuilder().setRuleFailed( mapObject, rd, "Compound " + name + "has two sets of CID: '" + comp1.getCID() + "' and '" + comp.getCID() + "'"); } if (!comp1.getChEBIId().equals(comp.getChEBIId())) { IValidationRuleDefinition rd = getReportBuilder().getRuleStore() .getRuleById(MetabolicRuleLoader.COMP_DEF_ERROR_ID); getReportBuilder().setRuleFailed( mapObject, rd, "Compound " + name + "has two sets of ChEBIId: '" + comp1.getChEBIId() + "' and '" + comp.getChEBIId() + "'"); } if (!comp1.getInChI().equals(comp.getInChI())) { IValidationRuleDefinition rd = getReportBuilder().getRuleStore() .getRuleById(MetabolicRuleLoader.COMP_DEF_ERROR_ID); getReportBuilder().setRuleFailed( mapObject, rd, "Compound " + name + "has two sets of InChI: '" + comp1.getInChI() + "' and '" + comp.getInChI() + "'"); } if (comp1.getIC() != (comp.getIC())) { IValidationRuleDefinition rd = getReportBuilder().getRuleStore() .getRuleById(MetabolicRuleLoader.COMP_DEF_ERROR_ID); getReportBuilder().setRuleFailed( mapObject, rd, "Compound " + name + "has two sets of getIC: '" + comp1.getIC() + "' and '" + comp.getIC() + "'"); } if (!comp1.getPubChemId().equals(comp.getPubChemId())) { IValidationRuleDefinition rd = getReportBuilder().getRuleStore() .getRuleById(MetabolicRuleLoader.COMP_DEF_ERROR_ID); getReportBuilder().setRuleFailed( mapObject, rd, "Compound " + name + "has two sets of PubChemId: '" + comp1.getPubChemId() + "' and '" + comp.getPubChemId() + "'"); } if (!comp1.getSmiles().equals(comp.getSmiles())) { IValidationRuleDefinition rd = getReportBuilder().getRuleStore() .getRuleById(MetabolicRuleLoader.COMP_DEF_ERROR_ID); getReportBuilder().setRuleFailed( mapObject, rd, "Compound " + name + "has two sets of Smiles: '" + comp1.getSmiles() + "' and '" + comp.getSmiles() + "'"); } } @Override protected void compartment(MetabolicCompartment parent, IMapObject mapObject) { MetabolicCompartment compartment = compartment(mapObject); try { name2Compound.addFirst(new HashMap<String, MetabolicCompound>()); parent.addChildCompartment(compartment); List<IMapObject> ch = mapObject.getChildren(); for (IMapObject el : ch) { String ot = el.getObjectType().getTypeName(); if ("Compartment".equals(ot)) { compartment(compartment, el); } else if ("Process".equals(ot)) { process(compartment, el); } else if ("Compound".equals(ot)) { compound(compartment, el); } else if ("Macromolecule".equals(ot)) { macromolecule(compartment, el); } } name2Compound.removeFirst(); } catch (NdomException e) { report(e); e.printStackTrace(); } } @Override protected void connectivity() { for (MetabolicReaction r : reaction2Shape.keySet()) { IShape s = reaction2Shape.get(r); prodLinks = new ArrayList<ILink>(); Set<ILink> lset = s.getSourceLinks(); if (lset.size() == 0) { } for (ILink el : lset) { String ot = el.getObjectType().getTypeName(); if ("Produce".equals(ot)) { products(el, r); } } lset = s.getTargetLinks(); int nsubstr = 0; for (ILink el : lset) { String ot = el.getObjectType().getTypeName(); if ("Consume".equals(ot)) { substrate(el, r); nsubstr++; } else if ("Activation".equals(ot)) { activate(el, r); } else if ("Catalysis".equals(ot)) { catalysis(el, r); } else if ("Inhibition".equals(ot)) { inhibit(el, r); } } if (nsubstr == 0 && !r.isReversible()) { // TODO replace with rules IValidationRuleDefinition rd = getReportBuilder() .getRuleStore().getRuleById( MetabolicRuleLoader.RE_DEF_ERROR_ID); getReportBuilder().setRuleFailed( s, rd, "Reaction is not reversible and do not have substrates \t" + s.getId()); } processProdLinks(r); } } @Override protected void process(ModelObject parent, IMapObject mapObject) { MetabolicReaction re = process(mapObject); // checkParameters(re); ndom.addReaction(re); reaction2Shape.put(re, (IShape) mapObject); } /** * @deprecated replaced by * {@link NDOMFactory#setReParam(IMapObject, MetabolicReaction)} * @param re * process node; */ void checkParameters(MetabolicReaction re) { // String parameters = re.getParameters(); // //TODO replace with rules // if(parameters.trim().length()>0 && // !parameters.matches("^(\\s*\\w+\\s*=\\s*[0-9eE\\-+.]+\\s*;)+$")){ // // !parameters.matches("^(\\s*\\w+\\s*=\\s*[0-9eE-+.]+\\s*;)+$")){ // error("Invalid parameter definition"+parameters); // } } } /* * $Log: MetabolicNDOMFactory.java,v $ Revision 1.8 2008/07/15 11:14:32 smoodie * Refactored so code compiles with new Toolkit framework. * * Revision 1.7 2008/06/24 10:07:40 radams moved rule builder upt oAbstractNDOM * parsers * * Revision 1.6 2008/06/23 14:42:35 radams added report builder to parser * * Revision 1.5 2008/06/23 14:22:34 radams added report builder to parser * * Revision 1.4 2008/06/20 22:48:19 radams imports * * Revision 1.3 2008/06/09 13:26:29 asorokin Bug fixes for SBML export * * Revision 1.2 2008/06/02 15:14:31 asorokin KineticLaw parameters parsing and * validation * * Revision 1.1 2008/06/02 10:31:42 asorokin Reference to Service provider from * all Service interfaces * */
Fixed imports
src/uk/ac/ed/inf/Metabolic/parser/MetabolicNDOMFactory.java
Fixed imports
<ide><path>rc/uk/ac/ed/inf/Metabolic/parser/MetabolicNDOMFactory.java <ide> import org.pathwayeditor.contextadapter.toolkit.ndom.ModelObject; <ide> import org.pathwayeditor.contextadapter.toolkit.ndom.NdomException; <ide> <del>import uk.ac.ed.inf.Metabolic.excelexport.ModelProcessor; <ide> import uk.ac.ed.inf.Metabolic.ndomAPI.ERelType; <del>import uk.ac.ed.inf.Metabolic.ndomAPI.ICompound; <del>import uk.ac.ed.inf.Metabolic.ndomAPI.IModel; <ide> import uk.ac.ed.inf.Metabolic.ndomAPI.IReaction; <ide> <ide> public class MetabolicNDOMFactory extends NDOMFactory { <ide> } <ide> <ide> void checkOrphanCompounds() { <del> ModelProcessor proc=new ModelProcessor(ndom); <add>// ModelProcessor proc=new ModelProcessor(ndom); <ide> for(Entry<IShape,MetabolicMolecule> e:shape2Molecule.entrySet()){ <ide> IShape el=e.getKey(); <ide> MetabolicMolecule c=e.getValue();
Java
agpl-3.0
5018424015df6ae3ff302ebbc8c6ce0a60359d3f
0
animotron/core,animotron/core
/* * Copyright (C) 2011-2012 The Animo Project * http://animotron.org * * This file is part of Animotron. * * Animotron 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. * * Animotron 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 Animotron. * If not, see <http://www.gnu.org/licenses/>. */ package org.animotron.statement.operator; import org.animotron.ATest; import org.animotron.expression.JExpression; import org.animotron.statement.query.PREFER; import org.animotron.statement.relation.USE; import org.junit.Test; import static org.animotron.expression.JExpression._; import static org.animotron.expression.JExpression.__; /** * @author <a href="mailto:[email protected]">Dmitriy Shabanov</a> * @author <a href="mailto:[email protected]">Evgeny Gazdovsky</a> * */ public class PreferTest extends ATest { @Test public void test_0() throws Throwable { __( new JExpression( _(DEF._, "A", _(AN._, "X")) ), new JExpression( _(DEF._, "B", _(AN._, "X")) ) ); JExpression test = new JExpression( _(PREFER._, "X") ); assertAnimoResultOneStep(test, ""); } @Test public void test_01() throws Throwable { __( new JExpression( _(DEF._, "A", _(AN._, "X")) ), new JExpression( _(DEF._, "B", _(AN._, "X")) ) ); JExpression test = new JExpression( _(PREFER._, "X", _(USE._, "X")) ); assertAnimoResultOneStep(test, "A X. B X."); } @Test public void test_02() throws Throwable { __( new JExpression( _(DEF._, "A", _(AN._, "X")) ), new JExpression( _(DEF._, "B", _(AN._, "X")) ) ); JExpression test = new JExpression( _(PREFER._, "X", _(USE._, "A")) ); assertAnimoResultOneStep(test, "A X."); } @Test public void test_03() throws Throwable { __( new JExpression( _(DEF._, "A", _(AN._, "X")) ), new JExpression( _(DEF._, "B", _(AN._, "X")) ) ); JExpression test = new JExpression( _(PREFER._, "X", _(USE._, "B")) ); assertAnimoResultOneStep(test, "B X."); } }
src/test/java/org/animotron/statement/operator/PreferTest.java
/* * Copyright (C) 2011-2012 The Animo Project * http://animotron.org * * This file is part of Animotron. * * Animotron 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. * * Animotron 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 Animotron. * If not, see <http://www.gnu.org/licenses/>. */ package org.animotron.statement.operator; import org.animotron.ATest; import org.animotron.expression.JExpression; import org.animotron.statement.query.PREFER; import org.animotron.statement.relation.USE; import org.junit.Test; import static org.animotron.expression.JExpression._; import static org.animotron.expression.JExpression.__; /** * @author <a href="mailto:[email protected]">Dmitriy Shabanov</a> * @author <a href="mailto:[email protected]">Evgeny Gazdovsky</a> * */ public class PreferTest extends ATest { @Test public void test_0() throws Throwable { __( new JExpression( _(DEF._, "A", _(AN._, "X")) ), new JExpression( _(DEF._, "B", _(AN._, "X")) ) ); JExpression test = new JExpression( _(PREFER._, "X") ); assertAnimoResultOneStep(test, ""); } @Test public void test_01() throws Throwable { __( new JExpression( _(DEF._, "A", _(AN._, "X")) ), new JExpression( _(DEF._, "B", _(AN._, "X")) ) ); JExpression test = new JExpression( _(PREFER._, "X", _(USE._, "X")) ); assertAnimoResultOneStep(test, "def A X. def B X."); } @Test public void test_02() throws Throwable { __( new JExpression( _(DEF._, "A", _(AN._, "X")) ), new JExpression( _(DEF._, "B", _(AN._, "X")) ) ); JExpression test = new JExpression( _(PREFER._, "X", _(USE._, "A")) ); assertAnimoResultOneStep(test, "def A X."); } @Test public void test_03() throws Throwable { __( new JExpression( _(DEF._, "A", _(AN._, "X")) ), new JExpression( _(DEF._, "B", _(AN._, "X")) ) ); JExpression test = new JExpression( _(PREFER._, "X", _(USE._, "B")) ); assertAnimoResultOneStep(test, "def B X."); } }
review
src/test/java/org/animotron/statement/operator/PreferTest.java
review
<ide><path>rc/test/java/org/animotron/statement/operator/PreferTest.java <ide> JExpression test = new JExpression( <ide> _(PREFER._, "X", _(USE._, "X")) <ide> ); <del> assertAnimoResultOneStep(test, "def A X. def B X."); <add> assertAnimoResultOneStep(test, "A X. B X."); <ide> <ide> } <ide> <ide> JExpression test = new JExpression( <ide> _(PREFER._, "X", _(USE._, "A")) <ide> ); <del> assertAnimoResultOneStep(test, "def A X."); <add> assertAnimoResultOneStep(test, "A X."); <ide> <ide> } <ide> <ide> JExpression test = new JExpression( <ide> _(PREFER._, "X", _(USE._, "B")) <ide> ); <del> assertAnimoResultOneStep(test, "def B X."); <add> assertAnimoResultOneStep(test, "B X."); <ide> } <ide> }
JavaScript
mit
54779cb0f991f7770655c6af643ac7907601409a
0
temich/apic.js,temich/apic.js
if (typeof define !== 'function') { //noinspection JSUnresolvedVariable var define = require('amdefine')(module); } define(function (require) { var transport = require('./transport'), auth = require('./auth'), urlencode = require('./urlencode'), Exception = require('./exception'); var placeholder = /^{(.+)}$/, safeMethods = { 'GET': true, 'HEAD': true, 'OPTIONS': true }, synonyms = { 'PUT': ['save', 'replace'], 'POST': ['add'], 'DELETE': ['remove'] }; function result(value) { if (value.indexOf('=') === -1) { return value; } var parts = value.split('='); // TODO: remove primitive type object wrapper value = new String(parts[0]); value.variable = parts[1]; return value; } function last(arr, except) { except || (except = 0); return typeof arr[arr.length - except - 1]; } return function apic(desc, options) { options = options || {}; var root = {}, base = desc.base, variables = {}, augments = {}, language; var scheme = 'http:'; options.synonyms = options.synonyms || synonyms; options.tokenHeader = options.tokenHeader || 'X-Security-Token'; options.authorizationHeader = options.authorizationHeader || 'Authorization'; if (typeof window !== 'undefined') { scheme = location.protocol; // current URI scheme } auth.apply(root); root.augment = function (name, value) { if (value === undefined) { return augments[name]; } augments[name] = value; }; root.localize = function (value) { if (value !== undefined) { language = value; } return language; }; function method(verb, uri, res, params, secure) { var safe = safeMethods[verb] || false, protocol = (secure = secure || !safe) ? 'https:' : scheme; // do not ever use this if (options.__forceProtocol) { protocol = options.__forceProtocol; } return function () { var args = Array.prototype.slice.call(arguments), headers = last(args) === 'object' && last(args, 1) === 'function' ? args.pop() : {}, callback = (last(args) === 'function' || last(args) === 'undefined') ? args.pop() : undefined, representation = last(args) === 'object' ? args.pop() : undefined, query = last(args) === 'object' ? args.pop() : {}, path = uri, _; if (safeMethods[verb]) { query = representation || {}; representation = undefined; } /* Check if all necessary arguments passed in arguments or have default variable value */ if (params.reduce(function (a, b) { return a - +(query[b] !== undefined || variables[b.variable] !== undefined); }, params.length) > args.length) { throw new Error([ params.length, ' argument', (params.length === 1 ? '' : 's'), params.length ? ' (' + params.join(', ') + ')' : '', ' expected ', args.length, ' given', args.length ? ' (' + args.join(', ') + ')' : '' ].join('')); } params.forEach(function (name, i) { if (!query[name]) { query[name] = args[i] === undefined ? (name.variable && variables[name.variable]) : args[i]; } if (name.template) { var _ = '{' + name + '}', value = args[i] || query[name]; path.indexOf(_) === -1 ? (path += '/' + value) : (path = path.replace(_, value)); delete query[name]; } }); // cleanup for (_ in query) { if (query[_] === undefined) { delete query[_]; } } if (secure && root.authorize()) { headers[options.authorizationHeader] = root.authorize(); } for (_ in augments) { if (augments[_] !== null) { headers[_] = augments[_]; } } if (language) { if (safe) { headers['Accept-Language'] = language; } else { headers['Content-Language'] = language; } } transport.request({ uri: protocol + base + path + urlencode.encode(query), method: verb, headers: headers, body: representation, cookie: options.cookie }, function (err, body, xhr) { var token; function cb(err) { if (!callback) { return; } var args = [err, body]; /** * Pass xhr object only if explicitly expected * otherwise some libraries using 'arguments' object * can work incorrectly */ callback.length === 3 && args.push(xhr); callback.apply(this, args); } if (err) { if (err.status === 401) { root.unauthorize(); } cb(new Exception(err, body)); return; } res.variable && (variables[res.variable] = body[res]); if (secure) { token = xhr.getResponseHeader(options.tokenHeader); token && root.authorize.token(token, root.authorize.realm()); } cb(null); }); }; } return function generate(map, uri, res) { var key, value, parts, secure, transparent, tree, _; res = res || {}; for (key in map) { if (map.hasOwnProperty(key) && key !== '@') { value = map[key]; transparent = key.match(placeholder); key = (parts = key.split('#')).shift(); parts = parts.map(function (name) { var template, variable, match; if (name.charAt(0) === '/') { template = true; name = name.substr(1); } if (match = name.match(placeholder)) { _ = match[1].split('='); name = _[0]; variable = _[1]; } // monkey code // TODO: remove primitive type object wrapper name = new String(name); name.template = template; name.variable = variable; return name; }); if (key.charAt(key.length - 1) === '*') secure = !!(key = key.substring(0, key.length - 1)); if (key.charAt(0) !== ':') { _ = key.toLowerCase(); tree = typeof value === 'string' ? method(key, uri || '/', result(value), parts, secure) : generate(value, (uri || '') + '/' + (value['@'] || key), transparent && res); transparent || (res[_] = tree); options.synonyms[key] && options.synonyms[key].forEach(function (alias) { res[alias] || (res[alias] = res[_]); }); } else res[key.substr(1)] = res[value.toLowerCase()]; } } return res; }(desc.resources, undefined, root); }; });
lib/apic.js
if (typeof define !== 'function') { //noinspection JSUnresolvedVariable var define = require('amdefine')(module); } define(function (require) { var transport = require('./transport'), auth = require('./auth'), urlencode = require('./urlencode'), Exception = require('./exception'); var placeholder = /^{(.+)}$/, safeMethods = { 'GET': true, 'HEAD': true, 'OPTIONS': true }, synonyms = { 'PUT': ['save', 'replace'], 'POST': ['add'], 'DELETE': ['remove'] }; function result(value) { if (value.indexOf('=') === -1) { return value; } var parts = value.split('='); // TODO: remove primitive type object wrapper value = new String(parts[0]); value.variable = parts[1]; return value; } function last(arr, except) { except || (except = 0); return typeof arr[arr.length - except - 1]; } return function apic(desc, options) { options = options || {}; var root = {}, base = desc.base, variables = {}, augments = {}; var scheme = 'http:'; options.synonyms = options.synonyms || synonyms; options.tokenHeader = options.tokenHeader || 'X-Security-Token'; options.authorizationHeader = options.authorizationHeader || 'Authorization'; if (typeof window !== 'undefined') { scheme = location.protocol; // current URI scheme } auth.apply(root); root.augment = function (name, value) { if (value === undefined) { return augments[name]; } augments[name] = value; }; function method(verb, uri, res, params, secure) { var safe = safeMethods[verb] || false, protocol = (secure = secure || !safe) ? 'https:' : scheme; // do not ever use this if (options.__forceProtocol) { protocol = options.__forceProtocol; } return function () { var args = Array.prototype.slice.call(arguments), headers = last(args) === 'object' && last(args, 1) === 'function' ? args.pop() : {}, callback = (last(args) === 'function' || last(args) === 'undefined') ? args.pop() : undefined, representation = last(args) === 'object' ? args.pop() : undefined, query = last(args) === 'object' ? args.pop() : {}, path = uri, _; if (safeMethods[verb]) { query = representation || {}; representation = undefined; } /* Check if all necessary arguments passed in arguments or have default variable value */ if (params.reduce(function (a, b) { return a - +(query[b] !== undefined || variables[b.variable] !== undefined); }, params.length) > args.length) { throw new Error([ params.length, ' argument', (params.length === 1 ? '' : 's'), params.length ? ' (' + params.join(', ') + ')' : '', ' expected ', args.length, ' given', args.length ? ' (' + args.join(', ') + ')' : '' ].join('')); } params.forEach(function (name, i) { if (!query[name]) { query[name] = args[i] === undefined ? (name.variable && variables[name.variable]) : args[i]; } if (name.template) { var _ = '{' + name + '}', value = args[i] || query[name]; path.indexOf(_) === -1 ? (path += '/' + value) : (path = path.replace(_, value)); delete query[name]; } }); // cleanup for (_ in query) { if (query[_] === undefined) { delete query[_]; } } if (secure && root.authorize()) { headers[options.authorizationHeader] = root.authorize(); } for (_ in augments) { if (augments[_] !== null) { headers[_] = augments[_]; } } transport.request({ uri: protocol + base + path + urlencode.encode(query), method: verb, headers: headers, body: representation, cookie: options.cookie }, function (err, body, xhr) { var token; function cb(err) { if (!callback) { return; } var args = [err, body]; /** * Pass xhr object only if explicitly expected * otherwise some libraries using 'arguments' object * can work incorrectly */ callback.length === 3 && args.push(xhr); callback.apply(this, args); } if (err) { if (err.status === 401) { root.unauthorize(); } cb(new Exception(err, body)); return; } res.variable && (variables[res.variable] = body[res]); if (secure) { token = xhr.getResponseHeader(options.tokenHeader); token && root.authorize.token(token, root.authorize.realm()); } cb(null); }); }; } return function generate(map, uri, res) { var key, value, parts, secure, transparent, tree, _; res = res || {}; for (key in map) { if (map.hasOwnProperty(key) && key !== '@') { value = map[key]; transparent = key.match(placeholder); key = (parts = key.split('#')).shift(); parts = parts.map(function (name) { var template, variable, match; if (name.charAt(0) === '/') { template = true; name = name.substr(1); } if (match = name.match(placeholder)) { _ = match[1].split('='); name = _[0]; variable = _[1]; } // monkey code // TODO: remove primitive type object wrapper name = new String(name); name.template = template; name.variable = variable; return name; }); if (key.charAt(key.length - 1) === '*') secure = !!(key = key.substring(0, key.length - 1)); if (key.charAt(0) !== ':') { _ = key.toLowerCase(); tree = typeof value === 'string' ? method(key, uri || '/', result(value), parts, secure) : generate(value, (uri || '') + '/' + (value['@'] || key), transparent && res); transparent || (res[_] = tree); options.synonyms[key] && options.synonyms[key].forEach(function (alias) { res[alias] || (res[alias] = res[_]); }); } else res[key.substr(1)] = res[value.toLowerCase()]; } } return res; }(desc.resources, undefined, root); }; });
Added method to indicate the content locale
lib/apic.js
Added method to indicate the content locale
<ide><path>ib/apic.js <ide> var root = {}, <ide> base = desc.base, <ide> variables = {}, <del> augments = {}; <add> augments = {}, <add> language; <ide> <ide> var scheme = 'http:'; <ide> <ide> } <ide> <ide> augments[name] = value; <add> }; <add> <add> root.localize = function (value) { <add> <add> if (value !== undefined) { <add> language = value; <add> } <add> <add> return language; <ide> }; <ide> <ide> function method(verb, uri, res, params, secure) { <ide> <ide> } <ide> <add> if (language) { <add> <add> if (safe) { <add> headers['Accept-Language'] = language; <add> } else { <add> headers['Content-Language'] = language; <add> } <add> <add> } <add> <ide> transport.request({ <ide> uri: protocol + base + path + urlencode.encode(query), <ide> method: verb,
Java
bsd-3-clause
08f874c74b1e0ccd3d5881ed8b7d1153d3f5111b
0
ksclarke/basex,deshmnnit04/basex,ksclarke/basex,vincentml/basex,dimitarp/basex,BaseXdb/basex,dimitarp/basex,JensErat/basex,deshmnnit04/basex,BaseXdb/basex,drmacro/basex,drmacro/basex,ksclarke/basex,vincentml/basex,joansmith/basex,deshmnnit04/basex,vincentml/basex,drmacro/basex,BaseXdb/basex,drmacro/basex,joansmith/basex,joansmith/basex,deshmnnit04/basex,BaseXdb/basex,joansmith/basex,JensErat/basex,deshmnnit04/basex,deshmnnit04/basex,ksclarke/basex,dimitarp/basex,drmacro/basex,ksclarke/basex,drmacro/basex,ksclarke/basex,joansmith/basex,BaseXdb/basex,ksclarke/basex,deshmnnit04/basex,drmacro/basex,dimitarp/basex,JensErat/basex,vincentml/basex,ksclarke/basex,JensErat/basex,joansmith/basex,dimitarp/basex,deshmnnit04/basex,JensErat/basex,joansmith/basex,deshmnnit04/basex,ksclarke/basex,JensErat/basex,drmacro/basex,vincentml/basex,vincentml/basex,dimitarp/basex,vincentml/basex,JensErat/basex,JensErat/basex,dimitarp/basex,vincentml/basex,joansmith/basex,BaseXdb/basex,BaseXdb/basex,BaseXdb/basex,joansmith/basex,vincentml/basex,deshmnnit04/basex,dimitarp/basex,vincentml/basex,ksclarke/basex,deshmnnit04/basex,BaseXdb/basex,dimitarp/basex,joansmith/basex,BaseXdb/basex,vincentml/basex,ksclarke/basex,drmacro/basex,dimitarp/basex,ksclarke/basex,BaseXdb/basex,dimitarp/basex,drmacro/basex,drmacro/basex,JensErat/basex,JensErat/basex,BaseXdb/basex,JensErat/basex,joansmith/basex,JensErat/basex,joansmith/basex,deshmnnit04/basex,vincentml/basex,drmacro/basex,dimitarp/basex
package org.basex.gui.view.plot; import static org.basex.util.Token.*; import java.util.Arrays; import org.basex.data.Data; import org.basex.data.Nodes; import org.basex.data.StatsKey.Kind; import org.basex.gui.GUI; import org.basex.index.Names; import org.basex.util.IntList; import org.basex.util.TokenList; /** * An additional layer which prepares the data for the scatter plot. * * @author Workgroup DBIS, University of Konstanz 2005-08, ISC License * @author Lukas Kircher */ public final class PlotData { /** The x axis of the plot. */ final PlotAxis xAxis; /** The y axis of the plot. */ final PlotAxis yAxis; /** Items pre values. */ int[] pres; /** Number of items displayed in plot. */ int size; /** Item token selected by user. */ byte[] item = EMPTY; /** * Default Constructor. */ public PlotData() { xAxis = new PlotAxis(this); yAxis = new PlotAxis(this); //xAxis.log = true; //yAxis.log = true; pres = new int[0]; } /** * Returns a string array with all top items * and the keys of the specified set. * @return key array */ TokenList getItems() { final Data data = GUI.context.data(); final TokenList tl = new TokenList(); for(final byte[] k : data.skel.desc(EMPTY, true, true)) { if(getCategories(k).size > 1) tl.add(k); } return tl; } /** * Returns a string array with suitable categories for the specified item. * @param it top item * @return key array */ TokenList getCategories(final byte[] it) { final Data data = GUI.context.data(); final TokenList tl = new TokenList(); for(final byte[] k : data.skel.desc(it, true, false)) { final Names index = startsWith(k, '@') ? data.atts : data.tags; if(index.stat(index.id(delete(k, '@'))).kind != Kind.NONE) tl.add(k); } return tl; } /** * Called if the user changes the item level displayed in the plot. If a new * item was selected the plot data is recalculated. * @param newItem item selected by the user * @return true if a new item was selected and the plot data has been * recalculated */ boolean setItem(final String newItem) { if(newItem == null) return false; final byte[] b = token(newItem); if(eq(b, item)) return false; item = b; refreshItems(GUI.context.current(), true); return true; } /** * Refreshes item list and coordinates if the selection has changed. So far * only numerical data is considered for plotting. * @param context context to be displayed * @param sub determine descendant nodes of given context nodes */ void refreshItems(final Nodes context, final boolean sub) { final Data data = GUI.context.data(); final IntList tmpPres = new IntList(); final int itmID = data.tagID(item); if(!sub) { pres = context.nodes; Arrays.sort(pres); size = pres.length; return; } final int[] contextPres = context.nodes; for(int i = 0; i < contextPres.length; i++) { int p = contextPres[i]; final int nl = p + data.size(p, Data.ELEM); while(p < nl) { final int kind = data.kind(p); if(kind == Data.ELEM) { if(data.tagID(p) == itmID) tmpPres.add(p); p += data.attSize(p, kind); } else { p++; } } } pres = tmpPres.finish(); Arrays.sort(pres); size = pres.length; } /** * Returns the array position of a given pre value by performing a binary * search on the sorted pre values array currently displayed in the plot. * @param pre pre value to be looked up * @return array index if found, -1 if not */ int findPre(final int pre) { return Arrays.binarySearch(pres, pre); } }
src/org/basex/gui/view/plot/PlotData.java
package org.basex.gui.view.plot; import static org.basex.util.Token.*; import java.util.Arrays; import org.basex.data.Data; import org.basex.data.Nodes; import org.basex.data.StatsKey.Kind; import org.basex.gui.GUI; import org.basex.index.Names; import org.basex.util.IntList; import org.basex.util.TokenList; /** * An additional layer which prepares the data for the scatter plot. * * @author Workgroup DBIS, University of Konstanz 2005-08, ISC License * @author Lukas Kircher */ public final class PlotData { /** The x axis of the plot. */ final PlotAxis xAxis; /** The y axis of the plot. */ final PlotAxis yAxis; /** Items pre values. */ int[] pres; /** Number of items displayed in plot. */ int size; /** Item token selected by user. */ byte[] item = EMPTY; /** * Default Constructor. */ public PlotData() { xAxis = new PlotAxis(this); yAxis = new PlotAxis(this); xAxis.log = true; yAxis.log = true; pres = new int[0]; } /** * Returns a string array with all top items * and the keys of the specified set. * @return key array */ TokenList getItems() { final Data data = GUI.context.data(); final TokenList tl = new TokenList(); for(final byte[] k : data.skel.desc(EMPTY, true, true)) { if(getCategories(k).size > 1) tl.add(k); } return tl; } /** * Returns a string array with suitable categories for the specified item. * @param it top item * @return key array */ TokenList getCategories(final byte[] it) { final Data data = GUI.context.data(); final TokenList tl = new TokenList(); for(final byte[] k : data.skel.desc(it, true, false)) { final Names index = startsWith(k, '@') ? data.atts : data.tags; if(index.stat(index.id(delete(k, '@'))).kind != Kind.NONE) tl.add(k); } return tl; } /** * Called if the user changes the item level displayed in the plot. If a new * item was selected the plot data is recalculated. * @param newItem item selected by the user * @return true if a new item was selected and the plot data has been * recalculated */ boolean setItem(final String newItem) { if(newItem == null) return false; final byte[] b = token(newItem); if(eq(b, item)) return false; item = b; refreshItems(GUI.context.current(), true); return true; } /** * Refreshes item list and coordinates if the selection has changed. So far * only numerical data is considered for plotting. * @param context context to be displayed * @param sub determine descendant nodes of given context nodes */ void refreshItems(final Nodes context, final boolean sub) { final Data data = GUI.context.data(); final IntList tmpPres = new IntList(); final int itmID = data.tagID(item); if(!sub) { pres = context.nodes; Arrays.sort(pres); size = pres.length; return; } final int[] contextPres = context.nodes; for(int i = 0; i < contextPres.length; i++) { int p = contextPres[i]; final int nl = p + data.size(p, Data.ELEM); while(p < nl) { final int kind = data.kind(p); if(kind == Data.ELEM) { if(data.tagID(p) == itmID) tmpPres.add(p); p += data.attSize(p, kind); } else { p++; } } } pres = tmpPres.finish(); Arrays.sort(pres); size = pres.length; } /** * Returns the array position of a given pre value by performing a binary * search on the sorted pre values array currently displayed in the plot. * @param pre pre value to be looked up * @return array index if found, -1 if not */ int findPre(final int pre) { return Arrays.binarySearch(pres, pre); } }
plot bugfix
src/org/basex/gui/view/plot/PlotData.java
plot bugfix
<ide><path>rc/org/basex/gui/view/plot/PlotData.java <ide> public PlotData() { <ide> xAxis = new PlotAxis(this); <ide> yAxis = new PlotAxis(this); <del> xAxis.log = true; <del> yAxis.log = true; <add> //xAxis.log = true; <add> //yAxis.log = true; <ide> pres = new int[0]; <ide> } <ide>
Java
lgpl-2.1
3d8cef0dba2421bbfb6764ac46e5f573fb94f3e1
0
drhee/toxoMine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,drhee/toxoMine,JoeCarlson/intermine,tomck/intermine,zebrafishmine/intermine,justincc/intermine,tomck/intermine,joshkh/intermine,kimrutherford/intermine,zebrafishmine/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,kimrutherford/intermine,tomck/intermine,kimrutherford/intermine,justincc/intermine,Arabidopsis-Information-Portal/intermine,drhee/toxoMine,JoeCarlson/intermine,tomck/intermine,joshkh/intermine,zebrafishmine/intermine,zebrafishmine/intermine,kimrutherford/intermine,elsiklab/intermine,drhee/toxoMine,justincc/intermine,elsiklab/intermine,joshkh/intermine,elsiklab/intermine,Arabidopsis-Information-Portal/intermine,JoeCarlson/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,justincc/intermine,tomck/intermine,joshkh/intermine,JoeCarlson/intermine,justincc/intermine,Arabidopsis-Information-Portal/intermine,drhee/toxoMine,kimrutherford/intermine,justincc/intermine,elsiklab/intermine,Arabidopsis-Information-Portal/intermine,drhee/toxoMine,justincc/intermine,JoeCarlson/intermine,zebrafishmine/intermine,kimrutherford/intermine,kimrutherford/intermine,tomck/intermine,joshkh/intermine,zebrafishmine/intermine,zebrafishmine/intermine,tomck/intermine,elsiklab/intermine,elsiklab/intermine,justincc/intermine,zebrafishmine/intermine,elsiklab/intermine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,zebrafishmine/intermine,joshkh/intermine,drhee/toxoMine,joshkh/intermine,JoeCarlson/intermine,justincc/intermine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,JoeCarlson/intermine,kimrutherford/intermine,drhee/toxoMine,tomck/intermine,drhee/toxoMine,elsiklab/intermine,JoeCarlson/intermine
package org.intermine.web.logic.query; /* * Copyright (C) 2002-2008 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.util.HashMap; import java.util.List; import java.util.Map; import org.intermine.metadata.FieldDescriptor; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreException; import org.intermine.objectstore.flatouterjoins.ObjectStoreFlatOuterJoinsImpl; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.QuerySelectable; import org.intermine.objectstore.query.Results; import org.intermine.pathquery.PathQuery; import org.intermine.web.logic.Constants; import org.intermine.web.logic.WebUtil; import org.intermine.web.logic.bag.BagQueryConfig; import org.intermine.web.logic.bag.BagQueryResult; import org.intermine.web.logic.bag.BagQueryRunner; import org.intermine.web.logic.bag.InterMineBag; import org.intermine.web.logic.profile.Profile; import org.intermine.web.logic.results.WebResults; import org.intermine.web.logic.search.SearchRepository; import org.intermine.web.logic.template.TemplateQuery; /** * Executes a PathQuery and returns a WebResults object, to be used when multi-row * style results are required. * @author Richard Smith * @author Jakub Kulaviak */ public class WebResultsExecutor { private ObjectStore os; private Map<String, List<FieldDescriptor>> classKeys; private BagQueryConfig bagQueryConfig; private Profile profile; private List<TemplateQuery> conversionTemplates; private SearchRepository searchRepository; /** * Construct with necessary objects to generate and ObjectStore query from a PathQuery and * execute it. * @param os the ObjectStore to run the query in * @param classKeys key fields for classes in the data model * @param bagQueryConfig bag queries to run when intepreting LOOKUP constraints * @param profile the user executing the query - for access to saved lists * @param conversionTemplates templates used for converting bag query results between types * @param searchRepository global search repository to fetch saved bags from */ public WebResultsExecutor(ObjectStore os, Map<String, List<FieldDescriptor>> classKeys, BagQueryConfig bagQueryConfig, Profile profile, List<TemplateQuery> conversionTemplates, SearchRepository searchRepository) { this.os = os; this.classKeys = classKeys; this.bagQueryConfig = bagQueryConfig; this.profile = profile; this.conversionTemplates = conversionTemplates; this.searchRepository = searchRepository; } /** * Create and ObjectStore query from a PathQuery and execute it, returning results in a format * appropriate for displaying a web table. * @param pathQuery the query to execute * @return results in a format appropriate for display in a web page table * @throws ObjectStoreException if problem running query */ public WebResults execute(PathQuery pathQuery) throws ObjectStoreException { Map<String, QuerySelectable> pathToQueryNode = new HashMap<String, QuerySelectable>(); Map<String, BagQueryResult> pathToBagQueryResult = new HashMap<String, BagQueryResult>(); BagQueryRunner bqr = new BagQueryRunner(os, classKeys, bagQueryConfig, conversionTemplates); Map<String, InterMineBag> allBags = WebUtil.getAllBags(profile.getSavedBags(), searchRepository); Query q = MainHelper.makeQuery(pathQuery, allBags, pathToQueryNode, bqr, pathToBagQueryResult, false); ObjectStoreFlatOuterJoinsImpl joinsOs = new ObjectStoreFlatOuterJoinsImpl(os); Results results = joinsOs.execute(q); results.setBatchSize(Constants.BATCH_SIZE); results.setNoPrefetch(); WebResults webResults = new WebResults(pathQuery, results, os.getModel(), pathToQueryNode, classKeys, pathToBagQueryResult); return webResults; } // public ResultsInfo estimate(PathQuery pq) { // return null; // } // // public int count(PathQuery pq) { // return 0; // // } }
intermine/web/main/src/org/intermine/web/logic/query/WebResultsExecutor.java
package org.intermine.web.logic.query; import java.util.HashMap; import java.util.List; import java.util.Map; import org.intermine.metadata.FieldDescriptor; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreException; import org.intermine.objectstore.flatouterjoins.ObjectStoreFlatOuterJoinsImpl; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.QuerySelectable; import org.intermine.objectstore.query.Results; import org.intermine.objectstore.query.ResultsInfo; import org.intermine.pathquery.PathQuery; import org.intermine.web.logic.Constants; import org.intermine.web.logic.WebUtil; import org.intermine.web.logic.bag.BagQueryConfig; import org.intermine.web.logic.bag.BagQueryResult; import org.intermine.web.logic.bag.BagQueryRunner; import org.intermine.web.logic.bag.InterMineBag; import org.intermine.web.logic.profile.Profile; import org.intermine.web.logic.results.WebResults; import org.intermine.web.logic.search.SearchRepository; import org.intermine.web.logic.template.TemplateQuery; // Very preliminary version of path query executor returning WebResults, because it // will be changed heavily checkstyle errors are ignored public class WebResultsExecutor { private ObjectStore os; private Map<String, List<FieldDescriptor>> classKeys; private BagQueryConfig bagQueryConfig; private Profile profile; private List<TemplateQuery> conversionTemplates; private SearchRepository searchRepository; public WebResultsExecutor(ObjectStore os, Map<String, List<FieldDescriptor>> classKeys, BagQueryConfig bagQueryConfig, Profile profile, List<TemplateQuery> conversionTemplates, SearchRepository searchRepository) { this.os = os; this.classKeys = classKeys; this.bagQueryConfig = bagQueryConfig; this.profile = profile; this.conversionTemplates = conversionTemplates; this.searchRepository = searchRepository; } public WebResults execute(PathQuery pathQuery) throws ObjectStoreException { Map<String, QuerySelectable> pathToQueryNode = new HashMap<String, QuerySelectable>(); Map<String, BagQueryResult> pathToBagQueryResult = new HashMap<String, BagQueryResult>(); BagQueryRunner bqr = new BagQueryRunner(os, classKeys, bagQueryConfig, conversionTemplates); Map<String, InterMineBag> allBags = WebUtil.getAllBags(profile.getSavedBags(), searchRepository); Query q = MainHelper.makeQuery(pathQuery, allBags, pathToQueryNode, bqr, pathToBagQueryResult, false); ObjectStoreFlatOuterJoinsImpl joinsOs = new ObjectStoreFlatOuterJoinsImpl(os); Results results = joinsOs.execute(q); results.setBatchSize(Constants.BATCH_SIZE); results.setNoPrefetch(); WebResults webResults = new WebResults(pathQuery, results, os.getModel(), pathToQueryNode, classKeys, pathToBagQueryResult); return webResults; } public ResultsInfo estimate(PathQuery pq) { return null; } public int count(PathQuery pq) { return 0; } }
Checkstyle fixes.
intermine/web/main/src/org/intermine/web/logic/query/WebResultsExecutor.java
Checkstyle fixes.
<ide><path>ntermine/web/main/src/org/intermine/web/logic/query/WebResultsExecutor.java <ide> package org.intermine.web.logic.query; <add> <add>/* <add> * Copyright (C) 2002-2008 FlyMine <add> * <add> * This code may be freely distributed and modified under the <add> * terms of the GNU Lesser General Public Licence. This should <add> * be distributed with the code. See the LICENSE file for more <add> * information or http://www.gnu.org/copyleft/lesser.html. <add> * <add> */ <ide> <ide> import java.util.HashMap; <ide> import java.util.List; <ide> import org.intermine.objectstore.query.Query; <ide> import org.intermine.objectstore.query.QuerySelectable; <ide> import org.intermine.objectstore.query.Results; <del>import org.intermine.objectstore.query.ResultsInfo; <ide> import org.intermine.pathquery.PathQuery; <ide> import org.intermine.web.logic.Constants; <ide> import org.intermine.web.logic.WebUtil; <ide> import org.intermine.web.logic.search.SearchRepository; <ide> import org.intermine.web.logic.template.TemplateQuery; <ide> <del>// Very preliminary version of path query executor returning WebResults, because it <del>// will be changed heavily checkstyle errors are ignored <del> <del>public class WebResultsExecutor { <add>/** <add> * Executes a PathQuery and returns a WebResults object, to be used when multi-row <add> * style results are required. <add> * @author Richard Smith <add> * @author Jakub Kulaviak <add> */ <add>public class WebResultsExecutor <add>{ <ide> private ObjectStore os; <ide> private Map<String, List<FieldDescriptor>> classKeys; <ide> private BagQueryConfig bagQueryConfig; <ide> private List<TemplateQuery> conversionTemplates; <ide> private SearchRepository searchRepository; <ide> <add> /** <add> * Construct with necessary objects to generate and ObjectStore query from a PathQuery and <add> * execute it. <add> * @param os the ObjectStore to run the query in <add> * @param classKeys key fields for classes in the data model <add> * @param bagQueryConfig bag queries to run when intepreting LOOKUP constraints <add> * @param profile the user executing the query - for access to saved lists <add> * @param conversionTemplates templates used for converting bag query results between types <add> * @param searchRepository global search repository to fetch saved bags from <add> */ <ide> public WebResultsExecutor(ObjectStore os, <ide> Map<String, List<FieldDescriptor>> classKeys, <ide> BagQueryConfig bagQueryConfig, <ide> this.searchRepository = searchRepository; <ide> } <ide> <add> /** <add> * Create and ObjectStore query from a PathQuery and execute it, returning results in a format <add> * appropriate for displaying a web table. <add> * @param pathQuery the query to execute <add> * @return results in a format appropriate for display in a web page table <add> * @throws ObjectStoreException if problem running query <add> */ <ide> public WebResults execute(PathQuery pathQuery) throws ObjectStoreException { <ide> Map<String, QuerySelectable> pathToQueryNode = new HashMap<String, QuerySelectable>(); <ide> <ide> Map<String, InterMineBag> allBags = WebUtil.getAllBags(profile.getSavedBags(), <ide> searchRepository); <ide> <del> Query q = MainHelper.makeQuery(pathQuery, allBags, pathToQueryNode, bqr, pathToBagQueryResult, <del> false); <add> Query q = MainHelper.makeQuery(pathQuery, allBags, pathToQueryNode, bqr, <add> pathToBagQueryResult, false); <ide> <ide> ObjectStoreFlatOuterJoinsImpl joinsOs = new ObjectStoreFlatOuterJoinsImpl(os); <ide> Results results = joinsOs.execute(q); <ide> return webResults; <ide> } <ide> <del> public ResultsInfo estimate(PathQuery pq) { <del> return null; <del> } <del> <del> public int count(PathQuery pq) { <del> return 0; <del> <del> } <add>// public ResultsInfo estimate(PathQuery pq) { <add>// return null; <add>// } <add>// <add>// public int count(PathQuery pq) { <add>// return 0; <add>// <add>// } <ide> }
JavaScript
mit
f5b4468b50a08ebbb860ecf2c21f08dc95b32d28
0
getcahoots/api
/* * cahoots-api * * Copyright Cahoots.pw * MIT Licensed * */ /** * @author André König <[email protected]> * */ 'use strict'; var http = require('http'); var debug = require('debug')('cahoots:api:OrganizationsResource'); var services = require('cahoots-api-services'); var schemes = require('cahoots-api-schemes'); var validator = require('cahoots-api-validator'); var middlewares = require('./middlewares/'); module.exports = function instantiate () { var resource = new OrganizationsResource(); return [ { method: 'GET', path: '/organizations', handler: resource.list.bind(resource) }, { method: 'GET', path: '/organizations/:id', handler: resource.one.bind(resource) }, { method: 'POST', path: '/organizations', handler: resource.insert.bind(resource), middlewares: [middlewares.authentication()] } ]; }; /** * The /organizations resource. * */ function OrganizationsResource () { this.$service = services('organization'); this.$schema = schemes('organization'); } /** * POST /organizations * * Persists a new organization. * */ OrganizationsResource.prototype.insert = function insert (req, res) { var self = this; var organization = req.body; var schema = this.$schema.insert; function onValidation (err) { if (err) { debug('Validation failed. Insert of organization impossible: %j', err); return res.status(400).send(http.STATUS_CODES[400]); } self.$service.save(organization, onSave); } function onSave (err, organization) { if (err) { debug('Error while saving a new organization: %j', err); return res.status(500).send(http.STATUS_CODES[500]); } res.status(201).json(organization); } validator(schema).check(organization, onValidation); }; /** * GET /organizations/:id * * Finds an organization by id. * */ OrganizationsResource.prototype.one = function one (req, res) { var id = req.params.id; function onFindById (err, organization) { if (err) { debug('Error while request the organization with the id "%s": %j', id, err); return res.status(500).send(http.STATUS_CODES[500]); } if (!organization) { return res.status(404).json({}); } debug('Found one organization by id "%s": %j', id, organization); res.status(200).json(organization); } this.$service.findById(id, onFindById); }; /** * GET /organizations[?ids=id0, id2] * * Lists all available organizations or organizations by an array of ids. * */ OrganizationsResource.prototype.list = function list (req, res) { var ids = req.query.ids; function onFind (err, organizations) { if (err) { debug('Error while requesting organizations: %j', err); return res.status(500).send(http.STATUS_CODES[500]); } if (!organizations.length) { return res.status(404).json(organizations); } debug('Found %d organization(s).', organizations.length); res.status(200).json(organizations); } if (ids && ids.indexOf(',') !== -1) { ids = ids.split(','); debug('Requested organizations by specific ids: %s', ids); return this.$service.findByIds(ids, onFind); } debug('Requested all organizations.'); this.$service.findAll(onFind); };
app/v1/organizations.js
/* * cahoots-api * * Copyright Cahoots.pw * MIT Licensed * */ /** * @author André König <[email protected]> * */ 'use strict'; var http = require('http'); var debug = require('debug')('cahoots:api:OrganizationsResource'); var services = require('cahoots-api-services'); var schemes = require('cahoots-api-schemes'); var validator = require('cahoots-api-validator'); var middlewares = require('./middlewares/'); module.exports = function instantiate () { var resource = new OrganizationsResource(); return [ { method: 'GET', path: '/organizations', handler: resource.list.bind(resource) }, { method: 'GET', path: '/organizations/:id', handler: resource.one.bind(resource) }, { method: 'POST', path: '/organizations', handler: resource.insert.bind(resource), middlewares: [middlewares.authentication()] } ]; }; /** * The /organizations resource. * */ function OrganizationsResource () { this.$service = services('organization'); this.$schema = schemes('organization'); } /** * POST /organizations * * Persists a new organization. * */ OrganizationsResource.prototype.insert = function insert (req, res) { var self = this; var organization = req.body; var schema = this.$schema.insert; function onValidation (err) { if (err) { debug('Validation failed. Insert of organization impossible: %j', err); return res.status(400).send(http.STATUS_CODES[400]); } self.$service.save(organization, onSave); } function onSave (err, organization) { if (err) { debug('Error while saving a new organization: %j', err); return res.status(500).send(http.STATUS_CODES[500]); } res.status(201).json(organization); } validator(schema).check(organization, onValidation); }; /** * GET /organizations/:id * * Finds an organization by id. * */ OrganizationsResource.prototype.one = function one (req, res) { var id = req.params.id; function onFindById (err, organization) { if (err) { debug('Error while request the organization with the id "%s": %j', id, err); return res.status(500).send(http.STATUS_CODES[500]); } if (!organization) { return res.status(404).json({}); } debug('Found one organization by id "%s": %j', id, organization); res.status(200).json(organization); } this.$service.findById(id, onFindById); }; /** * GET /organizations[?ids=id0, id2] * * Lists all available organizations or organizations by an array of ids. * */ OrganizationsResource.prototype.list = function list (req, res) { var ids = req.query.ids; function onFind (err, organizations) { if (err) { debug('Error while requesting organizations: %j', err); return res.status(500).send(http.STATUS_CODES[500]); } if (!organizations.length) { return res.status(404).json(organizations); } debug('Found %d organization(s)', organizations.length); res.status(200).json(organizations); } if (ids && ids.indexOf(',') !== -1) { ids = ids.split(','); return this.$service.findByIds(ids, onFind); } this.$service.findAll(onFind); };
Extended logging in the organization resource.
app/v1/organizations.js
Extended logging in the organization resource.
<ide><path>pp/v1/organizations.js <ide> return res.status(404).json(organizations); <ide> } <ide> <del> debug('Found %d organization(s)', organizations.length); <add> debug('Found %d organization(s).', organizations.length); <ide> <ide> res.status(200).json(organizations); <ide> } <ide> if (ids && ids.indexOf(',') !== -1) { <ide> ids = ids.split(','); <ide> <add> debug('Requested organizations by specific ids: %s', ids); <add> <ide> return this.$service.findByIds(ids, onFind); <ide> } <ide> <add> debug('Requested all organizations.'); <add> <ide> this.$service.findAll(onFind); <ide> };
Java
apache-2.0
0cd95258f2a294e7da5e04cf7ad7784ae5e99fc5
0
kelemen/JTrim,kelemen/JTrim
package org.jtrim.swing.concurrent; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.swing.SwingUtilities; import org.jtrim.cancel.CancellationToken; import org.jtrim.concurrent.*; import org.jtrim.utils.ExceptionHelper; /** * Defines a {@code TaskExecutorService} which executes submitted tasks on the * <I>AWT Event Dispatch Thread</I>. Submitted tasks are executed in the order * they were submitted. Unlike {@code TaskExecutorService} implementations in * general, {@code SwingTaskExecutor} instances does not need to be shutted down * (although shutdown is still possible). * <P> * In case the services provided by the {@code TaskExecutor} service are * adequate, consider using the more efficient implementations returned by the * static {@link #getSimpleExecutor(boolean) getSimpleExecutor} or * {@link #getStrictExecutor(boolean) getStrictExecutor} methods. * <P> * A static instance can be retrieved by the * {@link #getDefaultInstance() getDefaultInstance} method. The instance * returned by this method can be used as a sensible default value. * * <h3>Thread safety</h3> * Methods of this class are safely accessible from multiple threads * concurrently. * * <h4>Synchronization transparency</h4> * Method of this class are not <I>synchronization transparent</I> unless * otherwise noted. * * @see #getDefaultInstance() * @see #getSimpleExecutor(boolean) * @see #getStrictExecutor(boolean) * * @author Kelemen Attila */ public final class SwingTaskExecutor extends DelegatedTaskExecutorService { private static volatile TaskExecutorService defaultInstance = TaskExecutors.asUnstoppableExecutor(new SwingTaskExecutor()); /** * Returns a {@code TaskExecutorService} which executes tasks submitted to * them on the <I>AWT Event Dispatch Thread</I>. This method always returns * the same {@code TaskExecutorService} instance and is intended to be used * as a sensible default value when an executor is need which executes * task on the EDT. The returned {@code TaskExecutorService} cannot be * shutted down, attempting to do so will cause an unchecked exception to be * thrown. * * @return a {@code TaskExecutorService} which executes tasks submitted to * them on the <I>AWT Event Dispatch Thread</I>. This method never returns * {@code null}. */ public static TaskExecutorService getDefaultInstance() { return defaultInstance; } /** * Returns a {@code TaskExecutor} which executes tasks submitted to * them on the <I>AWT Event Dispatch Thread</I>. The returned executor does * not necessarily executes tasks in the same order as the tasks were * submitted. In case tasks needed to be executed in the same order as they * were submitted to the executor: Use the * {@link #getStrictExecutor(boolean)} method. * <P> * The returned executor is more efficient than an instance of * {@code SwingTaskExecutor}. * * @param alwaysInvokeLater if this argument is {@code true}, submitted * tasks are never executed synchronously on the calling thread (i.e.: * they are always submitted as {@code SwingUtilities.invokeLater} does * it). In case this argument is {@code false}, tasks submitted from the * <I>AWT Event Dispatch Thread</I> will be executed immediately on the * calling thread. * @return a {@code TaskExecutor} which executes tasks submitted to * them on the <I>AWT Event Dispatch Thread</I>. This method never returns * {@code null}. * * @see #getStrictExecutor(boolean) */ public static TaskExecutor getSimpleExecutor(boolean alwaysInvokeLater) { return alwaysInvokeLater ? LazyExecutor.INSTANCE : EagerExecutor.INSTANCE; } /** * Returns a {@code TaskExecutor} which executes tasks submitted to * them on the <I>AWT Event Dispatch Thread</I>. The returned executor * executes tasks in the same order as the tasks were submitted. If you * don't need to execute them in the same order, consider using the * {@link #getSimpleExecutor(boolean)} method. * <P> * The returned executor is more efficient than an instance of * {@code SwingTaskExecutor}. * * @param alwaysInvokeLater if this argument is {@code true}, submitted * tasks are never executed synchronously on the calling thread (i.e.: * they are always submitted as {@code SwingUtilities.invokeLater} does * it). In case this argument is {@code false}, tasks submitted from the * <I>AWT Event Dispatch Thread</I> will be executed immediately on the * calling thread (this may not always possible to execute tasks in the * order they were submitted). * @return a {@code TaskExecutor} which executes tasks submitted to * them on the <I>AWT Event Dispatch Thread</I>. This method never returns * {@code null}. * * @see #getSimpleExecutor(boolean) */ public static TaskExecutor getStrictExecutor(boolean alwaysInvokeLater) { // We silently assume that SwingUtilities.invokeLater // invokes the tasks in the order they were scheduled. // This is not documented but it still seems safe to assume. return alwaysInvokeLater ? LazyExecutor.INSTANCE : new StrictEagerExecutor(); } private enum LazyExecutor implements TaskExecutor { INSTANCE; @Override public void execute( final CancellationToken cancelToken, final CancelableTask task, final CleanupTask cleanupTask) { ExceptionHelper.checkNotNullArgument(cancelToken, "cancelToken"); ExceptionHelper.checkNotNullArgument(task, "task"); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { TaskExecutor executor = SyncTaskExecutor.getSimpleExecutor(); executor.execute(cancelToken, task, cleanupTask); } }); } } private enum EagerExecutor implements TaskExecutor { INSTANCE; @Override public void execute( CancellationToken cancelToken, CancelableTask task, CleanupTask cleanupTask) { ExceptionHelper.checkNotNullArgument(cancelToken, "cancelToken"); ExceptionHelper.checkNotNullArgument(task, "task"); if (SwingUtilities.isEventDispatchThread()) { TaskExecutor executor = SyncTaskExecutor.getSimpleExecutor(); executor.execute(cancelToken, task, cleanupTask); } else { LazyExecutor.INSTANCE.execute(cancelToken, task, cleanupTask); } } } private static class StrictEagerExecutor implements TaskExecutor { // We assume that there are always less than Integer.MAX_VALUE // concurrent tasks. // Having more than this would surely make the application unusable // anyway (since these tasks run on the single Event Dispatch Thread, // this would make it more outrageous). private final AtomicInteger currentlyExecuting = new AtomicInteger(0); @Override public void execute( final CancellationToken cancelToken, final CancelableTask task, final CleanupTask cleanupTask) { ExceptionHelper.checkNotNullArgument(cancelToken, "cancelToken"); ExceptionHelper.checkNotNullArgument(task, "task"); boolean canInvokeNow = currentlyExecuting.get() == 0; // Tasks that are scheduled concurrently this call, // does not matter if they run after this task. // This executor only guarantees that A task happens before // B task, if scheduling A happens before scheduling B // (which implies that they does not run concurrently). if (canInvokeNow && SwingUtilities.isEventDispatchThread()) { TaskExecutor executor = SyncTaskExecutor.getSimpleExecutor(); executor.execute(cancelToken, task, cleanupTask); } else { currentlyExecuting.incrementAndGet(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { try { TaskExecutor executor = SyncTaskExecutor.getSimpleExecutor(); executor.execute(cancelToken, task, cleanupTask); } finally { currentlyExecuting.decrementAndGet(); } } }); } } } /** * Creates a new {@code SwingTaskExecutor} which will execute submitted * tasks on the <I>AWT Event Dispatch Thread</I>. * <P> * This constructor is equivalent to calling * {@code SwingTaskExecutor(true)}. */ public SwingTaskExecutor() { this(true); } /** * Creates a new {@code SwingTaskExecutor} which will execute submitted * tasks on the <I>AWT Event Dispatch Thread</I>. * * @param alwaysInvokeLater if this argument is {@code true}, submitted * tasks are never executed synchronously on the calling thread (i.e.: * they are always submitted as {@code SwingUtilities.invokeLater} does * it). In case this argument is {@code false}, tasks submitted from the * <I>AWT Event Dispatch Thread</I> will be executed immediately on the * calling thread (this may not always possible to execute tasks in the * order they were submitted). */ public SwingTaskExecutor(boolean alwaysInvokeLater) { super(TaskExecutors.upgradeExecutor(getStrictExecutor(alwaysInvokeLater))); } private static void checkWaitOnEDT() { if (SwingUtilities.isEventDispatchThread()) { // Waiting on the EDT would be a good way to cause a dead-lock. throw new IllegalStateException("Cannot wait for termination on the Event Dispatch Thread."); } } /** * {@inheritDoc } * <P> * This method may not be called from the <I>AWT Event Dispatch Thread</I>. * This is forbidden because it is very dead-lock prone: If a task was * submitted to this executor, it could not complete because this method * prevents any task to be executed on the EDT. * * @throws IllegalStateException thrown if the current calling thread is the * <I>AWT Event Dispatch Thread</I> */ @Override public void awaitTermination(CancellationToken cancelToken) { checkWaitOnEDT(); wrappedExecutor.awaitTermination(cancelToken); } /** * {@inheritDoc } * <P> * This method may not be called from the <I>AWT Event Dispatch Thread</I>. * This is forbidden because it is very dead-lock prone: If a task was * submitted to this executor, it could not complete because this method * prevents any task to be executed on the EDT. * * @throws IllegalStateException thrown if the current calling thread is the * <I>AWT Event Dispatch Thread</I> */ @Override public boolean awaitTermination(CancellationToken cancelToken, long timeout, TimeUnit unit) { checkWaitOnEDT(); return wrappedExecutor.awaitTermination(cancelToken, timeout, unit); } }
jtrim-gui/src/main/java/org/jtrim/swing/concurrent/SwingTaskExecutor.java
package org.jtrim.swing.concurrent; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.swing.SwingUtilities; import org.jtrim.cancel.CancellationToken; import org.jtrim.concurrent.*; import org.jtrim.utils.ExceptionHelper; /** * Defines a {@code TaskExecutorService} which executes submitted tasks on the * <I>AWT Event Dispatch Thread</I>. Submitted tasks are executed in the order * they were submitted. Unlike {@code TaskExecutorService} implementations in * general, {@code SwingTaskExecutor} instances does not need to be shutted down * (although shutdown is still possible). * <P> * In case the services provided by the {@code TaskExecutor} service are * adequate, consider using the more efficient implementations returned by the * static {@link #getSimpleExecutor(boolean) getSimpleExecutor} or * {@link #getStrictExecutor(boolean) getStrictExecutor} methods. * <P> * A static instance can be retrieved by the * {@link #getDefaultInstance() getDefaultInstance} method. The instance * returned by this method can be used as a sensible default value. * * <h3>Thread safety</h3> * Methods of this class are safely accessible from multiple threads * concurrently. * * <h4>Synchronization transparency</h4> * Method of this class are not <I>synchronization transparent</I> unless * otherwise noted. * * @see #getDefaultInstance() * @see #getSimpleExecutor(boolean) * @see #getStrictExecutor(boolean) * * @author Kelemen Attila */ public final class SwingTaskExecutor extends DelegatedTaskExecutorService { private static volatile TaskExecutorService defaultInstance = TaskExecutors.asUnstoppableExecutor(new SwingTaskExecutor()); /** * Returns a {@code TaskExecutorService} which executes tasks submitted to * them on the <I>AWT Event Dispatch Thread</I>. This method always returns * the same {@code TaskExecutorService} instance and is intended to be used * as a sensible default value when an executor is need which executes * task on the EDT. The returned {@code TaskExecutorService} cannot be * shutted down, attempting to do so will cause an unchecked exception to be * thrown. * * @return a {@code TaskExecutorService} which executes tasks submitted to * them on the <I>AWT Event Dispatch Thread</I>. This method never returns * {@code null}. */ public static TaskExecutorService getDefaultInstance() { return defaultInstance; } /** * Returns a {@code TaskExecutor} which executes tasks submitted to * them on the <I>AWT Event Dispatch Thread</I>. The returned executor does * not necessarily executes tasks in the same order as the tasks were * submitted. In case tasks needed to be executed in the same order as they * were submitted to the executor: Use the * {@link #getStrictExecutor(boolean)} method. * <P> * The returned executor is more efficient than an instance of * {@code SwingTaskExecutor}. * * @param alwaysInvokeLater if this argument is {@code true}, submitted * tasks are never executed synchronously on the calling thread (i.e.: * they are always submitted as {@code SwingUtilities.invokeLater} does * it). In case this argument is {@code false}, tasks submitted from the * <I>AWT Event Dispatch Thread</I> will be executed immediately on the * calling thread. * @return a {@code TaskExecutor} which executes tasks submitted to * them on the <I>AWT Event Dispatch Thread</I>. This method never returns * {@code null}. * * @see #getStrictExecutor(boolean) */ public static TaskExecutor getSimpleExecutor(boolean alwaysInvokeLater) { return alwaysInvokeLater ? LazyExecutor.INSTANCE : EagerExecutor.INSTANCE; } /** * Returns a {@code TaskExecutor} which executes tasks submitted to * them on the <I>AWT Event Dispatch Thread</I>. The returned executor * executes tasks in the same order as the tasks were submitted. If you * don't need to execute them in the same order, consider using the * {@link #getSimpleExecutor(boolean)} method. * <P> * The returned executor is more efficient than an instance of * {@code SwingTaskExecutor}. * * @param alwaysInvokeLater if this argument is {@code true}, submitted * tasks are never executed synchronously on the calling thread (i.e.: * they are always submitted as {@code SwingUtilities.invokeLater} does * it). In case this argument is {@code false}, tasks submitted from the * <I>AWT Event Dispatch Thread</I> will be executed immediately on the * calling thread (this may not always possible to execute tasks in the * order they were submitted). * @return a {@code TaskExecutor} which executes tasks submitted to * them on the <I>AWT Event Dispatch Thread</I>. This method never returns * {@code null}. * * @see #getSimpleExecutor(boolean) */ public static TaskExecutor getStrictExecutor(boolean alwaysInvokeLater) { // We silently assume that SwingUtilities.invokeLater // invokes the tasks in the order they were scheduled. // This is not documented but it still seems safe to assume. return alwaysInvokeLater ? LazyExecutor.INSTANCE : new StrictEagerExecutor(); } private enum LazyExecutor implements TaskExecutor { INSTANCE; @Override public void execute( final CancellationToken cancelToken, final CancelableTask task, final CleanupTask cleanupTask) { ExceptionHelper.checkNotNullArgument(cancelToken, "cancelToken"); ExceptionHelper.checkNotNullArgument(task, "task"); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { TaskExecutor executor = SyncTaskExecutor.getSimpleExecutor(); executor.execute(cancelToken, task, cleanupTask); } }); } } private enum EagerExecutor implements TaskExecutor { INSTANCE; @Override public void execute( CancellationToken cancelToken, CancelableTask task, CleanupTask cleanupTask) { ExceptionHelper.checkNotNullArgument(cancelToken, "cancelToken"); ExceptionHelper.checkNotNullArgument(task, "task"); if (SwingUtilities.isEventDispatchThread()) { TaskExecutor executor = SyncTaskExecutor.getSimpleExecutor(); executor.execute(cancelToken, task, cleanupTask); } else { LazyExecutor.INSTANCE.execute(cancelToken, task, cleanupTask); } } } private static class StrictEagerExecutor implements TaskExecutor { // We assume that there are always less than Integer.MAX_VALUE // concurrent tasks. // Having more than this would surely make the application unusable // anyway (since these tasks run on the single Event Dispatch Thread, // this would make it more outrageous). private final AtomicInteger currentlyExecuting = new AtomicInteger(0); @Override public void execute( final CancellationToken cancelToken, final CancelableTask task, final CleanupTask cleanupTask) { ExceptionHelper.checkNotNullArgument(cancelToken, "cancelToken"); ExceptionHelper.checkNotNullArgument(task, "task"); boolean canInvokeNow = currentlyExecuting.get() == 0; // Tasks that are scheduled concurrently this call, // does not matter if they run after this task. // This executor only guarantees that A task happens before // B task, if scheduling A happens before scheduling B // (which implies that they does not run concurrently). if (canInvokeNow && SwingUtilities.isEventDispatchThread()) { TaskExecutor executor = SyncTaskExecutor.getSimpleExecutor(); executor.execute(cancelToken, task, cleanupTask); } else { currentlyExecuting.incrementAndGet(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { try { TaskExecutor executor = SyncTaskExecutor.getSimpleExecutor(); executor.execute(cancelToken, task, cleanupTask); } finally { currentlyExecuting.decrementAndGet(); } } }); } } } /** * Creates a new {@code SwingTaskExecutor} which will execute submitted * tasks on the <I>AWT Event Dispatch Thread</I>. * <P> * This constructor is equivalent to calling * {@code SwingTaskExecutor(true)}. */ public SwingTaskExecutor() { this(true); } /** * Creates a new {@code SwingTaskExecutor} which will execute submitted * tasks on the <I>AWT Event Dispatch Thread</I>. * * @param alwaysInvokeLater if this argument is {@code true}, submitted * tasks are never executed synchronously on the calling thread (i.e.: * they are always submitted as {@code SwingUtilities.invokeLater} does * it). In case this argument is {@code false}, tasks submitted from the * <I>AWT Event Dispatch Thread</I> will be executed immediately on the * calling thread. */ public SwingTaskExecutor(boolean alwaysInvokeLater) { super(TaskExecutors.upgradeExecutor(getStrictExecutor(alwaysInvokeLater))); } private static void checkWaitOnEDT() { if (SwingUtilities.isEventDispatchThread()) { // Waiting on the EDT would be a good way to cause a dead-lock. throw new IllegalStateException("Cannot wait for termination on the Event Dispatch Thread."); } } /** * {@inheritDoc } * <P> * This method may not be called from the <I>AWT Event Dispatch Thread</I>. * This is forbidden because it is very dead-lock prone: If a task was * submitted to this executor, it could not complete because this method * prevents any task to be executed on the EDT. * * @throws IllegalStateException thrown if the current calling thread is the * <I>AWT Event Dispatch Thread</I> */ @Override public void awaitTermination(CancellationToken cancelToken) { checkWaitOnEDT(); wrappedExecutor.awaitTermination(cancelToken); } /** * {@inheritDoc } * <P> * This method may not be called from the <I>AWT Event Dispatch Thread</I>. * This is forbidden because it is very dead-lock prone: If a task was * submitted to this executor, it could not complete because this method * prevents any task to be executed on the EDT. * * @throws IllegalStateException thrown if the current calling thread is the * <I>AWT Event Dispatch Thread</I> */ @Override public boolean awaitTermination(CancellationToken cancelToken, long timeout, TimeUnit unit) { checkWaitOnEDT(); return wrappedExecutor.awaitTermination(cancelToken, timeout, unit); } }
Adjusted the apidoc of SwingTaskExecutor
jtrim-gui/src/main/java/org/jtrim/swing/concurrent/SwingTaskExecutor.java
Adjusted the apidoc of SwingTaskExecutor
<ide><path>trim-gui/src/main/java/org/jtrim/swing/concurrent/SwingTaskExecutor.java <ide> * they are always submitted as {@code SwingUtilities.invokeLater} does <ide> * it). In case this argument is {@code false}, tasks submitted from the <ide> * <I>AWT Event Dispatch Thread</I> will be executed immediately on the <del> * calling thread. <add> * calling thread (this may not always possible to execute tasks in the <add> * order they were submitted). <ide> */ <ide> public SwingTaskExecutor(boolean alwaysInvokeLater) { <ide> super(TaskExecutors.upgradeExecutor(getStrictExecutor(alwaysInvokeLater)));
Java
apache-2.0
a8b26e8eec6dc64484575b2edf5df54839cb98fc
0
tristantarrant/JGroups,danberindei/JGroups,vjuranek/JGroups,ibrahimshbat/JGroups,rpelisse/JGroups,ibrahimshbat/JGroups,pruivo/JGroups,TarantulaTechnology/JGroups,deepnarsay/JGroups,danberindei/JGroups,kedzie/JGroups,vjuranek/JGroups,pferraro/JGroups,belaban/JGroups,belaban/JGroups,ligzy/JGroups,slaskawi/JGroups,pruivo/JGroups,slaskawi/JGroups,tristantarrant/JGroups,rhusar/JGroups,TarantulaTechnology/JGroups,pferraro/JGroups,Sanne/JGroups,pferraro/JGroups,ligzy/JGroups,ibrahimshbat/JGroups,vjuranek/JGroups,ligzy/JGroups,danberindei/JGroups,TarantulaTechnology/JGroups,kedzie/JGroups,belaban/JGroups,rvansa/JGroups,Sanne/JGroups,dimbleby/JGroups,ibrahimshbat/JGroups,deepnarsay/JGroups,rhusar/JGroups,rvansa/JGroups,slaskawi/JGroups,dimbleby/JGroups,kedzie/JGroups,Sanne/JGroups,rpelisse/JGroups,rhusar/JGroups,rpelisse/JGroups,pruivo/JGroups,deepnarsay/JGroups,dimbleby/JGroups
package org.jgroups.stack; import org.jgroups.Event; import org.jgroups.Global; import org.jgroups.annotations.DeprecatedProperty; import org.jgroups.annotations.LocalAddress; import org.jgroups.annotations.Property; import org.jgroups.conf.PropertyHelper; import org.jgroups.conf.ProtocolConfiguration; import org.jgroups.logging.Log; import org.jgroups.logging.LogFactory; import org.jgroups.protocols.TP; import org.jgroups.util.StackType; import org.jgroups.util.Tuple; import org.jgroups.util.Util; import java.io.IOException; import java.io.PushbackReader; import java.io.Reader; import java.io.StringReader; import java.lang.reflect.*; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.*; import java.util.concurrent.ConcurrentMap; /** * The task if this class is to setup and configure the protocol stack. A string describing * the desired setup, which is both the layering and the configuration of each layer, is * given to the configurator which creates and configures the protocol stack and returns * a reference to the top layer (Protocol).<p> * Future functionality will include the capability to dynamically modify the layering * of the protocol stack and the properties of each layer. * @author Bela Ban * @author Richard Achmatowicz */ public class Configurator { protected static final Log log=LogFactory.getLog(Configurator.class); private final ProtocolStack stack; public Configurator() { stack=null; } public Configurator(ProtocolStack protocolStack) { stack=protocolStack; } public Protocol setupProtocolStack(List<ProtocolConfiguration> config) throws Exception{ return setupProtocolStack(config, stack); } public Protocol setupProtocolStack(ProtocolStack copySource)throws Exception{ List<Protocol> protocols=copySource.copyProtocols(stack); Collections.reverse(protocols); return connectProtocols(protocols); } /** * The configuration string has a number of entries, separated by a ':' (colon). * Each entry consists of the name of the protocol, followed by an optional configuration * of that protocol. The configuration is enclosed in parentheses, and contains entries * which are name/value pairs connected with an assignment sign (=) and separated by * a semicolon. * <pre>UDP(in_port=5555;out_port=4445):FRAG(frag_size=1024)</pre><p> * The <em>first</em> entry defines the <em>bottommost</em> layer, the string is parsed * left to right and the protocol stack constructed bottom up. Example: the string * "UDP(in_port=5555):FRAG(frag_size=32000):DEBUG" results is the following stack:<pre> * * ----------------------- * | DEBUG | * |-----------------------| * | FRAG frag_size=32000 | * |-----------------------| * | UDP in_port=32000 | * ----------------------- * </pre> */ private static Protocol setupProtocolStack(List<ProtocolConfiguration> protocol_configs, ProtocolStack st) throws Exception { List<Protocol> protocols=createProtocols(protocol_configs, st); if(protocols == null) return null; // check InetAddress related features of stack Map<String, Map<String,InetAddressInfo>> inetAddressMap = createInetAddressMap(protocol_configs, protocols) ; Collection<InetAddress> addrs=getAddresses(inetAddressMap); StackType ip_version=Util.getIpStackType(); // 0 = n/a, 4 = IPv4, 6 = IPv6 if(!addrs.isEmpty()) { // check that all user-supplied InetAddresses have a consistent version: // 1. If an addr is IPv6 and we have an IPv4 stack --> FAIL // 2. If an address is an IPv4 class D (multicast) address and the stack is IPv6: FAIL // Else pass for(InetAddress addr: addrs) { if(addr instanceof Inet6Address && ip_version == StackType.IPv4) throw new IllegalArgumentException("found IPv6 address " + addr + " in an IPv4 stack"); if(addr instanceof Inet4Address && addr.isMulticastAddress() && ip_version == StackType.IPv6) throw new Exception("found IPv4 multicast address " + addr + " in an IPv6 stack"); } } // process default values setDefaultValues(protocol_configs, protocols, ip_version); ensureValidBindAddresses(protocols); return connectProtocols(protocols); } public static void setDefaultValues(List<Protocol> protocols) throws Exception { if(protocols == null) return; // check InetAddress related features of stack Collection<InetAddress> addrs=getInetAddresses(protocols); StackType ip_version=Util.getIpStackType(); // 0 = n/a, 4 = IPv4, 6 = IPv6 if(!addrs.isEmpty()) { // check that all user-supplied InetAddresses have a consistent version: // 1. If an addr is IPv6 and we have an IPv4 stack --> FAIL // 2. If an address is an IPv4 class D (multicast) address and the stack is IPv6: FAIL // Else pass for(InetAddress addr : addrs) { if(addr instanceof Inet6Address && ip_version == StackType.IPv4) throw new IllegalArgumentException("found IPv6 address " + addr + " in an IPv4 stack"); if(addr instanceof Inet4Address && addr.isMulticastAddress() && ip_version == StackType.IPv6) throw new Exception("found IPv4 multicast address " + addr + " in an IPv6 stack"); } } // process default values setDefaultValues(protocols, ip_version); } /** * Creates a new protocol given the protocol specification. Initializes the properties and starts the * up and down handler threads. * @param prot_spec The specification of the protocol. Same convention as for specifying a protocol stack. * An exception will be thrown if the class cannot be created. Example: * <pre>"VERIFY_SUSPECT(timeout=1500)"</pre> Note that no colons (:) have to be * specified * @param stack The protocol stack * @return Protocol The newly created protocol * @exception Exception Will be thrown when the new protocol cannot be created */ public static Protocol createProtocol(String prot_spec, ProtocolStack stack) throws Exception { ProtocolConfiguration config; Protocol prot; if(prot_spec == null) throw new Exception("Configurator.createProtocol(): prot_spec is null"); // parse the configuration for this protocol config=new ProtocolConfiguration(prot_spec); // create an instance of the protocol class and configure it prot=createLayer(stack, config); prot.init(); return prot; } /* ------------------------------- Private Methods ------------------------------------- */ /** * Creates a protocol stack by iterating through the protocol list and connecting * adjacent layers. The list starts with the topmost layer and has the bottommost * layer at the tail. * @param protocol_list List of Protocol elements (from top to bottom) * @return Protocol stack */ public static Protocol connectProtocols(List<Protocol> protocol_list) throws Exception { Protocol current_layer=null, next_layer=null; for(int i=0; i < protocol_list.size(); i++) { current_layer=protocol_list.get(i); if(i + 1 >= protocol_list.size()) break; next_layer=protocol_list.get(i + 1); next_layer.setDownProtocol(current_layer); current_layer.setUpProtocol(next_layer); if(current_layer instanceof TP) { TP transport = (TP)current_layer; if(transport.isSingleton()) { ConcurrentMap<String, Protocol> up_prots=transport.getUpProtocols(); String key; synchronized(up_prots) { while(true) { key=Global.DUMMY + System.currentTimeMillis(); if(up_prots.containsKey(key)) continue; up_prots.put(key, next_layer); break; } } current_layer.setUpProtocol(null); } } } // basic protocol sanity check sanityCheck(protocol_list); return current_layer; } /** * Get a string of the form "P1(config_str1):P2:P3(config_str3)" and return * ProtocolConfigurations for it. That means, parse "P1(config_str1)", "P2" and * "P3(config_str3)" * @param config_str Configuration string * @return Vector of strings */ private static List<String> parseProtocols(String config_str) throws IOException { List<String> retval=new LinkedList<String>(); PushbackReader reader=new PushbackReader(new StringReader(config_str)); int ch; StringBuilder sb; boolean running=true; while(running) { String protocol_name=readWord(reader); sb=new StringBuilder(); sb.append(protocol_name); ch=read(reader); if(ch == -1) { retval.add(sb.toString()); break; } if(ch == ':') { // no attrs defined retval.add(sb.toString()); continue; } if(ch == '(') { // more attrs defined reader.unread(ch); String attrs=readUntil(reader, ')'); sb.append(attrs); retval.add(sb.toString()); } else { retval.add(sb.toString()); } while(true) { ch=read(reader); if(ch == ':') { break; } if(ch == -1) { running=false; break; } } } reader.close(); return retval; } private static int read(Reader reader) throws IOException { int ch=-1; while((ch=reader.read()) != -1) { if(!Character.isWhitespace(ch)) return ch; } return ch; } /** * Return a number of ProtocolConfigurations in a vector * @param configuration protocol-stack configuration string * @return List of ProtocolConfigurations */ public static List<ProtocolConfiguration> parseConfigurations(String configuration) throws Exception { List<ProtocolConfiguration> retval=new ArrayList<ProtocolConfiguration>(); List<String> protocol_string=parseProtocols(configuration); if(protocol_string == null) return null; for(String component_string: protocol_string) { retval.add(new ProtocolConfiguration(component_string)); } return retval; } public static String printConfigurations(Collection<ProtocolConfiguration> configs) { StringBuilder sb=new StringBuilder(); boolean first=true; for(ProtocolConfiguration config: configs) { if(first) first=false; else sb.append(":"); sb.append(config.getProtocolName()); if(!config.getProperties().isEmpty()) { sb.append('(').append(config.propertiesToString()).append(')'); } } return sb.toString(); } private static String readUntil(Reader reader, char c) throws IOException { StringBuilder sb=new StringBuilder(); int ch; while((ch=read(reader)) != -1) { sb.append((char)ch); if(ch == c) break; } return sb.toString(); } private static String readWord(PushbackReader reader) throws IOException { StringBuilder sb=new StringBuilder(); int ch; while((ch=read(reader)) != -1) { if(Character.isLetterOrDigit(ch) || ch == '_' || ch == '.' || ch == '$') { sb.append((char)ch); } else { reader.unread(ch); break; } } return sb.toString(); } /** * Takes vector of ProtocolConfigurations, iterates through it, creates Protocol for * each ProtocolConfiguration and returns all Protocols in a vector. * @param protocol_configs Vector of ProtocolConfigurations * @param stack The protocol stack * @return List of Protocols */ private static List<Protocol> createProtocols(List<ProtocolConfiguration> protocol_configs, final ProtocolStack stack) throws Exception { List<Protocol> retval=new LinkedList<Protocol>(); ProtocolConfiguration protocol_config; Protocol layer; String singleton_name; for(int i=0; i < protocol_configs.size(); i++) { protocol_config=protocol_configs.get(i); singleton_name=protocol_config.getProperties().get(Global.SINGLETON_NAME); if(singleton_name != null && singleton_name.trim().length() > 0) { Map<String,Tuple<TP, ProtocolStack.RefCounter>> singleton_transports=ProtocolStack.getSingletonTransports(); synchronized(singleton_transports) { if(i > 0) { // crude way to check whether protocol is a transport throw new IllegalArgumentException("Property 'singleton_name' can only be used in a transport" + " protocol (was used in " + protocol_config.getProtocolName() + ")"); } Tuple<TP, ProtocolStack.RefCounter> val=singleton_transports.get(singleton_name); layer=val != null? val.getVal1() : null; if(layer != null) { retval.add(layer); } else { layer=createLayer(stack, protocol_config); if(layer == null) return null; singleton_transports.put(singleton_name, new Tuple<TP, ProtocolStack.RefCounter>((TP)layer,new ProtocolStack.RefCounter((short)0,(short)0))); retval.add(layer); } } continue; } layer=createLayer(stack, protocol_config); if(layer == null) return null; retval.add(layer); } return retval; } protected static Protocol createLayer(ProtocolStack stack, ProtocolConfiguration config) throws Exception { String protocol_name=config.getProtocolName(); Map<String, String> properties=config.getProperties(); Protocol retval=null; if(protocol_name == null || properties == null) return null; String defaultProtocolName=ProtocolConfiguration.protocol_prefix + '.' + protocol_name; Class<?> clazz=null; try { clazz=Util.loadClass(defaultProtocolName, stack.getClass()); } catch(ClassNotFoundException e) { } if(clazz == null) { try { clazz=Util.loadClass(protocol_name, stack.getClass()); } catch(ClassNotFoundException e) { } if(clazz == null) { throw new Exception("unable to load class for protocol " + protocol_name + " (either as an absolute - " + protocol_name + " - or relative - " + defaultProtocolName + " - package name)!"); } } try { retval=(Protocol)clazz.newInstance(); if(retval == null) throw new Exception("creation of instance for protocol " + protocol_name + "failed !"); retval.setProtocolStack(stack); removeDeprecatedProperties(retval, properties); // before processing Field and Method based properties, take dependencies specified // with @Property.dependsUpon into account AccessibleObject[] dependencyOrderedFieldsAndMethods = computePropertyDependencies(retval, properties) ; for(AccessibleObject ordered: dependencyOrderedFieldsAndMethods) { if (ordered instanceof Field) { resolveAndAssignField(retval, (Field)ordered, properties) ; } else if (ordered instanceof Method) { resolveAndInvokePropertyMethod(retval, (Method)ordered, properties) ; } } List<Object> additional_objects=retval.getConfigurableObjects(); if(additional_objects != null && !additional_objects.isEmpty()) { for(Object obj: additional_objects) { resolveAndAssignFields(obj, properties); resolveAndInvokePropertyMethods(obj, properties); } } if(!properties.isEmpty()) { throw new IllegalArgumentException("the following properties in " + protocol_name + " are not recognized: " + properties); } } catch(InstantiationException inst_ex) { log.error("an instance of " + protocol_name + " could not be created. Please check that it implements" + " interface Protocol and that is has a public empty constructor !"); throw inst_ex; } return retval; } /** Throws an exception if sanity check fails. Possible sanity check is uniqueness of all protocol names */ public static void sanityCheck(List<Protocol> protocols) throws Exception { // check for unique IDs Set<Short> ids=new HashSet<Short>(); for(Protocol protocol: protocols) { short id=protocol.getId(); if(id > 0 && ids.add(id) == false) throw new Exception("Protocol ID " + id + " (name=" + protocol.getName() + ") is duplicate; protocol IDs have to be unique"); } // For each protocol, get its required up and down services and check (if available) if they're satisfied for(Protocol protocol: protocols) { List<Integer> required_down_services=protocol.requiredDownServices(); List<Integer> required_up_services=protocol.requiredUpServices(); if(required_down_services != null && !required_down_services.isEmpty()) { // the protocols below 'protocol' have to provide the services listed in required_down_services List<Integer> tmp=new ArrayList<Integer>(required_down_services); removeProvidedUpServices(protocol, tmp); if(!tmp.isEmpty()) throw new Exception("events " + printEvents(tmp) + " are required by " + protocol.getName() + ", but not provided by any of the protocols below it"); } if(required_up_services != null && !required_up_services.isEmpty()) { // the protocols above 'protocol' have to provide the services listed in required_up_services List<Integer> tmp=new ArrayList<Integer>(required_up_services); removeProvidedDownServices(protocol, tmp); if(!tmp.isEmpty()) throw new Exception("events " + printEvents(tmp) + " are required by " + protocol.getName() + ", but not provided by any of the protocols above it"); } } } protected static String printEvents(List<Integer> events) { StringBuilder sb=new StringBuilder("["); for(int evt: events) sb.append(Event.type2String(evt)).append(" "); sb.append("]"); return sb.toString(); } /** * Removes all events provided by the protocol below protocol from events * @param protocol * @param events */ protected static void removeProvidedUpServices(Protocol protocol, List<Integer> events) { if(protocol == null || events == null) return; for(Protocol prot=protocol.getDownProtocol(); prot != null && !events.isEmpty(); prot=prot.getDownProtocol()) { List<Integer> provided_up_services=prot.providedUpServices(); if(provided_up_services != null && !provided_up_services.isEmpty()) events.removeAll(provided_up_services); } } /** * Removes all events provided by the protocol above protocol from events * @param protocol * @param events */ protected static void removeProvidedDownServices(Protocol protocol, List<Integer> events) { if(protocol == null || events == null) return; for(Protocol prot=protocol.getUpProtocol(); prot != null && !events.isEmpty(); prot=prot.getUpProtocol()) { List<Integer> provided_down_services=prot.providedDownServices(); if(provided_down_services != null && !provided_down_services.isEmpty()) events.removeAll(provided_down_services); } } /** * Returns all inet addresses found */ public static Collection<InetAddress> getAddresses(Map<String, Map<String, InetAddressInfo>> inetAddressMap) throws Exception { Set<InetAddress> addrs=new HashSet<InetAddress>(); for(Map.Entry<String, Map<String, InetAddressInfo>> inetAddressMapEntry : inetAddressMap.entrySet()) { Map<String, InetAddressInfo> protocolInetAddressMap=inetAddressMapEntry.getValue(); for(Map.Entry<String, InetAddressInfo> protocolInetAddressMapEntry : protocolInetAddressMap.entrySet()) { InetAddressInfo inetAddressInfo=protocolInetAddressMapEntry.getValue(); // add InetAddressInfo to sets based on IP version List<InetAddress> addresses=inetAddressInfo.getInetAddresses(); for(InetAddress address : addresses) { if(address == null) throw new RuntimeException("failed converting address info to IP address: " + inetAddressInfo); addrs.add(address); } } } return addrs; } /** * This method takes a set of InetAddresses, represented by an inetAddressmap, and: * - if the resulting set is non-empty, goes through to see if all InetAddress-related * user settings have a consistent IP version: v4 or v6, and throws an exception if not * - if the resulting set is empty, sets the default IP version based on available stacks * and if a dual stack, stack preferences * - sets the IP version to be used in the JGroups session * @return StackType.IPv4 for IPv4, StackType.IPv6 for IPv6, StackType.Unknown if the version cannot be determined */ public static StackType determineIpVersionFromAddresses(Collection<InetAddress> addrs) throws Exception { Set<InetAddress> ipv4_addrs= new HashSet<InetAddress>() ; Set<InetAddress> ipv6_addrs= new HashSet<InetAddress>() ; for(InetAddress address: addrs) { if (address instanceof Inet4Address) ipv4_addrs.add(address) ; else ipv6_addrs.add(address) ; } if(log.isTraceEnabled()) log.trace("all addrs=" + addrs + ", IPv4 addrs=" + ipv4_addrs + ", IPv6 addrs=" + ipv6_addrs); // the user supplied 1 or more IP address inputs. Check if we have a consistent set if (!addrs.isEmpty()) { if (!ipv4_addrs.isEmpty() && !ipv6_addrs.isEmpty()) { throw new RuntimeException("all addresses have to be either IPv4 or IPv6: IPv4 addresses=" + ipv4_addrs + ", IPv6 addresses=" + ipv6_addrs); } return !ipv6_addrs.isEmpty()? StackType.IPv6 : StackType.IPv4; } return StackType.Unknown; } /* * A method which does the following: * - discovers all Fields or Methods within the protocol stack which set * InetAddress, IpAddress, InetSocketAddress (and Lists of such) for which the user *has* * specified a default value. * - stores the resulting set of Fields and Methods in a map of the form: * Protocol -> Property -> InetAddressInfo * where InetAddressInfo instances encapsulate the InetAddress related information * of the Fields and Methods. */ public static Map<String, Map<String,InetAddressInfo>> createInetAddressMap(List<ProtocolConfiguration> protocol_configs, List<Protocol> protocols) throws Exception { // Map protocol -> Map<String, InetAddressInfo>, where the latter is protocol specific Map<String, Map<String,InetAddressInfo>> inetAddressMap = new HashMap<String, Map<String, InetAddressInfo>>() ; // collect InetAddressInfo for (int i = 0; i < protocol_configs.size(); i++) { ProtocolConfiguration protocol_config = protocol_configs.get(i) ; Protocol protocol = protocols.get(i) ; String protocolName = protocol.getName(); // regenerate the Properties which were destroyed during basic property processing Map<String,String> properties = protocol_config.getOriginalProperties(); // check which InetAddress-related properties are ***non-null ***, and // create an InetAddressInfo structure for them // Method[] methods=protocol.getClass().getMethods(); Method[] methods=Util.getAllDeclaredMethodsWithAnnotations(protocol.getClass(), Property.class); for(int j = 0; j < methods.length; j++) { if (methods[j].isAnnotationPresent(Property.class) && isSetPropertyMethod(methods[j])) { String propertyName = PropertyHelper.getPropertyName(methods[j]) ; String propertyValue = properties.get(propertyName); // if there is a systemProperty attribute defined in the annotation, set the property value from the system property String tmp=grabSystemProp(methods[j].getAnnotation(Property.class)); if(tmp != null) propertyValue=tmp; if (propertyValue != null && InetAddressInfo.isInetAddressRelated(methods[j])) { Object converted = null ; try { converted=PropertyHelper.getConvertedValue(protocol, methods[j], properties, propertyValue, false); } catch(Exception e) { throw new Exception("String value could not be converted for method " + propertyName + " in " + protocolName + " with default value " + propertyValue + ".Exception is " +e, e); } InetAddressInfo inetinfo = new InetAddressInfo(protocol, methods[j], properties, propertyValue, converted) ; Map<String, InetAddressInfo> protocolInetAddressMap=inetAddressMap.get(protocolName); if(protocolInetAddressMap == null) { protocolInetAddressMap = new HashMap<String,InetAddressInfo>() ; inetAddressMap.put(protocolName, protocolInetAddressMap) ; } protocolInetAddressMap.put(propertyName, inetinfo) ; } } } //traverse class hierarchy and find all annotated fields and add them to the list if annotated for(Class<?> clazz=protocol.getClass(); clazz != null; clazz=clazz.getSuperclass()) { Field[] fields=clazz.getDeclaredFields(); for(int j = 0; j < fields.length; j++ ) { if (fields[j].isAnnotationPresent(Property.class)) { String propertyName = PropertyHelper.getPropertyName(fields[j], properties) ; String propertyValue = properties.get(propertyName) ; // if there is a systemProperty attribute defined in the annotation, set the property value from the system property String tmp=grabSystemProp(fields[j].getAnnotation(Property.class)); if(tmp != null) propertyValue=tmp; if ((propertyValue != null || !PropertyHelper.usesDefaultConverter(fields[j])) && InetAddressInfo.isInetAddressRelated(protocol, fields[j])) { Object converted = null ; try { converted=PropertyHelper.getConvertedValue(protocol, fields[j], properties, propertyValue, false); } catch(Exception e) { throw new Exception("String value could not be converted for method " + propertyName + " in " + protocolName + " with default value " + propertyValue + ".Exception is " +e, e); } InetAddressInfo inetinfo = new InetAddressInfo(protocol, fields[j], properties, propertyValue, converted) ; Map<String, InetAddressInfo> protocolInetAddressMap=inetAddressMap.get(protocolName); if(protocolInetAddressMap == null) { protocolInetAddressMap = new HashMap<String,InetAddressInfo>() ; inetAddressMap.put(protocolName, protocolInetAddressMap) ; } protocolInetAddressMap.put(propertyName, inetinfo) ; }// recompute } } } } return inetAddressMap ; } public static List<InetAddress> getInetAddresses(List<Protocol> protocols) throws Exception { List<InetAddress> retval=new LinkedList<InetAddress>(); // collect InetAddressInfo for(Protocol protocol : protocols) { String protocolName=protocol.getName(); //traverse class hierarchy and find all annotated fields and add them to the list if annotated for(Class<?> clazz=protocol.getClass(); clazz != null; clazz=clazz.getSuperclass()) { Field[] fields=clazz.getDeclaredFields(); for(int j=0; j < fields.length; j++) { if(fields[j].isAnnotationPresent(Property.class)) { if(InetAddressInfo.isInetAddressRelated(protocol, fields[j])) { Object value=getValueFromProtocol(protocol, fields[j]); if(value instanceof InetAddress) retval.add((InetAddress)value); else if(value instanceof IpAddress) retval.add(((IpAddress)value).getIpAddress()); else if(value instanceof InetSocketAddress) retval.add(((InetSocketAddress)value).getAddress()); } } } } } return retval; } /* * Method which processes @Property.default() values, associated with the annotation * using the defaultValue= attribute. This method does the following: * - locate all properties which have no user value assigned * - if the defaultValue attribute is not "", generate a value for the field using the * property converter for that property and assign it to the field */ public static void setDefaultValues(List<ProtocolConfiguration> protocol_configs, List<Protocol> protocols, StackType ip_version) throws Exception { InetAddress default_ip_address=Util.getNonLoopbackAddress(); if(default_ip_address == null) { log.warn("unable to find an address other than loopback for IP version " + ip_version); default_ip_address=Util.getLocalhost(ip_version); } for(int i=0; i < protocol_configs.size(); i++) { ProtocolConfiguration protocol_config=protocol_configs.get(i); Protocol protocol=protocols.get(i); String protocolName=protocol.getName(); // regenerate the Properties which were destroyed during basic property processing Map<String,String> properties=protocol_config.getOriginalProperties(); Method[] methods=Util.getAllDeclaredMethodsWithAnnotations(protocol.getClass(), Property.class); for(int j=0; j < methods.length; j++) { if(isSetPropertyMethod(methods[j])) { String propertyName=PropertyHelper.getPropertyName(methods[j]); Object propertyValue=getValueFromProtocol(protocol, propertyName); if(propertyValue == null) { // if propertyValue is null, check if there is a we can use Property annotation=methods[j].getAnnotation(Property.class); // get the default value for the method- check for InetAddress types String defaultValue=null; if(InetAddressInfo.isInetAddressRelated(methods[j])) { defaultValue=ip_version == StackType.IPv4? annotation.defaultValueIPv4() : annotation.defaultValueIPv6(); if(defaultValue != null && defaultValue.length() > 0) { Object converted=null; try { if(defaultValue.equalsIgnoreCase(Global.NON_LOOPBACK_ADDRESS)) converted=default_ip_address; else converted=PropertyHelper.getConvertedValue(protocol, methods[j], properties, defaultValue, true); methods[j].invoke(protocol, converted); } catch(Exception e) { throw new Exception("default could not be assigned for method " + propertyName + " in " + protocolName + " with default " + defaultValue, e); } if(log.isDebugEnabled()) log.debug("set property " + protocolName + "." + propertyName + " to default value " + converted); } } } } } //traverse class hierarchy and find all annotated fields and add them to the list if annotated Field[] fields=Util.getAllDeclaredFieldsWithAnnotations(protocol.getClass(), Property.class); for(int j=0; j < fields.length; j++) { String propertyName=PropertyHelper.getPropertyName(fields[j], properties); Object propertyValue=getValueFromProtocol(protocol, fields[j]); if(propertyValue == null) { // add to collection of @Properties with no user specified value Property annotation=fields[j].getAnnotation(Property.class); // get the default value for the field - check for InetAddress types String defaultValue=null; if(InetAddressInfo.isInetAddressRelated(protocol, fields[j])) { defaultValue=ip_version == StackType.IPv4? annotation.defaultValueIPv4() : annotation.defaultValueIPv6(); if(defaultValue != null && defaultValue.length() > 0) { // condition for invoking converter if(defaultValue != null || !PropertyHelper.usesDefaultConverter(fields[j])) { Object converted=null; try { if(defaultValue.equalsIgnoreCase(Global.NON_LOOPBACK_ADDRESS)) converted=default_ip_address; else converted=PropertyHelper.getConvertedValue(protocol, fields[j], properties, defaultValue, true); if(converted != null) setField(fields[j], protocol, converted); } catch(Exception e) { throw new Exception("default could not be assigned for field " + propertyName + " in " + protocolName + " with default value " + defaultValue, e); } if(log.isDebugEnabled()) log.debug("set property " + protocolName + "." + propertyName + " to default value " + converted); } } } } } } } public static void setDefaultValues(List<Protocol> protocols, StackType ip_version) throws Exception { InetAddress default_ip_address=Util.getNonLoopbackAddress(); if(default_ip_address == null) { log.warn("unable to find an address other than loopback for IP version " + ip_version); default_ip_address=Util.getLocalhost(ip_version); } for(Protocol protocol : protocols) { String protocolName=protocol.getName(); //traverse class hierarchy and find all annotated fields and add them to the list if annotated Field[] fields=Util.getAllDeclaredFieldsWithAnnotations(protocol.getClass(), Property.class); for(int j=0; j < fields.length; j++) { // get the default value for the field - check for InetAddress types if(InetAddressInfo.isInetAddressRelated(protocol, fields[j])) { Object propertyValue=getValueFromProtocol(protocol, fields[j]); if(propertyValue == null) { // add to collection of @Properties with no user specified value Property annotation=fields[j].getAnnotation(Property.class); String defaultValue=ip_version == StackType.IPv4? annotation.defaultValueIPv4() : annotation.defaultValueIPv6(); if(defaultValue != null && defaultValue.length() > 0) { // condition for invoking converter Object converted=null; try { if(defaultValue.equalsIgnoreCase(Global.NON_LOOPBACK_ADDRESS)) converted=default_ip_address; else converted=PropertyHelper.getConvertedValue(protocol, fields[j], defaultValue, true); if(converted != null) setField(fields[j], protocol, converted); } catch(Exception e) { throw new Exception("default could not be assigned for field " + fields[j].getName() + " in " + protocolName + " with default value " + defaultValue, e); } if(log.isDebugEnabled()) log.debug("set property " + protocolName + "." + fields[j].getName() + " to default value " + converted); } } } } } } /** * Makes sure that all fields annotated with @LocalAddress is (1) an InetAddress and (2) a valid address on any * local network interface * @param protocols * @throws Exception */ public static void ensureValidBindAddresses(List<Protocol> protocols) throws Exception { for(Protocol protocol : protocols) { String protocolName=protocol.getName(); //traverse class hierarchy and find all annotated fields and add them to the list if annotated Field[] fields=Util.getAllDeclaredFieldsWithAnnotations(protocol.getClass(), LocalAddress.class); for(int i=0; i < fields.length; i++) { Object val=getValueFromProtocol(protocol, fields[i]); if(!(val instanceof InetAddress)) throw new Exception("field " + protocolName + "." + fields[i].getName() + " is not an InetAddress"); Util.checkIfValidAddress((InetAddress)val, protocolName); } } } public static Object getValueFromProtocol(Protocol protocol, Field field) throws IllegalAccessException { if(protocol == null || field == null) return null; if(!Modifier.isPublic(field.getModifiers())) field.setAccessible(true); return field.get(protocol); } public static Object getValueFromProtocol(Protocol protocol, String field_name) throws IllegalAccessException { if(protocol == null || field_name == null) return null; Field field=Util.getField(protocol.getClass(), field_name); return field != null? getValueFromProtocol(protocol, field) : null; } /** * This method creates a list of all properties (Field or Method) in dependency order, * where dependencies are specified using the dependsUpon specifier of the Property annotation. * In particular, it does the following: * (i) creates a master list of properties * (ii) checks that all dependency references are present * (iii) creates a copy of the master list in dependency order */ static AccessibleObject[] computePropertyDependencies(Object obj, Map<String,String> properties) { // List of Fields and Methods of the protocol annotated with @Property List<AccessibleObject> unorderedFieldsAndMethods = new LinkedList<AccessibleObject>() ; List<AccessibleObject> orderedFieldsAndMethods = new LinkedList<AccessibleObject>() ; // Maps property name to property object Map<String, AccessibleObject> propertiesInventory = new HashMap<String, AccessibleObject>() ; // get the methods for this class and add them to the list if annotated with @Property Method[] methods=obj.getClass().getMethods(); for(int i = 0; i < methods.length; i++) { if (methods[i].isAnnotationPresent(Property.class) && isSetPropertyMethod(methods[i])) { String propertyName = PropertyHelper.getPropertyName(methods[i]) ; unorderedFieldsAndMethods.add(methods[i]) ; propertiesInventory.put(propertyName, methods[i]) ; } } //traverse class hierarchy and find all annotated fields and add them to the list if annotated for(Class<?> clazz=obj.getClass(); clazz != null; clazz=clazz.getSuperclass()) { Field[] fields=clazz.getDeclaredFields(); for(int i = 0; i < fields.length; i++ ) { if (fields[i].isAnnotationPresent(Property.class)) { String propertyName = PropertyHelper.getPropertyName(fields[i], properties) ; unorderedFieldsAndMethods.add(fields[i]) ; // may need to change this based on name parameter of Property propertiesInventory.put(propertyName, fields[i]) ; } } } // at this stage, we have all Fields and Methods annotated with @Property checkDependencyReferencesPresent(unorderedFieldsAndMethods, propertiesInventory) ; // order the fields and methods by dependency orderedFieldsAndMethods = orderFieldsAndMethodsByDependency(unorderedFieldsAndMethods, propertiesInventory) ; // convert to array of Objects AccessibleObject[] result = new AccessibleObject[orderedFieldsAndMethods.size()] ; for(int i = 0; i < orderedFieldsAndMethods.size(); i++) { result[i] = orderedFieldsAndMethods.get(i) ; } return result ; } static List<AccessibleObject> orderFieldsAndMethodsByDependency(List<AccessibleObject> unorderedList, Map<String, AccessibleObject> propertiesMap) { // Stack to detect cycle in depends relation Stack<AccessibleObject> stack = new Stack<AccessibleObject>() ; // the result list List<AccessibleObject> orderedList = new LinkedList<AccessibleObject>() ; // add the elements from the unordered list to the ordered list // any dependencies will be checked and added first, in recursive manner for(int i = 0; i < unorderedList.size(); i++) { AccessibleObject obj = unorderedList.get(i) ; addPropertyToDependencyList(orderedList, propertiesMap, stack, obj) ; } return orderedList ; } /** * DFS of dependency graph formed by Property annotations and dependsUpon parameter * This is used to create a list of Properties in dependency order */ static void addPropertyToDependencyList(List<AccessibleObject> orderedList, Map<String, AccessibleObject> props, Stack<AccessibleObject> stack, AccessibleObject obj) { if (orderedList.contains(obj)) return ; if (stack.search(obj) > 0) { throw new RuntimeException("Deadlock in @Property dependency processing") ; } // record the fact that we are processing obj stack.push(obj) ; // process dependencies for this object before adding it to the list Property annotation = obj.getAnnotation(Property.class) ; String dependsClause = annotation.dependsUpon() ; StringTokenizer st = new StringTokenizer(dependsClause, ",") ; while (st.hasMoreTokens()) { String token = st.nextToken().trim(); AccessibleObject dep = props.get(token) ; // if null, throw exception addPropertyToDependencyList(orderedList, props, stack, dep) ; } // indicate we're done with processing dependencies stack.pop() ; // we can now add in dependency order orderedList.add(obj) ; } /* * Checks that for every dependency referred, there is a matching property */ static void checkDependencyReferencesPresent(List<AccessibleObject> objects, Map<String, AccessibleObject> props) { // iterate overall properties marked by @Property for(int i = 0; i < objects.size(); i++) { // get the Property annotation AccessibleObject ao = objects.get(i) ; Property annotation = ao.getAnnotation(Property.class) ; if (annotation == null) { throw new IllegalArgumentException("@Property annotation is required for checking dependencies;" + " annotation is missing for Field/Method " + ao.toString()) ; } String dependsClause = annotation.dependsUpon() ; if (dependsClause.trim().length() == 0) continue ; // split dependsUpon specifier into tokens; trim each token; search for token in list StringTokenizer st = new StringTokenizer(dependsClause, ",") ; while (st.hasMoreTokens()) { String token = st.nextToken().trim() ; // check that the string representing a property name is in the list boolean found = false ; Set<String> keyset = props.keySet(); for (Iterator<String> iter = keyset.iterator(); iter.hasNext();) { if (iter.next().equals(token)) { found = true ; break ; } } if (!found) { throw new IllegalArgumentException("@Property annotation " + annotation.name() + " has an unresolved dependsUpon property: " + token) ; } } } } public static void resolveAndInvokePropertyMethods(Object obj, Map<String,String> props) throws Exception { Method[] methods=obj.getClass().getMethods(); for(Method method: methods) { resolveAndInvokePropertyMethod(obj, method, props) ; } } public static void resolveAndInvokePropertyMethod(Object obj, Method method, Map<String,String> props) throws Exception { String methodName=method.getName(); Property annotation=method.getAnnotation(Property.class); if(annotation != null && isSetPropertyMethod(method)) { String propertyName=PropertyHelper.getPropertyName(method) ; String propertyValue=props.get(propertyName); // if there is a systemProperty attribute defined in the annotation, set the property value from the system property String tmp=grabSystemProp(method.getAnnotation(Property.class)); if(tmp != null) propertyValue=tmp; if(propertyName != null && propertyValue != null) { String deprecated_msg=annotation.deprecatedMessage(); if(deprecated_msg != null && deprecated_msg.length() > 0) { log.warn(method.getDeclaringClass().getSimpleName() + "." + methodName + " has been deprecated : " + deprecated_msg); } } if(propertyValue != null) { Object converted=null; try { converted=PropertyHelper.getConvertedValue(obj, method, props, propertyValue, true); method.invoke(obj, converted); } catch(Exception e) { String name=obj instanceof Protocol? ((Protocol)obj).getName() : obj.getClass().getName(); throw new Exception("Could not assign property " + propertyName + " in " + name + ", method is " + methodName + ", converted value is " + converted, e); } } props.remove(propertyName); } } public static void resolveAndAssignFields(Object obj, Map<String,String> props) throws Exception { //traverse class hierarchy and find all annotated fields for(Class<?> clazz=obj.getClass(); clazz != null; clazz=clazz.getSuperclass()) { Field[] fields=clazz.getDeclaredFields(); for(Field field: fields) { resolveAndAssignField(obj, field, props) ; } } } public static void resolveAndAssignField(Object obj, Field field, Map<String,String> props) throws Exception { Property annotation=field.getAnnotation(Property.class); if(annotation != null) { String propertyName = PropertyHelper.getPropertyName(field, props) ; String propertyValue=props.get(propertyName); // if there is a systemProperty attribute defined in the annotation, set the property value from the system property String tmp=grabSystemProp(field.getAnnotation(Property.class)); if(tmp != null) propertyValue=tmp; if(propertyName != null && propertyValue != null) { String deprecated_msg=annotation.deprecatedMessage(); if(deprecated_msg != null && deprecated_msg.length() > 0) { log.warn(field.getDeclaringClass().getSimpleName() + "." + field.getName() + " has been deprecated: " + deprecated_msg); } } if(propertyValue != null || !PropertyHelper.usesDefaultConverter(field)){ Object converted=null; try { converted=PropertyHelper.getConvertedValue(obj, field, props, propertyValue, true); if(converted != null) setField(field, obj, converted); } catch(Exception e) { String name=obj instanceof Protocol? ((Protocol)obj).getName() : obj.getClass().getName(); throw new Exception("Property assignment of " + propertyName + " in " + name + " with original property value " + propertyValue + " and converted to " + converted + " could not be assigned", e); } } props.remove(propertyName); } } public static void removeDeprecatedProperties(Object obj, Map<String,String> props) throws Exception { //traverse class hierarchy and find all deprecated properties for(Class<?> clazz=obj.getClass(); clazz != null; clazz=clazz.getSuperclass()) { if(clazz.isAnnotationPresent(DeprecatedProperty.class)) { DeprecatedProperty declaredAnnotation=clazz.getAnnotation(DeprecatedProperty.class); String[] deprecatedProperties=declaredAnnotation.names(); for(String propertyName : deprecatedProperties) { String propertyValue=props.get(propertyName); if(propertyValue != null) { if(log.isWarnEnabled()) { String name=obj instanceof Protocol? ((Protocol)obj).getName() : obj.getClass().getName(); log.warn(name + " property " + propertyName + " was deprecated and is ignored"); } props.remove(propertyName); } } } } } public static boolean isSetPropertyMethod(Method method) { return (method.getName().startsWith("set") && method.getReturnType() == java.lang.Void.TYPE && method.getParameterTypes().length == 1); } public static void setField(Field field, Object target, Object value) { if(!Modifier.isPublic(field.getModifiers())) { field.setAccessible(true); } try { field.set(target, value); } catch(IllegalAccessException iae) { throw new IllegalArgumentException("Could not set field " + field, iae); } } public static Object getField(Field field, Object target) { if(!Modifier.isPublic(field.getModifiers())) { field.setAccessible(true); } try { return field.get(target); } catch(IllegalAccessException iae) { throw new IllegalArgumentException("Could not get field " + field, iae); } } private static String grabSystemProp(Property annotation) { String[] system_property_names=annotation.systemProperty(); String retval=null; for(String system_property_name: system_property_names) { if(system_property_name != null && system_property_name.length() > 0) { if(system_property_name.equals(Global.BIND_ADDR) || system_property_name.equals(Global.BIND_ADDR_OLD)) if(Util.isBindAddressPropertyIgnored()) continue; try { retval=System.getProperty(system_property_name); if(retval != null) return retval; } catch(SecurityException ex) { log.error("failed getting system property for " + system_property_name, ex); } } } return retval; } /* --------------------------- End of Private Methods ---------------------------------- */ public static class InetAddressInfo { Protocol protocol ; AccessibleObject fieldOrMethod ; Map<String,String> properties ; String propertyName ; String stringValue ; Object convertedValue ; boolean isField ; boolean isParameterized ; // is the associated type parametrized? (e.g. Collection<String>) Object baseType ; // what is the base type (e.g. Collection) InetAddressInfo(Protocol protocol, AccessibleObject fieldOrMethod, Map<String,String> properties, String stringValue, Object convertedValue) { // check input values if (protocol == null) { throw new IllegalArgumentException("Protocol for Field/Method must be non-null") ; } if (fieldOrMethod instanceof Field) { isField = true ; } else if (fieldOrMethod instanceof Method) { isField = false ; } else throw new IllegalArgumentException("AccesibleObject is neither Field nor Method") ; if (properties == null) { throw new IllegalArgumentException("Properties for Field/Method must be non-null") ; } // set the values passed by the user - need to check for null this.protocol = protocol ; this.fieldOrMethod = fieldOrMethod ; this.properties = properties ; this.stringValue = stringValue ; this.convertedValue = convertedValue ; // set the property name Property annotation=fieldOrMethod.getAnnotation(Property.class); if (isField()) propertyName=PropertyHelper.getPropertyName((Field)fieldOrMethod, properties) ; else propertyName=PropertyHelper.getPropertyName((Method)fieldOrMethod) ; // is variable type parameterized this.isParameterized = false ; if (isField()) this.isParameterized = hasParameterizedType((Field)fieldOrMethod) ; else this.isParameterized = hasParameterizedType((Method)fieldOrMethod) ; // if parameterized, what is the base type? this.baseType = null ; if (isField() && isParameterized) { // the Field has a single type ParameterizedType fpt = (ParameterizedType)((Field)fieldOrMethod).getGenericType() ; this.baseType = fpt.getActualTypeArguments()[0] ; } else if (!isField() && isParameterized) { // the Method has several parameters (and so types) Type[] types = (Type[])((Method)fieldOrMethod).getGenericParameterTypes(); ParameterizedType mpt = (ParameterizedType) types[0] ; this.baseType = mpt.getActualTypeArguments()[0] ; } } // Protocol getProtocol() {return protocol ;} Object getProtocol() {return protocol ;} AccessibleObject getFieldOrMethod() {return fieldOrMethod ;} boolean isField() { return isField ; } String getStringValue() {return stringValue ;} String getPropertyName() {return propertyName ;} Map<String,String> getProperties() {return properties ;} Object getConvertedValue() {return convertedValue ;} boolean isParameterized() {return isParameterized ;} Object getBaseType() { return baseType ;} static boolean hasParameterizedType(Field f) { if (f == null) { throw new IllegalArgumentException("Field argument is null") ; } Type type = f.getGenericType(); return (type instanceof ParameterizedType) ; } static boolean hasParameterizedType(Method m) throws IllegalArgumentException { if (m == null) { throw new IllegalArgumentException("Method argument is null") ; } Type[] types = m.getGenericParameterTypes() ; return (types[0] instanceof ParameterizedType) ; } static boolean isInetAddressRelated(Protocol prot, Field f) { if (hasParameterizedType(f)) { // check for List<InetAddress>, List<InetSocketAddress>, List<IpAddress> ParameterizedType fieldtype = (ParameterizedType) f.getGenericType() ; // check that this parameterized type satisfies our constraints try { parameterizedTypeSanityCheck(fieldtype) ; } catch(IllegalArgumentException e) { // because this Method's parameter fails the sanity check, its probably not an InetAddress related structure return false ; } Class<?> listType = (Class<?>) fieldtype.getActualTypeArguments()[0] ; return isInetAddressOrCompatibleType(listType) ; } else { // check if the non-parameterized type is InetAddress, InetSocketAddress or IpAddress Class<?> fieldtype = f.getType() ; return isInetAddressOrCompatibleType(fieldtype) ; } } /* * Checks if this method's single parameter represents of of the following: * an InetAddress, IpAddress or InetSocketAddress or one of * List<InetAddress>, List<IpAddress> or List<InetSocketAddress> */ static boolean isInetAddressRelated(Method m) { if (hasParameterizedType(m)) { Type[] types = m.getGenericParameterTypes(); ParameterizedType methodParamType = (ParameterizedType)types[0] ; // check that this parameterized type satisfies our constraints try { parameterizedTypeSanityCheck(methodParamType) ; } catch(IllegalArgumentException e) { if(log.isErrorEnabled()) { log.error("Method " + m.getName() + " failed paramaterizedTypeSanityCheck()") ; } // because this Method's parameter fails the sanity check, its probably not // an InetAddress related structure return false ; } Class<?> listType = (Class<?>) methodParamType.getActualTypeArguments()[0] ; return isInetAddressOrCompatibleType(listType) ; } else { Class<?> methodParamType = m.getParameterTypes()[0] ; return isInetAddressOrCompatibleType(methodParamType) ; } } static boolean isInetAddressOrCompatibleType(Class<?> c) { return c.equals(InetAddress.class) || c.equals(InetSocketAddress.class) || c.equals(IpAddress.class) ; } /* * Check if the parameterized type represents one of: * List<InetAddress>, List<IpAddress>, List<InetSocketAddress> */ static void parameterizedTypeSanityCheck(ParameterizedType pt) throws IllegalArgumentException { Type rawType = pt.getRawType() ; Type[] actualTypes = pt.getActualTypeArguments() ; // constraints on use of parameterized types with @Property if (!(rawType instanceof Class<?> && rawType.equals(List.class))) { throw new IllegalArgumentException("Invalid parameterized type definition - parameterized type must be a List") ; } // check for non-parameterized type in List if (!(actualTypes[0] instanceof Class<?>)) { throw new IllegalArgumentException("Invalid parameterized type - List must not contain a parameterized type") ; } } /* * Converts the computedValue to a list of InetAddresses. * Because computedValues may be null, we need to return * a zero length list in some cases. */ public List<InetAddress> getInetAddresses() { List<InetAddress> addresses = new ArrayList<InetAddress>() ; if (getConvertedValue() == null) return addresses ; // if we take only an InetAddress argument if (!isParameterized()) { addresses.add(getInetAddress(getConvertedValue())) ; return addresses ; } // if we take a List<InetAddress> or similar else { List<?> values = (List<?>) getConvertedValue() ; if (values.isEmpty()) return addresses ; for (int i = 0; i < values.size(); i++) { addresses.add(getInetAddress(values.get(i))) ; } return addresses ; } } private static InetAddress getInetAddress(Object obj) throws IllegalArgumentException { if (obj == null) throw new IllegalArgumentException("Input argument must represent a non-null IP address") ; if (obj instanceof InetAddress) return (InetAddress) obj ; else if (obj instanceof IpAddress) return ((IpAddress) obj).getIpAddress() ; else if (obj instanceof InetSocketAddress) return ((InetSocketAddress) obj).getAddress() ; else { if (log.isWarnEnabled()) log.warn("Input argument does not represent one of InetAddress...: class=" + obj.getClass().getName()) ; throw new IllegalArgumentException("Input argument does not represent one of InetAddress. IpAddress not InetSocketAddress") ; } } public String toString() { StringBuilder sb = new StringBuilder() ; sb.append("InetAddressInfo(") ; sb.append("protocol=" + protocol.getName()) ; sb.append(", propertyName=" + getPropertyName()) ; sb.append(", string value=" + getStringValue()) ; sb.append(", parameterized=" + isParameterized()) ; if (isParameterized()) sb.append(", baseType=" + getBaseType()) ; sb.append(")") ; return sb.toString(); } } }
src/org/jgroups/stack/Configurator.java
package org.jgroups.stack; import org.jgroups.Event; import org.jgroups.Global; import org.jgroups.annotations.DeprecatedProperty; import org.jgroups.annotations.LocalAddress; import org.jgroups.annotations.Property; import org.jgroups.conf.PropertyHelper; import org.jgroups.conf.ProtocolConfiguration; import org.jgroups.logging.Log; import org.jgroups.logging.LogFactory; import org.jgroups.protocols.TP; import org.jgroups.util.StackType; import org.jgroups.util.Tuple; import org.jgroups.util.Util; import java.io.IOException; import java.io.PushbackReader; import java.io.Reader; import java.io.StringReader; import java.lang.reflect.*; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.*; import java.util.concurrent.ConcurrentMap; /** * The task if this class is to setup and configure the protocol stack. A string describing * the desired setup, which is both the layering and the configuration of each layer, is * given to the configurator which creates and configures the protocol stack and returns * a reference to the top layer (Protocol).<p> * Future functionality will include the capability to dynamically modify the layering * of the protocol stack and the properties of each layer. * @author Bela Ban * @author Richard Achmatowicz */ public class Configurator { protected static final Log log=LogFactory.getLog(Configurator.class); private final ProtocolStack stack; public Configurator() { stack=null; } public Configurator(ProtocolStack protocolStack) { stack=protocolStack; } public Protocol setupProtocolStack(List<ProtocolConfiguration> config) throws Exception{ return setupProtocolStack(config, stack); } public Protocol setupProtocolStack(ProtocolStack copySource)throws Exception{ List<Protocol> protocols=copySource.copyProtocols(stack); Collections.reverse(protocols); return connectProtocols(protocols); } /** * The configuration string has a number of entries, separated by a ':' (colon). * Each entry consists of the name of the protocol, followed by an optional configuration * of that protocol. The configuration is enclosed in parentheses, and contains entries * which are name/value pairs connected with an assignment sign (=) and separated by * a semicolon. * <pre>UDP(in_port=5555;out_port=4445):FRAG(frag_size=1024)</pre><p> * The <em>first</em> entry defines the <em>bottommost</em> layer, the string is parsed * left to right and the protocol stack constructed bottom up. Example: the string * "UDP(in_port=5555):FRAG(frag_size=32000):DEBUG" results is the following stack:<pre> * * ----------------------- * | DEBUG | * |-----------------------| * | FRAG frag_size=32000 | * |-----------------------| * | UDP in_port=32000 | * ----------------------- * </pre> */ private static Protocol setupProtocolStack(List<ProtocolConfiguration> protocol_configs, ProtocolStack st) throws Exception { List<Protocol> protocols=createProtocols(protocol_configs, st); if(protocols == null) return null; // check InetAddress related features of stack Map<String, Map<String,InetAddressInfo>> inetAddressMap = createInetAddressMap(protocol_configs, protocols) ; Collection<InetAddress> addrs=getAddresses(inetAddressMap); StackType ip_version=Util.getIpStackType(); // 0 = n/a, 4 = IPv4, 6 = IPv6 if(!addrs.isEmpty()) { // check that all user-supplied InetAddresses have a consistent version: // 1. If an addr is IPv6 and we have an IPv4 stack --> FAIL // 2. If an address is an IPv4 class D (multicast) address and the stack is IPv6: FAIL // Else pass for(InetAddress addr: addrs) { if(addr instanceof Inet6Address && ip_version == StackType.IPv4) throw new IllegalArgumentException("found IPv6 address " + addr + " in an IPv4 stack"); if(addr instanceof Inet4Address && addr.isMulticastAddress() && ip_version == StackType.IPv6) throw new Exception("found IPv4 multicast address " + addr + " in an IPv6 stack"); } } // process default values setDefaultValues(protocol_configs, protocols, ip_version); ensureValidBindAddresses(protocols); return connectProtocols(protocols); } public static void setDefaultValues(List<Protocol> protocols) throws Exception { if(protocols == null) return; // check InetAddress related features of stack Collection<InetAddress> addrs=getInetAddresses(protocols); StackType ip_version=Util.getIpStackType(); // 0 = n/a, 4 = IPv4, 6 = IPv6 if(!addrs.isEmpty()) { // check that all user-supplied InetAddresses have a consistent version: // 1. If an addr is IPv6 and we have an IPv4 stack --> FAIL // 2. If an address is an IPv4 class D (multicast) address and the stack is IPv6: FAIL // Else pass for(InetAddress addr : addrs) { if(addr instanceof Inet6Address && ip_version == StackType.IPv4) throw new IllegalArgumentException("found IPv6 address " + addr + " in an IPv4 stack"); if(addr instanceof Inet4Address && addr.isMulticastAddress() && ip_version == StackType.IPv6) throw new Exception("found IPv4 multicast address " + addr + " in an IPv6 stack"); } } // process default values setDefaultValues(protocols, ip_version); } /** * Creates a new protocol given the protocol specification. Initializes the properties and starts the * up and down handler threads. * @param prot_spec The specification of the protocol. Same convention as for specifying a protocol stack. * An exception will be thrown if the class cannot be created. Example: * <pre>"VERIFY_SUSPECT(timeout=1500)"</pre> Note that no colons (:) have to be * specified * @param stack The protocol stack * @return Protocol The newly created protocol * @exception Exception Will be thrown when the new protocol cannot be created */ public static Protocol createProtocol(String prot_spec, ProtocolStack stack) throws Exception { ProtocolConfiguration config; Protocol prot; if(prot_spec == null) throw new Exception("Configurator.createProtocol(): prot_spec is null"); // parse the configuration for this protocol config=new ProtocolConfiguration(prot_spec); // create an instance of the protocol class and configure it prot=createLayer(stack, config); prot.init(); return prot; } /* ------------------------------- Private Methods ------------------------------------- */ /** * Creates a protocol stack by iterating through the protocol list and connecting * adjacent layers. The list starts with the topmost layer and has the bottommost * layer at the tail. * @param protocol_list List of Protocol elements (from top to bottom) * @return Protocol stack */ public static Protocol connectProtocols(List<Protocol> protocol_list) throws Exception { Protocol current_layer=null, next_layer=null; for(int i=0; i < protocol_list.size(); i++) { current_layer=protocol_list.get(i); if(i + 1 >= protocol_list.size()) break; next_layer=protocol_list.get(i + 1); next_layer.setDownProtocol(current_layer); current_layer.setUpProtocol(next_layer); if(current_layer instanceof TP) { TP transport = (TP)current_layer; if(transport.isSingleton()) { ConcurrentMap<String, Protocol> up_prots=transport.getUpProtocols(); String key; synchronized(up_prots) { while(true) { key=Global.DUMMY + System.currentTimeMillis(); if(up_prots.containsKey(key)) continue; up_prots.put(key, next_layer); break; } } current_layer.setUpProtocol(null); } } } // basic protocol sanity check sanityCheck(protocol_list); return current_layer; } /** * Get a string of the form "P1(config_str1):P2:P3(config_str3)" and return * ProtocolConfigurations for it. That means, parse "P1(config_str1)", "P2" and * "P3(config_str3)" * @param config_str Configuration string * @return Vector of strings */ private static List<String> parseProtocols(String config_str) throws IOException { List<String> retval=new LinkedList<String>(); PushbackReader reader=new PushbackReader(new StringReader(config_str)); int ch; StringBuilder sb; boolean running=true; while(running) { String protocol_name=readWord(reader); sb=new StringBuilder(); sb.append(protocol_name); ch=read(reader); if(ch == -1) { retval.add(sb.toString()); break; } if(ch == ':') { // no attrs defined retval.add(sb.toString()); continue; } if(ch == '(') { // more attrs defined reader.unread(ch); String attrs=readUntil(reader, ')'); sb.append(attrs); retval.add(sb.toString()); } else { retval.add(sb.toString()); } while(true) { ch=read(reader); if(ch == ':') { break; } if(ch == -1) { running=false; break; } } } reader.close(); return retval; } private static int read(Reader reader) throws IOException { int ch=-1; while((ch=reader.read()) != -1) { if(!Character.isWhitespace(ch)) return ch; } return ch; } /** * Return a number of ProtocolConfigurations in a vector * @param configuration protocol-stack configuration string * @return List of ProtocolConfigurations */ public static List<ProtocolConfiguration> parseConfigurations(String configuration) throws Exception { List<ProtocolConfiguration> retval=new ArrayList<ProtocolConfiguration>(); List<String> protocol_string=parseProtocols(configuration); if(protocol_string == null) return null; for(String component_string: protocol_string) { retval.add(new ProtocolConfiguration(component_string)); } return retval; } public static String printConfigurations(Collection<ProtocolConfiguration> configs) { StringBuilder sb=new StringBuilder(); boolean first=true; for(ProtocolConfiguration config: configs) { if(first) first=false; else sb.append(":"); sb.append(config.getProtocolName()); if(!config.getProperties().isEmpty()) { sb.append('(').append(config.propertiesToString()).append(')'); } } return sb.toString(); } private static String readUntil(Reader reader, char c) throws IOException { StringBuilder sb=new StringBuilder(); int ch; while((ch=read(reader)) != -1) { sb.append((char)ch); if(ch == c) break; } return sb.toString(); } private static String readWord(PushbackReader reader) throws IOException { StringBuilder sb=new StringBuilder(); int ch; while((ch=read(reader)) != -1) { if(Character.isLetterOrDigit(ch) || ch == '_' || ch == '.' || ch == '$') { sb.append((char)ch); } else { reader.unread(ch); break; } } return sb.toString(); } /** * Takes vector of ProtocolConfigurations, iterates through it, creates Protocol for * each ProtocolConfiguration and returns all Protocols in a vector. * @param protocol_configs Vector of ProtocolConfigurations * @param stack The protocol stack * @return List of Protocols */ private static List<Protocol> createProtocols(List<ProtocolConfiguration> protocol_configs, final ProtocolStack stack) throws Exception { List<Protocol> retval=new LinkedList<Protocol>(); ProtocolConfiguration protocol_config; Protocol layer; String singleton_name; for(int i=0; i < protocol_configs.size(); i++) { protocol_config=protocol_configs.get(i); singleton_name=protocol_config.getProperties().get(Global.SINGLETON_NAME); if(singleton_name != null && singleton_name.trim().length() > 0) { Map<String,Tuple<TP, ProtocolStack.RefCounter>> singleton_transports=ProtocolStack.getSingletonTransports(); synchronized(singleton_transports) { if(i > 0) { // crude way to check whether protocol is a transport throw new IllegalArgumentException("Property 'singleton_name' can only be used in a transport" + " protocol (was used in " + protocol_config.getProtocolName() + ")"); } Tuple<TP, ProtocolStack.RefCounter> val=singleton_transports.get(singleton_name); layer=val != null? val.getVal1() : null; if(layer != null) { retval.add(layer); } else { layer=createLayer(stack, protocol_config); if(layer == null) return null; singleton_transports.put(singleton_name, new Tuple<TP, ProtocolStack.RefCounter>((TP)layer,new ProtocolStack.RefCounter((short)0,(short)0))); retval.add(layer); } } continue; } layer=createLayer(stack, protocol_config); if(layer == null) return null; retval.add(layer); } return retval; } protected static Protocol createLayer(ProtocolStack stack, ProtocolConfiguration config) throws Exception { String protocol_name=config.getProtocolName(); Map<String, String> properties=config.getProperties(); Protocol retval=null; if(protocol_name == null || properties == null) return null; String defaultProtocolName=ProtocolConfiguration.protocol_prefix + '.' + protocol_name; Class<?> clazz=null; try { clazz=Util.loadClass(defaultProtocolName, stack.getClass()); } catch(ClassNotFoundException e) { } if(clazz == null) { try { clazz=Util.loadClass(protocol_name, stack.getClass()); } catch(ClassNotFoundException e) { } if(clazz == null) { throw new Exception("unable to load class for protocol " + protocol_name + " (either as an absolute - " + protocol_name + " - or relative - " + defaultProtocolName + " - package name)!"); } } try { retval=(Protocol)clazz.newInstance(); if(retval == null) throw new Exception("creation of instance for protocol " + protocol_name + "failed !"); retval.setProtocolStack(stack); removeDeprecatedProperties(retval, properties); // before processing Field and Method based properties, take dependencies specified // with @Property.dependsUpon into account AccessibleObject[] dependencyOrderedFieldsAndMethods = computePropertyDependencies(retval, properties) ; for(AccessibleObject ordered: dependencyOrderedFieldsAndMethods) { if (ordered instanceof Field) { resolveAndAssignField(retval, (Field)ordered, properties) ; } else if (ordered instanceof Method) { resolveAndInvokePropertyMethod(retval, (Method)ordered, properties) ; } } List<Object> additional_objects=retval.getConfigurableObjects(); if(additional_objects != null && !additional_objects.isEmpty()) { for(Object obj: additional_objects) { resolveAndAssignFields(obj, properties); resolveAndInvokePropertyMethods(obj, properties); } } if(!properties.isEmpty()) { throw new IllegalArgumentException("the following properties in " + protocol_name + " are not recognized: " + properties); } } catch(InstantiationException inst_ex) { log.error("an instance of " + protocol_name + " could not be created. Please check that it implements" + " interface Protocol and that is has a public empty constructor !"); throw inst_ex; } return retval; } /** Throws an exception if sanity check fails. Possible sanity check is uniqueness of all protocol names */ public static void sanityCheck(List<Protocol> protocols) throws Exception { // check for unique IDs Set<Short> ids=new HashSet<Short>(); for(Protocol protocol: protocols) { short id=protocol.getId(); if(id > 0 && ids.add(id) == false) throw new Exception("Protocol ID " + id + " (name=" + protocol.getName() + ") is duplicate; protocol IDs have to be unique"); } // For each protocol, get its required up and down services and check (if available) if they're satisfied for(Protocol protocol: protocols) { List<Integer> required_down_services=protocol.requiredDownServices(); List<Integer> required_up_services=protocol.requiredUpServices(); if(required_down_services != null && !required_down_services.isEmpty()) { // the protocols below 'protocol' have to provide the services listed in required_down_services List<Integer> tmp=new ArrayList<Integer>(required_down_services); removeProvidedUpServices(protocol, tmp); if(!tmp.isEmpty()) throw new Exception("events " + printEvents(tmp) + " are required by " + protocol.getName() + ", but not provided by any of the protocols below it"); } if(required_up_services != null && !required_up_services.isEmpty()) { // the protocols above 'protocol' have to provide the services listed in required_up_services List<Integer> tmp=new ArrayList<Integer>(required_up_services); removeProvidedDownServices(protocol, tmp); if(!tmp.isEmpty()) throw new Exception("events " + printEvents(tmp) + " are required by " + protocol.getName() + ", but not provided by any of the protocols above it"); } } } protected static String printEvents(List<Integer> events) { StringBuilder sb=new StringBuilder("["); for(int evt: events) sb.append(Event.type2String(evt)).append(" "); sb.append("]"); return sb.toString(); } /** * Removes all events provided by the protocol below protocol from events * @param protocol * @param events */ protected static void removeProvidedUpServices(Protocol protocol, List<Integer> events) { if(protocol == null || events == null) return; for(Protocol prot=protocol.getDownProtocol(); prot != null && !events.isEmpty(); prot=prot.getDownProtocol()) { List<Integer> provided_up_services=prot.providedUpServices(); if(provided_up_services != null && !provided_up_services.isEmpty()) events.removeAll(provided_up_services); } } /** * Removes all events provided by the protocol above protocol from events * @param protocol * @param events */ protected static void removeProvidedDownServices(Protocol protocol, List<Integer> events) { if(protocol == null || events == null) return; for(Protocol prot=protocol.getUpProtocol(); prot != null && !events.isEmpty(); prot=prot.getUpProtocol()) { List<Integer> provided_down_services=prot.providedDownServices(); if(provided_down_services != null && !provided_down_services.isEmpty()) events.removeAll(provided_down_services); } } /** * Returns all inet addresses found */ public static Collection<InetAddress> getAddresses(Map<String, Map<String, InetAddressInfo>> inetAddressMap) throws Exception { Set<InetAddress> addrs=new HashSet<InetAddress>(); for(Map.Entry<String, Map<String, InetAddressInfo>> inetAddressMapEntry : inetAddressMap.entrySet()) { Map<String, InetAddressInfo> protocolInetAddressMap=inetAddressMapEntry.getValue(); for(Map.Entry<String, InetAddressInfo> protocolInetAddressMapEntry : protocolInetAddressMap.entrySet()) { InetAddressInfo inetAddressInfo=protocolInetAddressMapEntry.getValue(); // add InetAddressInfo to sets based on IP version List<InetAddress> addresses=inetAddressInfo.getInetAddresses(); for(InetAddress address : addresses) { if(address == null) throw new RuntimeException("This address should not be null! - something is wrong"); addrs.add(address); } } } return addrs; } /** * This method takes a set of InetAddresses, represented by an inetAddressmap, and: * - if the resulting set is non-empty, goes through to see if all InetAddress-related * user settings have a consistent IP version: v4 or v6, and throws an exception if not * - if the resulting set is empty, sets the default IP version based on available stacks * and if a dual stack, stack preferences * - sets the IP version to be used in the JGroups session * @return StackType.IPv4 for IPv4, StackType.IPv6 for IPv6, StackType.Unknown if the version cannot be determined */ public static StackType determineIpVersionFromAddresses(Collection<InetAddress> addrs) throws Exception { Set<InetAddress> ipv4_addrs= new HashSet<InetAddress>() ; Set<InetAddress> ipv6_addrs= new HashSet<InetAddress>() ; for(InetAddress address: addrs) { if (address instanceof Inet4Address) ipv4_addrs.add(address) ; else ipv6_addrs.add(address) ; } if(log.isTraceEnabled()) log.trace("all addrs=" + addrs + ", IPv4 addrs=" + ipv4_addrs + ", IPv6 addrs=" + ipv6_addrs); // the user supplied 1 or more IP address inputs. Check if we have a consistent set if (!addrs.isEmpty()) { if (!ipv4_addrs.isEmpty() && !ipv6_addrs.isEmpty()) { throw new RuntimeException("all addresses have to be either IPv4 or IPv6: IPv4 addresses=" + ipv4_addrs + ", IPv6 addresses=" + ipv6_addrs); } return !ipv6_addrs.isEmpty()? StackType.IPv6 : StackType.IPv4; } return StackType.Unknown; } /* * A method which does the following: * - discovers all Fields or Methods within the protocol stack which set * InetAddress, IpAddress, InetSocketAddress (and Lists of such) for which the user *has* * specified a default value. * - stores the resulting set of Fields and Methods in a map of the form: * Protocol -> Property -> InetAddressInfo * where InetAddressInfo instances encapsulate the InetAddress related information * of the Fields and Methods. */ public static Map<String, Map<String,InetAddressInfo>> createInetAddressMap(List<ProtocolConfiguration> protocol_configs, List<Protocol> protocols) throws Exception { // Map protocol -> Map<String, InetAddressInfo>, where the latter is protocol specific Map<String, Map<String,InetAddressInfo>> inetAddressMap = new HashMap<String, Map<String, InetAddressInfo>>() ; // collect InetAddressInfo for (int i = 0; i < protocol_configs.size(); i++) { ProtocolConfiguration protocol_config = protocol_configs.get(i) ; Protocol protocol = protocols.get(i) ; String protocolName = protocol.getName(); // regenerate the Properties which were destroyed during basic property processing Map<String,String> properties = protocol_config.getOriginalProperties(); // check which InetAddress-related properties are ***non-null ***, and // create an InetAddressInfo structure for them // Method[] methods=protocol.getClass().getMethods(); Method[] methods=Util.getAllDeclaredMethodsWithAnnotations(protocol.getClass(), Property.class); for(int j = 0; j < methods.length; j++) { if (methods[j].isAnnotationPresent(Property.class) && isSetPropertyMethod(methods[j])) { String propertyName = PropertyHelper.getPropertyName(methods[j]) ; String propertyValue = properties.get(propertyName); // if there is a systemProperty attribute defined in the annotation, set the property value from the system property String tmp=grabSystemProp(methods[j].getAnnotation(Property.class)); if(tmp != null) propertyValue=tmp; if (propertyValue != null && InetAddressInfo.isInetAddressRelated(methods[j])) { Object converted = null ; try { converted=PropertyHelper.getConvertedValue(protocol, methods[j], properties, propertyValue, false); } catch(Exception e) { throw new Exception("String value could not be converted for method " + propertyName + " in " + protocolName + " with default value " + propertyValue + ".Exception is " +e, e); } InetAddressInfo inetinfo = new InetAddressInfo(protocol, methods[j], properties, propertyValue, converted) ; Map<String, InetAddressInfo> protocolInetAddressMap=inetAddressMap.get(protocolName); if(protocolInetAddressMap == null) { protocolInetAddressMap = new HashMap<String,InetAddressInfo>() ; inetAddressMap.put(protocolName, protocolInetAddressMap) ; } protocolInetAddressMap.put(propertyName, inetinfo) ; } } } //traverse class hierarchy and find all annotated fields and add them to the list if annotated for(Class<?> clazz=protocol.getClass(); clazz != null; clazz=clazz.getSuperclass()) { Field[] fields=clazz.getDeclaredFields(); for(int j = 0; j < fields.length; j++ ) { if (fields[j].isAnnotationPresent(Property.class)) { String propertyName = PropertyHelper.getPropertyName(fields[j], properties) ; String propertyValue = properties.get(propertyName) ; // if there is a systemProperty attribute defined in the annotation, set the property value from the system property String tmp=grabSystemProp(fields[j].getAnnotation(Property.class)); if(tmp != null) propertyValue=tmp; if ((propertyValue != null || !PropertyHelper.usesDefaultConverter(fields[j])) && InetAddressInfo.isInetAddressRelated(protocol, fields[j])) { Object converted = null ; try { converted=PropertyHelper.getConvertedValue(protocol, fields[j], properties, propertyValue, false); } catch(Exception e) { throw new Exception("String value could not be converted for method " + propertyName + " in " + protocolName + " with default value " + propertyValue + ".Exception is " +e, e); } InetAddressInfo inetinfo = new InetAddressInfo(protocol, fields[j], properties, propertyValue, converted) ; Map<String, InetAddressInfo> protocolInetAddressMap=inetAddressMap.get(protocolName); if(protocolInetAddressMap == null) { protocolInetAddressMap = new HashMap<String,InetAddressInfo>() ; inetAddressMap.put(protocolName, protocolInetAddressMap) ; } protocolInetAddressMap.put(propertyName, inetinfo) ; }// recompute } } } } return inetAddressMap ; } public static List<InetAddress> getInetAddresses(List<Protocol> protocols) throws Exception { List<InetAddress> retval=new LinkedList<InetAddress>(); // collect InetAddressInfo for(Protocol protocol : protocols) { String protocolName=protocol.getName(); //traverse class hierarchy and find all annotated fields and add them to the list if annotated for(Class<?> clazz=protocol.getClass(); clazz != null; clazz=clazz.getSuperclass()) { Field[] fields=clazz.getDeclaredFields(); for(int j=0; j < fields.length; j++) { if(fields[j].isAnnotationPresent(Property.class)) { if(InetAddressInfo.isInetAddressRelated(protocol, fields[j])) { Object value=getValueFromProtocol(protocol, fields[j]); if(value instanceof InetAddress) retval.add((InetAddress)value); else if(value instanceof IpAddress) retval.add(((IpAddress)value).getIpAddress()); else if(value instanceof InetSocketAddress) retval.add(((InetSocketAddress)value).getAddress()); } } } } } return retval; } /* * Method which processes @Property.default() values, associated with the annotation * using the defaultValue= attribute. This method does the following: * - locate all properties which have no user value assigned * - if the defaultValue attribute is not "", generate a value for the field using the * property converter for that property and assign it to the field */ public static void setDefaultValues(List<ProtocolConfiguration> protocol_configs, List<Protocol> protocols, StackType ip_version) throws Exception { InetAddress default_ip_address=Util.getNonLoopbackAddress(); if(default_ip_address == null) { log.warn("unable to find an address other than loopback for IP version " + ip_version); default_ip_address=Util.getLocalhost(ip_version); } for(int i=0; i < protocol_configs.size(); i++) { ProtocolConfiguration protocol_config=protocol_configs.get(i); Protocol protocol=protocols.get(i); String protocolName=protocol.getName(); // regenerate the Properties which were destroyed during basic property processing Map<String,String> properties=protocol_config.getOriginalProperties(); Method[] methods=Util.getAllDeclaredMethodsWithAnnotations(protocol.getClass(), Property.class); for(int j=0; j < methods.length; j++) { if(isSetPropertyMethod(methods[j])) { String propertyName=PropertyHelper.getPropertyName(methods[j]); Object propertyValue=getValueFromProtocol(protocol, propertyName); if(propertyValue == null) { // if propertyValue is null, check if there is a we can use Property annotation=methods[j].getAnnotation(Property.class); // get the default value for the method- check for InetAddress types String defaultValue=null; if(InetAddressInfo.isInetAddressRelated(methods[j])) { defaultValue=ip_version == StackType.IPv4? annotation.defaultValueIPv4() : annotation.defaultValueIPv6(); if(defaultValue != null && defaultValue.length() > 0) { Object converted=null; try { if(defaultValue.equalsIgnoreCase(Global.NON_LOOPBACK_ADDRESS)) converted=default_ip_address; else converted=PropertyHelper.getConvertedValue(protocol, methods[j], properties, defaultValue, true); methods[j].invoke(protocol, converted); } catch(Exception e) { throw new Exception("default could not be assigned for method " + propertyName + " in " + protocolName + " with default " + defaultValue, e); } if(log.isDebugEnabled()) log.debug("set property " + protocolName + "." + propertyName + " to default value " + converted); } } } } } //traverse class hierarchy and find all annotated fields and add them to the list if annotated Field[] fields=Util.getAllDeclaredFieldsWithAnnotations(protocol.getClass(), Property.class); for(int j=0; j < fields.length; j++) { String propertyName=PropertyHelper.getPropertyName(fields[j], properties); Object propertyValue=getValueFromProtocol(protocol, fields[j]); if(propertyValue == null) { // add to collection of @Properties with no user specified value Property annotation=fields[j].getAnnotation(Property.class); // get the default value for the field - check for InetAddress types String defaultValue=null; if(InetAddressInfo.isInetAddressRelated(protocol, fields[j])) { defaultValue=ip_version == StackType.IPv4? annotation.defaultValueIPv4() : annotation.defaultValueIPv6(); if(defaultValue != null && defaultValue.length() > 0) { // condition for invoking converter if(defaultValue != null || !PropertyHelper.usesDefaultConverter(fields[j])) { Object converted=null; try { if(defaultValue.equalsIgnoreCase(Global.NON_LOOPBACK_ADDRESS)) converted=default_ip_address; else converted=PropertyHelper.getConvertedValue(protocol, fields[j], properties, defaultValue, true); if(converted != null) setField(fields[j], protocol, converted); } catch(Exception e) { throw new Exception("default could not be assigned for field " + propertyName + " in " + protocolName + " with default value " + defaultValue, e); } if(log.isDebugEnabled()) log.debug("set property " + protocolName + "." + propertyName + " to default value " + converted); } } } } } } } public static void setDefaultValues(List<Protocol> protocols, StackType ip_version) throws Exception { InetAddress default_ip_address=Util.getNonLoopbackAddress(); if(default_ip_address == null) { log.warn("unable to find an address other than loopback for IP version " + ip_version); default_ip_address=Util.getLocalhost(ip_version); } for(Protocol protocol : protocols) { String protocolName=protocol.getName(); //traverse class hierarchy and find all annotated fields and add them to the list if annotated Field[] fields=Util.getAllDeclaredFieldsWithAnnotations(protocol.getClass(), Property.class); for(int j=0; j < fields.length; j++) { // get the default value for the field - check for InetAddress types if(InetAddressInfo.isInetAddressRelated(protocol, fields[j])) { Object propertyValue=getValueFromProtocol(protocol, fields[j]); if(propertyValue == null) { // add to collection of @Properties with no user specified value Property annotation=fields[j].getAnnotation(Property.class); String defaultValue=ip_version == StackType.IPv4? annotation.defaultValueIPv4() : annotation.defaultValueIPv6(); if(defaultValue != null && defaultValue.length() > 0) { // condition for invoking converter Object converted=null; try { if(defaultValue.equalsIgnoreCase(Global.NON_LOOPBACK_ADDRESS)) converted=default_ip_address; else converted=PropertyHelper.getConvertedValue(protocol, fields[j], defaultValue, true); if(converted != null) setField(fields[j], protocol, converted); } catch(Exception e) { throw new Exception("default could not be assigned for field " + fields[j].getName() + " in " + protocolName + " with default value " + defaultValue, e); } if(log.isDebugEnabled()) log.debug("set property " + protocolName + "." + fields[j].getName() + " to default value " + converted); } } } } } } /** * Makes sure that all fields annotated with @LocalAddress is (1) an InetAddress and (2) a valid address on any * local network interface * @param protocols * @throws Exception */ public static void ensureValidBindAddresses(List<Protocol> protocols) throws Exception { for(Protocol protocol : protocols) { String protocolName=protocol.getName(); //traverse class hierarchy and find all annotated fields and add them to the list if annotated Field[] fields=Util.getAllDeclaredFieldsWithAnnotations(protocol.getClass(), LocalAddress.class); for(int i=0; i < fields.length; i++) { Object val=getValueFromProtocol(protocol, fields[i]); if(!(val instanceof InetAddress)) throw new Exception("field " + protocolName + "." + fields[i].getName() + " is not an InetAddress"); Util.checkIfValidAddress((InetAddress)val, protocolName); } } } public static Object getValueFromProtocol(Protocol protocol, Field field) throws IllegalAccessException { if(protocol == null || field == null) return null; if(!Modifier.isPublic(field.getModifiers())) field.setAccessible(true); return field.get(protocol); } public static Object getValueFromProtocol(Protocol protocol, String field_name) throws IllegalAccessException { if(protocol == null || field_name == null) return null; Field field=Util.getField(protocol.getClass(), field_name); return field != null? getValueFromProtocol(protocol, field) : null; } /** * This method creates a list of all properties (Field or Method) in dependency order, * where dependencies are specified using the dependsUpon specifier of the Property annotation. * In particular, it does the following: * (i) creates a master list of properties * (ii) checks that all dependency references are present * (iii) creates a copy of the master list in dependency order */ static AccessibleObject[] computePropertyDependencies(Object obj, Map<String,String> properties) { // List of Fields and Methods of the protocol annotated with @Property List<AccessibleObject> unorderedFieldsAndMethods = new LinkedList<AccessibleObject>() ; List<AccessibleObject> orderedFieldsAndMethods = new LinkedList<AccessibleObject>() ; // Maps property name to property object Map<String, AccessibleObject> propertiesInventory = new HashMap<String, AccessibleObject>() ; // get the methods for this class and add them to the list if annotated with @Property Method[] methods=obj.getClass().getMethods(); for(int i = 0; i < methods.length; i++) { if (methods[i].isAnnotationPresent(Property.class) && isSetPropertyMethod(methods[i])) { String propertyName = PropertyHelper.getPropertyName(methods[i]) ; unorderedFieldsAndMethods.add(methods[i]) ; propertiesInventory.put(propertyName, methods[i]) ; } } //traverse class hierarchy and find all annotated fields and add them to the list if annotated for(Class<?> clazz=obj.getClass(); clazz != null; clazz=clazz.getSuperclass()) { Field[] fields=clazz.getDeclaredFields(); for(int i = 0; i < fields.length; i++ ) { if (fields[i].isAnnotationPresent(Property.class)) { String propertyName = PropertyHelper.getPropertyName(fields[i], properties) ; unorderedFieldsAndMethods.add(fields[i]) ; // may need to change this based on name parameter of Property propertiesInventory.put(propertyName, fields[i]) ; } } } // at this stage, we have all Fields and Methods annotated with @Property checkDependencyReferencesPresent(unorderedFieldsAndMethods, propertiesInventory) ; // order the fields and methods by dependency orderedFieldsAndMethods = orderFieldsAndMethodsByDependency(unorderedFieldsAndMethods, propertiesInventory) ; // convert to array of Objects AccessibleObject[] result = new AccessibleObject[orderedFieldsAndMethods.size()] ; for(int i = 0; i < orderedFieldsAndMethods.size(); i++) { result[i] = orderedFieldsAndMethods.get(i) ; } return result ; } static List<AccessibleObject> orderFieldsAndMethodsByDependency(List<AccessibleObject> unorderedList, Map<String, AccessibleObject> propertiesMap) { // Stack to detect cycle in depends relation Stack<AccessibleObject> stack = new Stack<AccessibleObject>() ; // the result list List<AccessibleObject> orderedList = new LinkedList<AccessibleObject>() ; // add the elements from the unordered list to the ordered list // any dependencies will be checked and added first, in recursive manner for(int i = 0; i < unorderedList.size(); i++) { AccessibleObject obj = unorderedList.get(i) ; addPropertyToDependencyList(orderedList, propertiesMap, stack, obj) ; } return orderedList ; } /** * DFS of dependency graph formed by Property annotations and dependsUpon parameter * This is used to create a list of Properties in dependency order */ static void addPropertyToDependencyList(List<AccessibleObject> orderedList, Map<String, AccessibleObject> props, Stack<AccessibleObject> stack, AccessibleObject obj) { if (orderedList.contains(obj)) return ; if (stack.search(obj) > 0) { throw new RuntimeException("Deadlock in @Property dependency processing") ; } // record the fact that we are processing obj stack.push(obj) ; // process dependencies for this object before adding it to the list Property annotation = obj.getAnnotation(Property.class) ; String dependsClause = annotation.dependsUpon() ; StringTokenizer st = new StringTokenizer(dependsClause, ",") ; while (st.hasMoreTokens()) { String token = st.nextToken().trim(); AccessibleObject dep = props.get(token) ; // if null, throw exception addPropertyToDependencyList(orderedList, props, stack, dep) ; } // indicate we're done with processing dependencies stack.pop() ; // we can now add in dependency order orderedList.add(obj) ; } /* * Checks that for every dependency referred, there is a matching property */ static void checkDependencyReferencesPresent(List<AccessibleObject> objects, Map<String, AccessibleObject> props) { // iterate overall properties marked by @Property for(int i = 0; i < objects.size(); i++) { // get the Property annotation AccessibleObject ao = objects.get(i) ; Property annotation = ao.getAnnotation(Property.class) ; if (annotation == null) { throw new IllegalArgumentException("@Property annotation is required for checking dependencies;" + " annotation is missing for Field/Method " + ao.toString()) ; } String dependsClause = annotation.dependsUpon() ; if (dependsClause.trim().length() == 0) continue ; // split dependsUpon specifier into tokens; trim each token; search for token in list StringTokenizer st = new StringTokenizer(dependsClause, ",") ; while (st.hasMoreTokens()) { String token = st.nextToken().trim() ; // check that the string representing a property name is in the list boolean found = false ; Set<String> keyset = props.keySet(); for (Iterator<String> iter = keyset.iterator(); iter.hasNext();) { if (iter.next().equals(token)) { found = true ; break ; } } if (!found) { throw new IllegalArgumentException("@Property annotation " + annotation.name() + " has an unresolved dependsUpon property: " + token) ; } } } } public static void resolveAndInvokePropertyMethods(Object obj, Map<String,String> props) throws Exception { Method[] methods=obj.getClass().getMethods(); for(Method method: methods) { resolveAndInvokePropertyMethod(obj, method, props) ; } } public static void resolveAndInvokePropertyMethod(Object obj, Method method, Map<String,String> props) throws Exception { String methodName=method.getName(); Property annotation=method.getAnnotation(Property.class); if(annotation != null && isSetPropertyMethod(method)) { String propertyName=PropertyHelper.getPropertyName(method) ; String propertyValue=props.get(propertyName); // if there is a systemProperty attribute defined in the annotation, set the property value from the system property String tmp=grabSystemProp(method.getAnnotation(Property.class)); if(tmp != null) propertyValue=tmp; if(propertyName != null && propertyValue != null) { String deprecated_msg=annotation.deprecatedMessage(); if(deprecated_msg != null && deprecated_msg.length() > 0) { log.warn(method.getDeclaringClass().getSimpleName() + "." + methodName + " has been deprecated : " + deprecated_msg); } } if(propertyValue != null) { Object converted=null; try { converted=PropertyHelper.getConvertedValue(obj, method, props, propertyValue, true); method.invoke(obj, converted); } catch(Exception e) { String name=obj instanceof Protocol? ((Protocol)obj).getName() : obj.getClass().getName(); throw new Exception("Could not assign property " + propertyName + " in " + name + ", method is " + methodName + ", converted value is " + converted, e); } } props.remove(propertyName); } } public static void resolveAndAssignFields(Object obj, Map<String,String> props) throws Exception { //traverse class hierarchy and find all annotated fields for(Class<?> clazz=obj.getClass(); clazz != null; clazz=clazz.getSuperclass()) { Field[] fields=clazz.getDeclaredFields(); for(Field field: fields) { resolveAndAssignField(obj, field, props) ; } } } public static void resolveAndAssignField(Object obj, Field field, Map<String,String> props) throws Exception { Property annotation=field.getAnnotation(Property.class); if(annotation != null) { String propertyName = PropertyHelper.getPropertyName(field, props) ; String propertyValue=props.get(propertyName); // if there is a systemProperty attribute defined in the annotation, set the property value from the system property String tmp=grabSystemProp(field.getAnnotation(Property.class)); if(tmp != null) propertyValue=tmp; if(propertyName != null && propertyValue != null) { String deprecated_msg=annotation.deprecatedMessage(); if(deprecated_msg != null && deprecated_msg.length() > 0) { log.warn(field.getDeclaringClass().getSimpleName() + "." + field.getName() + " has been deprecated: " + deprecated_msg); } } if(propertyValue != null || !PropertyHelper.usesDefaultConverter(field)){ Object converted=null; try { converted=PropertyHelper.getConvertedValue(obj, field, props, propertyValue, true); if(converted != null) setField(field, obj, converted); } catch(Exception e) { String name=obj instanceof Protocol? ((Protocol)obj).getName() : obj.getClass().getName(); throw new Exception("Property assignment of " + propertyName + " in " + name + " with original property value " + propertyValue + " and converted to " + converted + " could not be assigned", e); } } props.remove(propertyName); } } public static void removeDeprecatedProperties(Object obj, Map<String,String> props) throws Exception { //traverse class hierarchy and find all deprecated properties for(Class<?> clazz=obj.getClass(); clazz != null; clazz=clazz.getSuperclass()) { if(clazz.isAnnotationPresent(DeprecatedProperty.class)) { DeprecatedProperty declaredAnnotation=clazz.getAnnotation(DeprecatedProperty.class); String[] deprecatedProperties=declaredAnnotation.names(); for(String propertyName : deprecatedProperties) { String propertyValue=props.get(propertyName); if(propertyValue != null) { if(log.isWarnEnabled()) { String name=obj instanceof Protocol? ((Protocol)obj).getName() : obj.getClass().getName(); log.warn(name + " property " + propertyName + " was deprecated and is ignored"); } props.remove(propertyName); } } } } } public static boolean isSetPropertyMethod(Method method) { return (method.getName().startsWith("set") && method.getReturnType() == java.lang.Void.TYPE && method.getParameterTypes().length == 1); } public static void setField(Field field, Object target, Object value) { if(!Modifier.isPublic(field.getModifiers())) { field.setAccessible(true); } try { field.set(target, value); } catch(IllegalAccessException iae) { throw new IllegalArgumentException("Could not set field " + field, iae); } } public static Object getField(Field field, Object target) { if(!Modifier.isPublic(field.getModifiers())) { field.setAccessible(true); } try { return field.get(target); } catch(IllegalAccessException iae) { throw new IllegalArgumentException("Could not get field " + field, iae); } } private static String grabSystemProp(Property annotation) { String[] system_property_names=annotation.systemProperty(); String retval=null; for(String system_property_name: system_property_names) { if(system_property_name != null && system_property_name.length() > 0) { if(system_property_name.equals(Global.BIND_ADDR) || system_property_name.equals(Global.BIND_ADDR_OLD)) if(Util.isBindAddressPropertyIgnored()) continue; try { retval=System.getProperty(system_property_name); if(retval != null) return retval; } catch(SecurityException ex) { log.error("failed getting system property for " + system_property_name, ex); } } } return retval; } /* --------------------------- End of Private Methods ---------------------------------- */ public static class InetAddressInfo { Protocol protocol ; AccessibleObject fieldOrMethod ; Map<String,String> properties ; String propertyName ; String stringValue ; Object convertedValue ; boolean isField ; boolean isParameterized ; // is the associated type parametrized? (e.g. Collection<String>) Object baseType ; // what is the base type (e.g. Collection) InetAddressInfo(Protocol protocol, AccessibleObject fieldOrMethod, Map<String,String> properties, String stringValue, Object convertedValue) { // check input values if (protocol == null) { throw new IllegalArgumentException("Protocol for Field/Method must be non-null") ; } if (fieldOrMethod instanceof Field) { isField = true ; } else if (fieldOrMethod instanceof Method) { isField = false ; } else throw new IllegalArgumentException("AccesibleObject is neither Field nor Method") ; if (properties == null) { throw new IllegalArgumentException("Properties for Field/Method must be non-null") ; } // set the values passed by the user - need to check for null this.protocol = protocol ; this.fieldOrMethod = fieldOrMethod ; this.properties = properties ; this.stringValue = stringValue ; this.convertedValue = convertedValue ; // set the property name Property annotation=fieldOrMethod.getAnnotation(Property.class); if (isField()) propertyName=PropertyHelper.getPropertyName((Field)fieldOrMethod, properties) ; else propertyName=PropertyHelper.getPropertyName((Method)fieldOrMethod) ; // is variable type parameterized this.isParameterized = false ; if (isField()) this.isParameterized = hasParameterizedType((Field)fieldOrMethod) ; else this.isParameterized = hasParameterizedType((Method)fieldOrMethod) ; // if parameterized, what is the base type? this.baseType = null ; if (isField() && isParameterized) { // the Field has a single type ParameterizedType fpt = (ParameterizedType)((Field)fieldOrMethod).getGenericType() ; this.baseType = fpt.getActualTypeArguments()[0] ; } else if (!isField() && isParameterized) { // the Method has several parameters (and so types) Type[] types = (Type[])((Method)fieldOrMethod).getGenericParameterTypes(); ParameterizedType mpt = (ParameterizedType) types[0] ; this.baseType = mpt.getActualTypeArguments()[0] ; } } // Protocol getProtocol() {return protocol ;} Object getProtocol() {return protocol ;} AccessibleObject getFieldOrMethod() {return fieldOrMethod ;} boolean isField() { return isField ; } String getStringValue() {return stringValue ;} String getPropertyName() {return propertyName ;} Map<String,String> getProperties() {return properties ;} Object getConvertedValue() {return convertedValue ;} boolean isParameterized() {return isParameterized ;} Object getBaseType() { return baseType ;} static boolean hasParameterizedType(Field f) { if (f == null) { throw new IllegalArgumentException("Field argument is null") ; } Type type = f.getGenericType(); return (type instanceof ParameterizedType) ; } static boolean hasParameterizedType(Method m) throws IllegalArgumentException { if (m == null) { throw new IllegalArgumentException("Method argument is null") ; } Type[] types = m.getGenericParameterTypes() ; return (types[0] instanceof ParameterizedType) ; } static boolean isInetAddressRelated(Protocol prot, Field f) { if (hasParameterizedType(f)) { // check for List<InetAddress>, List<InetSocketAddress>, List<IpAddress> ParameterizedType fieldtype = (ParameterizedType) f.getGenericType() ; // check that this parameterized type satisfies our constraints try { parameterizedTypeSanityCheck(fieldtype) ; } catch(IllegalArgumentException e) { // because this Method's parameter fails the sanity check, its probably not an InetAddress related structure return false ; } Class<?> listType = (Class<?>) fieldtype.getActualTypeArguments()[0] ; return isInetAddressOrCompatibleType(listType) ; } else { // check if the non-parameterized type is InetAddress, InetSocketAddress or IpAddress Class<?> fieldtype = f.getType() ; return isInetAddressOrCompatibleType(fieldtype) ; } } /* * Checks if this method's single parameter represents of of the following: * an InetAddress, IpAddress or InetSocketAddress or one of * List<InetAddress>, List<IpAddress> or List<InetSocketAddress> */ static boolean isInetAddressRelated(Method m) { if (hasParameterizedType(m)) { Type[] types = m.getGenericParameterTypes(); ParameterizedType methodParamType = (ParameterizedType)types[0] ; // check that this parameterized type satisfies our constraints try { parameterizedTypeSanityCheck(methodParamType) ; } catch(IllegalArgumentException e) { if(log.isErrorEnabled()) { log.error("Method " + m.getName() + " failed paramaterizedTypeSanityCheck()") ; } // because this Method's parameter fails the sanity check, its probably not // an InetAddress related structure return false ; } Class<?> listType = (Class<?>) methodParamType.getActualTypeArguments()[0] ; return isInetAddressOrCompatibleType(listType) ; } else { Class<?> methodParamType = m.getParameterTypes()[0] ; return isInetAddressOrCompatibleType(methodParamType) ; } } static boolean isInetAddressOrCompatibleType(Class<?> c) { return c.equals(InetAddress.class) || c.equals(InetSocketAddress.class) || c.equals(IpAddress.class) ; } /* * Check if the parameterized type represents one of: * List<InetAddress>, List<IpAddress>, List<InetSocketAddress> */ static void parameterizedTypeSanityCheck(ParameterizedType pt) throws IllegalArgumentException { Type rawType = pt.getRawType() ; Type[] actualTypes = pt.getActualTypeArguments() ; // constraints on use of parameterized types with @Property if (!(rawType instanceof Class<?> && rawType.equals(List.class))) { throw new IllegalArgumentException("Invalid parameterized type definition - parameterized type must be a List") ; } // check for non-parameterized type in List if (!(actualTypes[0] instanceof Class<?>)) { throw new IllegalArgumentException("Invalid parameterized type - List must not contain a parameterized type") ; } } /* * Converts the computedValue to a list of InetAddresses. * Because computedValues may be null, we need to return * a zero length list in some cases. */ public List<InetAddress> getInetAddresses() { List<InetAddress> addresses = new ArrayList<InetAddress>() ; if (getConvertedValue() == null) return addresses ; // if we take only an InetAddress argument if (!isParameterized()) { addresses.add(getInetAddress(getConvertedValue())) ; return addresses ; } // if we take a List<InetAddress> or similar else { List<?> values = (List<?>) getConvertedValue() ; if (values.isEmpty()) return addresses ; for (int i = 0; i < values.size(); i++) { addresses.add(getInetAddress(values.get(i))) ; } return addresses ; } } private static InetAddress getInetAddress(Object obj) throws IllegalArgumentException { if (obj == null) throw new IllegalArgumentException("Input argument must represent a non-null IP address") ; if (obj instanceof InetAddress) return (InetAddress) obj ; else if (obj instanceof IpAddress) return ((IpAddress) obj).getIpAddress() ; else if (obj instanceof InetSocketAddress) return ((InetSocketAddress) obj).getAddress() ; else { if (log.isWarnEnabled()) log.warn("Input argument does not represent one of InetAddress...: class=" + obj.getClass().getName()) ; throw new IllegalArgumentException("Input argument does not represent one of InetAddress. IpAddress not InetSocketAddress") ; } } public String toString() { StringBuilder sb = new StringBuilder() ; sb.append("InetAddressInfo(") ; sb.append("protocol=" + protocol.getName()) ; sb.append(", propertyName=" + getPropertyName()) ; sb.append(", string value=" + getStringValue()) ; sb.append(", parameterized=" + isParameterized()) ; if (isParameterized()) sb.append(", baseType=" + getBaseType()) ; sb.append(")") ; return sb.toString(); } } }
changed exception message
src/org/jgroups/stack/Configurator.java
changed exception message
<ide><path>rc/org/jgroups/stack/Configurator.java <ide> List<InetAddress> addresses=inetAddressInfo.getInetAddresses(); <ide> for(InetAddress address : addresses) { <ide> if(address == null) <del> throw new RuntimeException("This address should not be null! - something is wrong"); <add> throw new RuntimeException("failed converting address info to IP address: " + inetAddressInfo); <ide> addrs.add(address); <ide> } <ide> }
Java
apache-2.0
a7b834307fc89a1b194cf460e07ac60e92274b4a
0
magi42/vaadin,peterl1084/framework,Darsstar/framework,Legioth/vaadin,Scarlethue/vaadin,Peppe/vaadin,jdahlstrom/vaadin.react,mstahv/framework,Darsstar/framework,magi42/vaadin,cbmeeks/vaadin,jdahlstrom/vaadin.react,shahrzadmn/vaadin,kironapublic/vaadin,Flamenco/vaadin,kironapublic/vaadin,bmitc/vaadin,shahrzadmn/vaadin,Scarlethue/vaadin,mittop/vaadin,magi42/vaadin,shahrzadmn/vaadin,sitexa/vaadin,synes/vaadin,kironapublic/vaadin,Flamenco/vaadin,fireflyc/vaadin,carrchang/vaadin,bmitc/vaadin,udayinfy/vaadin,mittop/vaadin,oalles/vaadin,peterl1084/framework,synes/vaadin,travisfw/vaadin,Legioth/vaadin,travisfw/vaadin,kironapublic/vaadin,fireflyc/vaadin,synes/vaadin,peterl1084/framework,udayinfy/vaadin,magi42/vaadin,oalles/vaadin,Peppe/vaadin,Flamenco/vaadin,sitexa/vaadin,shahrzadmn/vaadin,shahrzadmn/vaadin,oalles/vaadin,travisfw/vaadin,Peppe/vaadin,sitexa/vaadin,bmitc/vaadin,Scarlethue/vaadin,jdahlstrom/vaadin.react,synes/vaadin,asashour/framework,magi42/vaadin,mittop/vaadin,peterl1084/framework,Peppe/vaadin,carrchang/vaadin,oalles/vaadin,Legioth/vaadin,Legioth/vaadin,mittop/vaadin,mstahv/framework,asashour/framework,peterl1084/framework,Scarlethue/vaadin,asashour/framework,cbmeeks/vaadin,travisfw/vaadin,fireflyc/vaadin,synes/vaadin,fireflyc/vaadin,Darsstar/framework,udayinfy/vaadin,Darsstar/framework,bmitc/vaadin,mstahv/framework,asashour/framework,jdahlstrom/vaadin.react,mstahv/framework,carrchang/vaadin,jdahlstrom/vaadin.react,Scarlethue/vaadin,udayinfy/vaadin,mstahv/framework,sitexa/vaadin,carrchang/vaadin,cbmeeks/vaadin,sitexa/vaadin,cbmeeks/vaadin,kironapublic/vaadin,udayinfy/vaadin,fireflyc/vaadin,Flamenco/vaadin,oalles/vaadin,travisfw/vaadin,asashour/framework,Darsstar/framework,Legioth/vaadin,Peppe/vaadin
package com.vaadin.demo.tutorial.addressbook.ui; import java.util.Arrays; import java.util.Iterator; import java.util.List; import com.vaadin.data.Item; import com.vaadin.data.util.BeanItem; import com.vaadin.demo.tutorial.addressbook.AddressBookApplication; import com.vaadin.demo.tutorial.addressbook.data.Person; import com.vaadin.demo.tutorial.addressbook.data.PersonContainer; import com.vaadin.demo.tutorial.addressbook.validators.EmailValidator; import com.vaadin.demo.tutorial.addressbook.validators.PostalCodeValidator; import com.vaadin.ui.Button; import com.vaadin.ui.ComboBox; import com.vaadin.ui.Component; import com.vaadin.ui.DefaultFieldFactory; import com.vaadin.ui.Field; import com.vaadin.ui.Form; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.TextField; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Button.ClickListener; public class PersonForm extends Form implements ClickListener { private Button save = new Button("Save", (ClickListener) this); private Button cancel = new Button("Cancel", (ClickListener) this); private Button edit = new Button("Edit", (ClickListener) this); private final ComboBox cities = new ComboBox("City"); private AddressBookApplication app; private boolean newContactMode = false; private Person newPerson = null; public PersonForm(AddressBookApplication app) { this.app = app; /* * Enable buffering so that commit() must be called for the form before * input is written to the data. (Form input is not written immediately * through to the underlying object.) */ setWriteThrough(false); HorizontalLayout footer = new HorizontalLayout(); footer.setSpacing(true); footer.addComponent(save); footer.addComponent(cancel); footer.addComponent(edit); footer.setVisible(false); setFooter(footer); /* Allow the user to enter new cities */ cities.setNewItemsAllowed(true); /* We do not want to use null values */ cities.setNullSelectionAllowed(false); /* Add an empty city used for selecting no city */ cities.addItem(""); /* Populate cities select using the cities in the data container */ PersonContainer ds = app.getDataSource(); for (Iterator<Person> it = ds.getItemIds().iterator(); it.hasNext();) { String city = (it.next()).getCity(); cities.addItem(city); } /* * Field factory for overriding how the component for city selection is * created */ setFormFieldFactory(new DefaultFieldFactory() { @Override public Field createField(Item item, Object propertyId, Component uiContext) { if (propertyId.equals("city")) { cities.setWidth("200px"); return cities; } Field field = super.createField(item, propertyId, uiContext); if (propertyId.equals("postalCode")) { TextField tf = (TextField) field; /* * We do not want to display "null" to the user when the * field is empty */ tf.setNullRepresentation(""); /* Add a validator for postalCode and make it required */ tf.addValidator(new PostalCodeValidator()); tf.setRequired(true); } else if (propertyId.equals("email")) { /* Add a validator for email and make it required */ field.addValidator(new EmailValidator()); field.setRequired(true); } field.setWidth("200px"); return field; } }); } public void buttonClick(ClickEvent event) { Button source = event.getButton(); if (source == save) { /* If the given input is not valid there is no point in continuing */ if (!isValid()) { return; } commit(); if (newContactMode) { /* We need to add the new person to the container */ Item addedItem = app.getDataSource().addItem(newPerson); /* * We must update the form to use the Item from our datasource * as we are now in edit mode (no longer in add mode) */ setItemDataSource(addedItem); newContactMode = false; } setReadOnly(true); } else if (source == cancel) { if (newContactMode) { newContactMode = false; /* Clear the form and make it invisible */ setItemDataSource(null); } else { discard(); } setReadOnly(true); } else if (source == edit) { setReadOnly(false); } } @Override public void setItemDataSource(Item newDataSource) { newContactMode = false; if (newDataSource != null) { List<Object> orderedProperties = Arrays .asList(PersonContainer.NATURAL_COL_ORDER); super.setItemDataSource(newDataSource, orderedProperties); setReadOnly(true); getFooter().setVisible(true); } else { super.setItemDataSource(null); getFooter().setVisible(false); } } @Override public void setReadOnly(boolean readOnly) { super.setReadOnly(readOnly); save.setVisible(!readOnly); cancel.setVisible(!readOnly); edit.setVisible(readOnly); } public void addContact() { // Create a temporary item for the form newPerson = new Person(); setItemDataSource(new BeanItem(newPerson)); newContactMode = true; setReadOnly(false); } }
src/com/vaadin/demo/tutorial/addressbook/ui/PersonForm.java
package com.vaadin.demo.tutorial.addressbook.ui; import java.util.Arrays; import java.util.Iterator; import java.util.List; import com.vaadin.data.Item; import com.vaadin.data.util.BeanItem; import com.vaadin.demo.tutorial.addressbook.AddressBookApplication; import com.vaadin.demo.tutorial.addressbook.data.Person; import com.vaadin.demo.tutorial.addressbook.data.PersonContainer; import com.vaadin.demo.tutorial.addressbook.validators.EmailValidator; import com.vaadin.demo.tutorial.addressbook.validators.PostalCodeValidator; import com.vaadin.ui.Button; import com.vaadin.ui.ComboBox; import com.vaadin.ui.Component; import com.vaadin.ui.DefaultFieldFactory; import com.vaadin.ui.Field; import com.vaadin.ui.Form; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.TextField; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Button.ClickListener; public class PersonForm extends Form implements ClickListener { private Button save = new Button("Save", (ClickListener) this); private Button cancel = new Button("Cancel", (ClickListener) this); private Button edit = new Button("Edit", (ClickListener) this); private final ComboBox cities = new ComboBox("City"); private AddressBookApplication app; private boolean newContactMode = false; private Person newPerson = null; public PersonForm(AddressBookApplication app) { this.app = app; /* * Enable buffering so that commit() must be called for the form before * input is written to the data. (Form input is not written immediately * through to the underlying object.) */ setWriteThrough(false); HorizontalLayout footer = new HorizontalLayout(); footer.setSpacing(true); footer.addComponent(save); footer.addComponent(cancel); footer.addComponent(edit); footer.setVisible(false); setFooter(footer); /* Allow the user to enter new cities */ cities.setNewItemsAllowed(true); /* We do not want to use null values */ cities.setNullSelectionAllowed(false); /* Add an empty city used for selecting no city */ cities.addItem(""); /* Populate cities select using the cities in the data container */ PersonContainer ds = app.getDataSource(); for (Iterator<Person> it = ds.getItemIds().iterator(); it.hasNext();) { String city = (it.next()).getCity(); cities.addItem(city); } /* * Field factory for overriding how the component for city selection is * created */ setFormFieldFactory(new DefaultFieldFactory() { @Override public Field createField(Item item, Object propertyId, Component uiContext) { if (propertyId.equals("city")) { cities.setWidth("200px"); return cities; } Field field = super.createField(item, propertyId, uiContext); if (propertyId.equals("postalCode")) { TextField tf = (TextField) field; /* * We do not want to display "null" to the user when the * field is empty */ tf.setNullRepresentation(""); /* Add a validator for postalCode and make it required */ tf.addValidator(new PostalCodeValidator()); tf.setRequired(true); } else if (propertyId.equals("email")) { /* Add a validator for email and make it required */ field.addValidator(new EmailValidator()); field.setRequired(true); } field.setWidth("200px"); return field; } }); } public void buttonClick(ClickEvent event) { Button source = event.getButton(); if (source == save) { /* If the given input is not valid there is no point in continuing */ if (!isValid()) { return; } commit(); if (newContactMode) { /* We need to add the new person to the container */ Item addedItem = app.getDataSource().addItem(newPerson); /* * We must update the form to use the Item from our datasource * as we are now in edit mode (no longer in add mode) */ setItemDataSource(addedItem); newContactMode = false; } setReadOnly(true); } else if (source == cancel) { if (newContactMode) { newContactMode = false; /* Clear the form and make it invisible */ setItemDataSource(null); } else { discard(); } setReadOnly(true); } else if (source == edit) { setReadOnly(false); } } @Override public void setItemDataSource(Item newDataSource) { newContactMode = false; if (newDataSource != null) { List<Object> orderedProperties = Arrays .asList(PersonContainer.NATURAL_COL_ORDER); super.setItemDataSource(newDataSource, orderedProperties); setReadOnly(true); getFooter().setVisible(true); } else { super.setItemDataSource(null); getFooter().setVisible(false); } } @Override public void setReadOnly(boolean readOnly) { super.setReadOnly(readOnly); save.setVisible(!readOnly); cancel.setVisible(!readOnly); edit.setVisible(readOnly); } public void addContact() { // Create a temporary item for the form newPerson = new Person(); setItemDataSource(new BeanItem(newPerson)); newContactMode = true; setReadOnly(false); } }
Reformatted AddressBook PersonForm with Eclipse default formatting settings. svn changeset:7788/svn branch:6.0
src/com/vaadin/demo/tutorial/addressbook/ui/PersonForm.java
Reformatted AddressBook PersonForm with Eclipse default formatting settings.
<ide><path>rc/com/vaadin/demo/tutorial/addressbook/ui/PersonForm.java <ide> <ide> public class PersonForm extends Form implements ClickListener { <ide> <del> private Button save = new Button("Save", (ClickListener) this); <del> private Button cancel = new Button("Cancel", (ClickListener) this); <del> private Button edit = new Button("Edit", (ClickListener) this); <del> private final ComboBox cities = new ComboBox("City"); <add> private Button save = new Button("Save", (ClickListener) this); <add> private Button cancel = new Button("Cancel", (ClickListener) this); <add> private Button edit = new Button("Edit", (ClickListener) this); <add> private final ComboBox cities = new ComboBox("City"); <ide> <del> private AddressBookApplication app; <del> private boolean newContactMode = false; <del> private Person newPerson = null; <add> private AddressBookApplication app; <add> private boolean newContactMode = false; <add> private Person newPerson = null; <ide> <del> public PersonForm(AddressBookApplication app) { <del> this.app = app; <add> public PersonForm(AddressBookApplication app) { <add> this.app = app; <ide> <del> /* <del> * Enable buffering so that commit() must be called for the form before <del> * input is written to the data. (Form input is not written immediately <del> * through to the underlying object.) <del> */ <del> setWriteThrough(false); <add> /* <add> * Enable buffering so that commit() must be called for the form before <add> * input is written to the data. (Form input is not written immediately <add> * through to the underlying object.) <add> */ <add> setWriteThrough(false); <ide> <del> HorizontalLayout footer = new HorizontalLayout(); <del> footer.setSpacing(true); <del> footer.addComponent(save); <del> footer.addComponent(cancel); <del> footer.addComponent(edit); <del> footer.setVisible(false); <add> HorizontalLayout footer = new HorizontalLayout(); <add> footer.setSpacing(true); <add> footer.addComponent(save); <add> footer.addComponent(cancel); <add> footer.addComponent(edit); <add> footer.setVisible(false); <ide> <del> setFooter(footer); <add> setFooter(footer); <ide> <del> /* Allow the user to enter new cities */ <del> cities.setNewItemsAllowed(true); <del> /* We do not want to use null values */ <del> cities.setNullSelectionAllowed(false); <del> /* Add an empty city used for selecting no city */ <del> cities.addItem(""); <add> /* Allow the user to enter new cities */ <add> cities.setNewItemsAllowed(true); <add> /* We do not want to use null values */ <add> cities.setNullSelectionAllowed(false); <add> /* Add an empty city used for selecting no city */ <add> cities.addItem(""); <ide> <del> /* Populate cities select using the cities in the data container */ <del> PersonContainer ds = app.getDataSource(); <del> for (Iterator<Person> it = ds.getItemIds().iterator(); it.hasNext();) { <del> String city = (it.next()).getCity(); <del> cities.addItem(city); <del> } <add> /* Populate cities select using the cities in the data container */ <add> PersonContainer ds = app.getDataSource(); <add> for (Iterator<Person> it = ds.getItemIds().iterator(); it.hasNext();) { <add> String city = (it.next()).getCity(); <add> cities.addItem(city); <add> } <ide> <del> /* <del> * Field factory for overriding how the component for city selection is <del> * created <del> */ <del> setFormFieldFactory(new DefaultFieldFactory() { <del> @Override <del> public Field createField(Item item, Object propertyId, <del> Component uiContext) { <del> if (propertyId.equals("city")) { <del> cities.setWidth("200px"); <del> return cities; <del> } <add> /* <add> * Field factory for overriding how the component for city selection is <add> * created <add> */ <add> setFormFieldFactory(new DefaultFieldFactory() { <add> @Override <add> public Field createField(Item item, Object propertyId, <add> Component uiContext) { <add> if (propertyId.equals("city")) { <add> cities.setWidth("200px"); <add> return cities; <add> } <ide> <del> Field field = super.createField(item, propertyId, uiContext); <del> if (propertyId.equals("postalCode")) { <del> TextField tf = (TextField) field; <del> /* <del> * We do not want to display "null" to the user when the <del> * field is empty <del> */ <del> tf.setNullRepresentation(""); <add> Field field = super.createField(item, propertyId, uiContext); <add> if (propertyId.equals("postalCode")) { <add> TextField tf = (TextField) field; <add> /* <add> * We do not want to display "null" to the user when the <add> * field is empty <add> */ <add> tf.setNullRepresentation(""); <ide> <del> /* Add a validator for postalCode and make it required */ <del> tf.addValidator(new PostalCodeValidator()); <del> tf.setRequired(true); <del> } else if (propertyId.equals("email")) { <del> /* Add a validator for email and make it required */ <del> field.addValidator(new EmailValidator()); <del> field.setRequired(true); <add> /* Add a validator for postalCode and make it required */ <add> tf.addValidator(new PostalCodeValidator()); <add> tf.setRequired(true); <add> } else if (propertyId.equals("email")) { <add> /* Add a validator for email and make it required */ <add> field.addValidator(new EmailValidator()); <add> field.setRequired(true); <ide> <del> } <add> } <ide> <del> field.setWidth("200px"); <del> return field; <del> } <del> }); <del> } <add> field.setWidth("200px"); <add> return field; <add> } <add> }); <add> } <ide> <del> public void buttonClick(ClickEvent event) { <del> Button source = event.getButton(); <add> public void buttonClick(ClickEvent event) { <add> Button source = event.getButton(); <ide> <del> if (source == save) { <del> /* If the given input is not valid there is no point in continuing */ <del> if (!isValid()) { <del> return; <del> } <add> if (source == save) { <add> /* If the given input is not valid there is no point in continuing */ <add> if (!isValid()) { <add> return; <add> } <ide> <del> commit(); <del> if (newContactMode) { <del> /* We need to add the new person to the container */ <del> Item addedItem = app.getDataSource().addItem(newPerson); <del> /* <del> * We must update the form to use the Item from our datasource <del> * as we are now in edit mode (no longer in add mode) <del> */ <del> setItemDataSource(addedItem); <add> commit(); <add> if (newContactMode) { <add> /* We need to add the new person to the container */ <add> Item addedItem = app.getDataSource().addItem(newPerson); <add> /* <add> * We must update the form to use the Item from our datasource <add> * as we are now in edit mode (no longer in add mode) <add> */ <add> setItemDataSource(addedItem); <ide> <del> newContactMode = false; <del> } <del> setReadOnly(true); <del> } else if (source == cancel) { <del> if (newContactMode) { <del> newContactMode = false; <del> /* Clear the form and make it invisible */ <del> setItemDataSource(null); <del> } else { <del> discard(); <del> } <del> setReadOnly(true); <del> } else if (source == edit) { <del> setReadOnly(false); <del> } <del> } <add> newContactMode = false; <add> } <add> setReadOnly(true); <add> } else if (source == cancel) { <add> if (newContactMode) { <add> newContactMode = false; <add> /* Clear the form and make it invisible */ <add> setItemDataSource(null); <add> } else { <add> discard(); <add> } <add> setReadOnly(true); <add> } else if (source == edit) { <add> setReadOnly(false); <add> } <add> } <ide> <del> @Override <del> public void setItemDataSource(Item newDataSource) { <del> newContactMode = false; <add> @Override <add> public void setItemDataSource(Item newDataSource) { <add> newContactMode = false; <ide> <del> if (newDataSource != null) { <del> List<Object> orderedProperties = Arrays <del> .asList(PersonContainer.NATURAL_COL_ORDER); <del> super.setItemDataSource(newDataSource, orderedProperties); <add> if (newDataSource != null) { <add> List<Object> orderedProperties = Arrays <add> .asList(PersonContainer.NATURAL_COL_ORDER); <add> super.setItemDataSource(newDataSource, orderedProperties); <ide> <del> setReadOnly(true); <del> getFooter().setVisible(true); <del> } else { <del> super.setItemDataSource(null); <del> getFooter().setVisible(false); <del> } <del> } <add> setReadOnly(true); <add> getFooter().setVisible(true); <add> } else { <add> super.setItemDataSource(null); <add> getFooter().setVisible(false); <add> } <add> } <ide> <del> @Override <del> public void setReadOnly(boolean readOnly) { <del> super.setReadOnly(readOnly); <del> save.setVisible(!readOnly); <del> cancel.setVisible(!readOnly); <del> edit.setVisible(readOnly); <del> } <add> @Override <add> public void setReadOnly(boolean readOnly) { <add> super.setReadOnly(readOnly); <add> save.setVisible(!readOnly); <add> cancel.setVisible(!readOnly); <add> edit.setVisible(readOnly); <add> } <ide> <del> public void addContact() { <del> // Create a temporary item for the form <del> newPerson = new Person(); <del> setItemDataSource(new BeanItem(newPerson)); <del> newContactMode = true; <del> setReadOnly(false); <del> } <add> public void addContact() { <add> // Create a temporary item for the form <add> newPerson = new Person(); <add> setItemDataSource(new BeanItem(newPerson)); <add> newContactMode = true; <add> setReadOnly(false); <add> } <ide> <ide> }
JavaScript
mit
1ce9f5b510c32a8b0fc168eb13c980943660a7b7
0
akg1852/CheezeBot,akg1852/CheezeBot
var post = require("./flowdock.js").post; var sqlite3 = require('sqlite3').verbose(); var utility = module.exports = { // parse time string parseTime: function(timeString) { var d = new Date(); if (typeof(timeString) == "string") { d.setHours(parseInt(timeString)); d.setMinutes(parseInt(timeString.split(":")[1])); d.setSeconds(0); d.setMilliseconds(0); if (d < new Date()) d.setHours(d.getHours() + 24); } return d; }, // parse duration string parseDuration: function(durationString) { var d = new Date(); if (typeof(durationString) == "string") { var duration = durationString.match(/^([\d.]+)\s*(second(?:s?)|minute(?:s?)|hour(?:s?)|day(?:s?))$/i) || []; var value = parseFloat(duration[1]); var units = duration[2]; if (value && units) { if (units.indexOf("day") != -1) d.setDate(d.getDate() + value); else if (units.indexOf("hour") != -1) d.setHours(d.getHours() + value); else if (units.indexOf("minute") != -1) d.setMinutes(d.getMinutes() + value); else if (units.indexOf("second") != -1) d.setSeconds(d.getSeconds() + value); else if (d < new Date()) d.setHours(d.getHours() + 24); } d.setSeconds(0); d.setMilliseconds(0); } return d; }, // format unix time as time string formatTime: function(time) { var t = new Date(time); return t.getHours() + ":" + ("0" + t.getMinutes()).substr(-2); }, // pad string to length pad: function(len, str) { while (str.length < len) str += " "; return str; }, // send an email email: function(email, context, callback) { require('nodemailer').createTransport().sendMail(email, function(error, info) { if (!error) { var result = (info.rejected.length > 0) ? "Failed to send email" : "Email sent"; if (context) post(result, context, callback); else { console.log(result); if (callback) callback(); } } else { if (context) post("Unable to send email", context); console.error("Error sending email: " + JSON.stringify(error) + "\n"); if (callback) callback(); } }); }, // connect to db dbConnect: function(callback) { var db = new sqlite3.Database('data.db'); callback(db); db.close(); }, }
utility.js
var post = require("./flowdock.js").post; var sqlite3 = require('sqlite3').verbose(); var utility = module.exports = { // parse time string parseTime: function(timeString) { var d = new Date(); if (typeof(timeString) == "string") { d.setHours(parseInt(timeString)); d.setMinutes(parseInt(timeString.split(":")[1])); d.setSeconds(0); d.setMilliseconds(0); if (d < new Date()) d.setHours(d.getHours() + 24); } return d; }, // parse duration string parseDuration: function(durationString) { var d = new Date(); if (typeof(durationString) == "string") { var duration = durationString.match(/^([\d.]+)\s*(second(?:s?)|minute(?:s?)|hour(?:s?)|day(?:s?))$/i) || []; var value = parseFloat(duration[1]); var units = duration[2]; if (value && units) { if (units.indexOf("day") != -1) d.setDate(d.getDate() + value); else if (units.indexOf("hour") != -1) d.setHours(d.getHours() + value); else if (units.indexOf("minute") != -1) d.setMinutes(d.getMinutes() + value); else if (units.indexOf("second") != -1) d.setSeconds(d.getSeconds() + value); else if (d < new Date()) d.setHours(d.getHours() + 24); } d.setSeconds(0); d.setMilliseconds(0); } return d; }, // format unix time as time string formatTime: function(time) { var t = new Date(time); return t.getHours() + ":" + ("0" + t.getMinutes()).substr(-2); }, // pad string to length pad: function(len, str) { while (str.length < len) str += " "; return str; }, // send an email email: function(email, context, callback) { require('nodemailer').createTransport().sendMail(email, function(error, info) { if (!error) { var result = (info.rejected.length > 0) ? "Failed to send email" : "Email sent"; if (context) post(result, context); else console.log(result); } else { if (context) post("Unable to send email", context); console.error("Error sending email: " + JSON.stringify(error) + "\n"); if (callback) callback(); } }); }, // connect to db dbConnect: function(callback) { var db = new sqlite3.Database('data.db'); callback(db); db.close(); }, }
fix callbacks in email utility method
utility.js
fix callbacks in email utility method
<ide><path>tility.js <ide> require('nodemailer').createTransport().sendMail(email, function(error, info) { <ide> if (!error) { <ide> var result = (info.rejected.length > 0) ? "Failed to send email" : "Email sent"; <del> if (context) post(result, context); <del> else console.log(result); <add> if (context) post(result, context, callback); <add> else { <add> console.log(result); <add> if (callback) callback(); <add> } <ide> } <ide> else { <ide> if (context) post("Unable to send email", context);
Java
apache-2.0
28ef52f48d36efc312f0d06475e5dacdc226a187
0
bitstorm/wicket,klopfdreh/wicket,klopfdreh/wicket,dashorst/wicket,mosoft521/wicket,astrapi69/wicket,martin-g/wicket-osgi,zwsong/wicket,astrapi69/wicket,mafulafunk/wicket,martin-g/wicket-osgi,apache/wicket,astrapi69/wicket,freiheit-com/wicket,zwsong/wicket,apache/wicket,topicusonderwijs/wicket,freiheit-com/wicket,selckin/wicket,mafulafunk/wicket,topicusonderwijs/wicket,selckin/wicket,bitstorm/wicket,selckin/wicket,mosoft521/wicket,apache/wicket,aldaris/wicket,bitstorm/wicket,dashorst/wicket,aldaris/wicket,apache/wicket,AlienQueen/wicket,aldaris/wicket,astrapi69/wicket,selckin/wicket,topicusonderwijs/wicket,mosoft521/wicket,freiheit-com/wicket,AlienQueen/wicket,mafulafunk/wicket,zwsong/wicket,martin-g/wicket-osgi,aldaris/wicket,bitstorm/wicket,klopfdreh/wicket,apache/wicket,topicusonderwijs/wicket,freiheit-com/wicket,dashorst/wicket,dashorst/wicket,klopfdreh/wicket,AlienQueen/wicket,AlienQueen/wicket,bitstorm/wicket,topicusonderwijs/wicket,klopfdreh/wicket,aldaris/wicket,dashorst/wicket,zwsong/wicket,freiheit-com/wicket,AlienQueen/wicket,selckin/wicket,mosoft521/wicket,mosoft521/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.markup.html.border; import org.apache.wicket.Component; import org.apache.wicket.MarkupContainer; import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.IMarkupFragment; import org.apache.wicket.markup.MarkupElement; import org.apache.wicket.markup.MarkupException; import org.apache.wicket.markup.MarkupFragment; import org.apache.wicket.markup.MarkupStream; import org.apache.wicket.markup.TagUtils; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.panel.BorderMarkupSourcingStrategy; import org.apache.wicket.markup.html.panel.IMarkupSourcingStrategy; import org.apache.wicket.markup.parser.XmlTag.TagType; import org.apache.wicket.markup.parser.filter.WicketTagIdentifier; import org.apache.wicket.markup.resolver.IComponentResolver; import org.apache.wicket.model.IModel; import org.apache.wicket.util.lang.Args; /** * A border component has associated markup which is drawn and determines placement of markup and/or * components nested within the border component. * <p> * The portion of the border's associated markup file which is to be used in rendering the border is * denoted by a &lt;wicket:border&gt; tag. The children of the border component instance are then * inserted into this markup, replacing the first &lt;wicket:body&gt; tag in the border's associated * markup. * <p> * For example, if a border's associated markup looked like this: * * <pre> * &lt;html&gt; * &lt;body&gt; * &lt;wicket:border&gt; * First &lt;wicket:body/&gt; Last * &lt;/wicket:border&gt; * &lt;/body&gt; * &lt;/html&gt; * </pre> * * And the border was used on a page like this: * * <pre> * &lt;html&gt; * &lt;body&gt; * &lt;span wicket:id = &quot;myBorder&quot;&gt; * Middle * &lt;/span&gt; * &lt;/body&gt; * &lt;/html&gt; * </pre> * * Then the resulting HTML would look like this: * * <pre> * &lt;html&gt; * &lt;body&gt; * First Middle Last * &lt;/body&gt; * &lt;/html&gt; * </pre> * * In other words, the body of the myBorder component is substituted into the border's associated * markup at the position indicated by the &lt;wicket:body&gt; tag. * <p> * Regarding &lt;wicket:body/&gt; you have two options. Either use &lt;wicket:body/&gt; (open-close * tag) which will automatically be expanded to &lt;wicket:body&gt;body content&lt;/wicket:body&gt; * or use &lt;wicket:body&gt;preview region&lt;/wicket:body&gt; in your border's markup. The preview * region (everything in between the open and close tag) will automatically be removed. * <p> * The border body container will automatically be created for you and added to the border * container. It is accessible via {@link #getBodyContainer()}. In case the body markup is not an * immediate child of border (see the example below), then you must use code such as * <code>someContainer.add(getBodyContainer())</code> to add the body component to the correct * container. * * <pre> * &lt;html&gt; * &lt;body&gt; * &lt;wicket:border&gt; * &lt;span wicket:id=&quot;someContainer&quot;&gt; * &lt;wicket:body/&gt; * &lt;/span&gt; * &lt;/wicket:border&gt; * &lt;/body&gt; * &lt;/html&gt; * </pre> * * The component "someContainer" in the previous example must be added to the border, and not the * body, which is achieved via {@link #addToBorder(Component...)}. * <p/> * {@link #add(Component...)} is an alias to {@code getBodyContainer().add(Component...)} and will * add a child component to the border body as shown in the example below. * * <pre> * &lt;html&gt; * &lt;body&gt; * &lt;span wicket:id = &quot;myBorder&quot;&gt; * &lt;input wicket:id=&quot;name&quot/;&gt; * &lt;/span&gt; * &lt;/body&gt; * &lt;/html&gt; * </pre> * * This implementation does not apply any magic with respect to component handling. In doubt think * simple. But everything you can do with a MarkupContainer or Component, you can do with a Border * or its Body as well. * <p/> * * Other methods like {@link #remove()}, {@link #get(int)}, {@link #iterator()}, etc. are not * aliased to work on the border's body and attention must be paid when they need to be used. * * @see PanelBorder An alternative implementation based on Panel * @see BorderBehavior A behavior which add (raw) markup before and after the component * * @author Jonathan Locke * @author Juergen Donnerstag */ public abstract class Border extends WebMarkupContainer implements IComponentResolver { private static final long serialVersionUID = 1L; /** */ public static final String BODY = "body"; /** */ public static final String BORDER = "border"; static { // register "wicket:body" and "wicket:border" WicketTagIdentifier.registerWellKnownTagName(BORDER); WicketTagIdentifier.registerWellKnownTagName(BODY); } /** The body component associated with <wicket:body> */ private final BorderBodyContainer body; /** * @see org.apache.wicket.Component#Component(String) */ public Border(final String id) { this(id, null); } /** * @see org.apache.wicket.Component#Component(String, IModel) */ public Border(final String id, final IModel<?> model) { super(id, model); body = new BorderBodyContainer(id + "_" + BODY); addToBorder(body); } /** * @return The border body container */ public final BorderBodyContainer getBodyContainer() { return body; } /** * This is for all components which have been added to the markup like this: * * <pre> * &lt;span wicket:id="myBorder"&gt; * &lt;input wicket:id="text1" .. /&gt; * ... * &lt;/span&gt; * * </pre> * * Whereas {@link #addToBorder(Component...)} will add a component associated with the following * markup: * * <pre> * &lt;wicket:border&gt; * &lt;form wicket:id="myForm" .. &gt; * &lt;wicket:body/&gt; * &lt;/form&gt; * &lt;/wicket:border&gt; * * </pre> * * @see org.apache.wicket.MarkupContainer#add(org.apache.wicket.Component[]) */ @Override public Border add(final Component... children) { getBodyContainer().add(children); return this; } @Override public Border addOrReplace(final Component... children) { getBodyContainer().addOrReplace(children); return this; } @Override public Border remove(final Component component) { getBodyContainer().remove(component); return this; } @Override public Border remove(final String id) { getBodyContainer().remove(id); return this; } @Override public Border removeAll() { getBodyContainer().removeAll(); return this; } @Override public Border replace(final Component replacement) { getBodyContainer().replace(replacement); return this; } /** * Adds children components to the Border itself * * @param children * the children components to add * @return this */ public Border addToBorder(final Component... children) { super.add(children); return this; } /** * Removes child from the Border itself * * @param child * @return {@code this} */ public Border removeFromBorder(final Component child) { super.remove(child); return this; } /** * Replaces component in the Border itself * * @param component * @return {@code this} */ public Border replaceInBorder(final Component component) { super.replace(component); return this; } /** * {@inheritDoc} */ public Component resolve(final MarkupContainer container, final MarkupStream markupStream, final ComponentTag tag) { // make sure nested borders are resolved properly if (body.rendering == false) { // We are only interested in border body tags. The tag ID actually is irrelevant since // always preset with the same default if (TagUtils.isWicketBodyTag(tag)) { return body; } } return null; } /** * {@inheritDoc} */ @Override protected IMarkupSourcingStrategy newMarkupSourcingStrategy() { return new BorderMarkupSourcingStrategy(); } /** * Search for the child markup in the file associated with the Border. The child markup must in * between the &lt;wicket:border&gt; tags. */ @Override public IMarkupFragment getMarkup(final Component child) { // Border require an associated markup resource file IMarkupFragment markup = getAssociatedMarkup(); if (markup == null) { throw new MarkupException("Unable to find associated markup file for Border: " + this.toString()); } // Find <wicket:border> IMarkupFragment borderMarkup = null; for (int i = 0; i < markup.size(); i++) { MarkupElement elem = markup.get(i); if (TagUtils.isWicketBorderTag(elem)) { borderMarkup = new MarkupFragment(markup, i); break; } } if (borderMarkup == null) { throw new MarkupException(markup.getMarkupResourceStream(), "Unable to find <wicket:border> tag in associated markup file for Border: " + this.toString()); } // If child == null, return the markup fragment starting with the <wicket:border> tag if (child == null) { return borderMarkup; } // Is child == BorderBody? if (child == body) { // Get the <wicket:body> markup return body.getMarkup(); } // Find the markup for the child component IMarkupFragment childMarkup = borderMarkup.find(child.getId()); if (childMarkup != null) { return childMarkup; } return ((BorderMarkupSourcingStrategy)getMarkupSourcingStrategy()).findMarkupInAssociatedFileHeader( this, child); } /** * The container to be associated with the &lt;wicket:body&gt; tag */ public class BorderBodyContainer extends WebMarkupContainer { private static final long serialVersionUID = 1L; /** The markup */ private transient IMarkupFragment markup; // properly resolve borders added to borders protected boolean rendering; /** * Constructor * * @param id */ public BorderBodyContainer(final String id) { super(id); } @Override protected void onComponentTag(final ComponentTag tag) { // Convert open-close to open-body-close if (tag.isOpenClose()) { tag.setType(TagType.OPEN); tag.setModified(true); } super.onComponentTag(tag); } @Override public void onComponentTagBody(final MarkupStream markupStream, final ComponentTag openTag) { // skip the <wicket:body> body if (markupStream.getPreviousTag().isOpen()) { // Only RawMarkup is allowed within the preview region, // which gets stripped from output markupStream.skipRawMarkup(); } // Get the <span wicket:id="myBorder"> markup and render that instead IMarkupFragment markup = Border.this.getMarkup(); MarkupStream stream = new MarkupStream(markup); ComponentTag tag = stream.getTag(); stream.next(); super.onComponentTagBody(stream, tag); } @Override protected void onRender() { rendering = true; try { super.onRender(); } finally { rendering = false; } } /** * Get the &lt;wicket:body&gt; markup from the body's parent container */ @Override public IMarkupFragment getMarkup() { if (markup == null) { markup = findByName(getParent().getMarkup(null), BODY); } return markup; } /** * Search for &lt;wicket:'name' ...&gt; on the same level, but ignoring other "transparent" * tags such as &lt;wicket:enclosure&gt; etc. * * @param markup * @param name * @return null, if not found */ private final IMarkupFragment findByName(final IMarkupFragment markup, final String name) { Args.notEmpty(name, "name"); MarkupStream stream = new MarkupStream(markup); // Skip any raw markup stream.skipUntil(ComponentTag.class); // Skip <wicket:border> stream.next(); while (stream.skipUntil(ComponentTag.class)) { ComponentTag tag = stream.getTag(); if (tag.isOpen() || tag.isOpenClose()) { if (TagUtils.isWicketBodyTag(tag)) { return stream.getMarkupFragment(); } } stream.next(); } return null; } /** * Get the child markup which must be in between the &lt;span wicktet:id="myBorder"&gt; tags */ @Override public IMarkupFragment getMarkup(final Component child) { IMarkupFragment markup = Border.this.getMarkup(); if (markup == null) { return null; } if (child == null) { return markup; } return markup.find(child.getId()); } } }
wicket-core/src/main/java/org/apache/wicket/markup/html/border/Border.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.markup.html.border; import org.apache.wicket.Component; import org.apache.wicket.MarkupContainer; import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.IMarkupFragment; import org.apache.wicket.markup.MarkupElement; import org.apache.wicket.markup.MarkupException; import org.apache.wicket.markup.MarkupFragment; import org.apache.wicket.markup.MarkupStream; import org.apache.wicket.markup.TagUtils; import org.apache.wicket.markup.html.TransparentWebMarkupContainer; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.panel.BorderMarkupSourcingStrategy; import org.apache.wicket.markup.html.panel.IMarkupSourcingStrategy; import org.apache.wicket.markup.parser.XmlTag.TagType; import org.apache.wicket.markup.parser.filter.WicketTagIdentifier; import org.apache.wicket.markup.resolver.IComponentResolver; import org.apache.wicket.model.IModel; import org.apache.wicket.util.lang.Args; /** * A border component has associated markup which is drawn and determines placement of markup and/or * components nested within the border component. * <p> * The portion of the border's associated markup file which is to be used in rendering the border is * denoted by a &lt;wicket:border&gt; tag. The children of the border component instance are then * inserted into this markup, replacing the first &lt;wicket:body&gt; tag in the border's associated * markup. * <p> * For example, if a border's associated markup looked like this: * * <pre> * &lt;html&gt; * &lt;body&gt; * &lt;wicket:border&gt; * First &lt;wicket:body/&gt; Last * &lt;/wicket:border&gt; * &lt;/body&gt; * &lt;/html&gt; * </pre> * * And the border was used on a page like this: * * <pre> * &lt;html&gt; * &lt;body&gt; * &lt;span wicket:id = &quot;myBorder&quot;&gt; * Middle * &lt;/span&gt; * &lt;/body&gt; * &lt;/html&gt; * </pre> * * Then the resulting HTML would look like this: * * <pre> * &lt;html&gt; * &lt;body&gt; * First Middle Last * &lt;/body&gt; * &lt;/html&gt; * </pre> * * In other words, the body of the myBorder component is substituted into the border's associated * markup at the position indicated by the &lt;wicket:body&gt; tag. * <p> * Regarding &lt;wicket:body/&gt; you have two options. Either use &lt;wicket:body/&gt; (open-close * tag) which will automatically be expanded to &lt;wicket:body&gt;body content&lt;/wicket:body&gt; * or use &lt;wicket:body&gt;preview region&lt;/wicket:body&gt; in your border's markup. The preview * region (everything in between the open and close tag) will automatically be removed. * <p> * The border body container will automatically be created for you and added to the border * container. It is accessible via {@link #getBodyContainer()}. In case the body markup is not an * immediate child of border (see the example below), then you must use code such as * <code>someContainer.add(getBodyContainer())</code> to add the body component to the correct * container. * * <pre> * &lt;html&gt; * &lt;body&gt; * &lt;wicket:border&gt; * &lt;span wicket:id=&quot;someContainer&quot;&gt; * &lt;wicket:body/&gt; * &lt;/span&gt; * &lt;/wicket:border&gt; * &lt;/body&gt; * &lt;/html&gt; * </pre> * * The component "someContainer" in the previous example must be added to the border, and not the * body, which is achieved via {@link #addToBorder(Component...)}. * <p/> * {@link #add(Component...)} is an alias to {@code getBodyContainer().add(Component...)} and will * add a child component to the border body as shown in the example below. * * <pre> * &lt;html&gt; * &lt;body&gt; * &lt;span wicket:id = &quot;myBorder&quot;&gt; * &lt;input wicket:id=&quot;name&quot/;&gt; * &lt;/span&gt; * &lt;/body&gt; * &lt;/html&gt; * </pre> * * This implementation does not apply any magic with respect to component handling. In doubt think * simple. But everything you can do with a MarkupContainer or Component, you can do with a Border * or its Body as well. * <p/> * * Other methods like {@link #remove()}, {@link #get(int)}, {@link #iterator()}, etc. are not * aliased to work on the border's body and attention must be paid when they need to be used. * * @see PanelBorder An alternative implementation based on Panel * @see BorderBehavior A behavior which add (raw) markup before and after the component * * @author Jonathan Locke * @author Juergen Donnerstag */ public abstract class Border extends WebMarkupContainer implements IComponentResolver { private static final long serialVersionUID = 1L; /** */ public static final String BODY = "body"; /** */ public static final String BORDER = "border"; static { // register "wicket:body" and "wicket:border" WicketTagIdentifier.registerWellKnownTagName(BORDER); WicketTagIdentifier.registerWellKnownTagName(BODY); } /** The body component associated with <wicket:body> */ private final BorderBodyContainer body; /** * @see org.apache.wicket.Component#Component(String) */ public Border(final String id) { this(id, null); } /** * @see org.apache.wicket.Component#Component(String, IModel) */ public Border(final String id, final IModel<?> model) { super(id, model); body = new BorderBodyContainer(id + "_" + BODY); addToBorder(body); } /** * @return The border body container */ public final BorderBodyContainer getBodyContainer() { return body; } /** * This is for all components which have been added to the markup like this: * * <pre> * &lt;span wicket:id="myBorder"&gt; * &lt;input wicket:id="text1" .. /&gt; * ... * &lt;/span&gt; * * </pre> * * Whereas {@link #addToBorder(Component...)} will add a component associated with the following * markup: * * <pre> * &lt;wicket:border&gt; * &lt;form wicket:id="myForm" .. &gt; * &lt;wicket:body/&gt; * &lt;/form&gt; * &lt;/wicket:border&gt; * * </pre> * * @see org.apache.wicket.MarkupContainer#add(org.apache.wicket.Component[]) */ @Override public Border add(final Component... children) { getBodyContainer().add(children); return this; } @Override public Border addOrReplace(final Component... children) { getBodyContainer().addOrReplace(children); return this; } @Override public Border remove(final Component component) { getBodyContainer().remove(component); return this; } @Override public Border remove(final String id) { getBodyContainer().remove(id); return this; } @Override public Border removeAll() { getBodyContainer().removeAll(); return this; } @Override public Border replace(final Component replacement) { getBodyContainer().replace(replacement); return this; } /** * Adds children components to the Border itself * * @param children * the children components to add * @return this */ public Border addToBorder(final Component... children) { super.add(children); return this; } /** * Removes child from the Border itself * * @param child * @return {@code this} */ public Border removeFromBorder(final Component child) { super.remove(child); return this; } /** * Replaces component in the Border itself * * @param component * @return {@code this} */ public Border replaceInBorder(final Component component) { super.replace(component); return this; } /** * {@inheritDoc} */ public Component resolve(final MarkupContainer container, final MarkupStream markupStream, final ComponentTag tag) { // make sure nested borders are resolved properly if (body.rendering == false) { // We are only interested in border body tags. The tag ID actually is irrelevant since // always preset with the same default if (TagUtils.isWicketBodyTag(tag)) { return body; } } return null; } /** * {@inheritDoc} */ @Override protected IMarkupSourcingStrategy newMarkupSourcingStrategy() { return new BorderMarkupSourcingStrategy(); } /** * Search for the child markup in the file associated with the Border. The child markup must in * between the &lt;wicket:border&gt; tags. */ @Override public IMarkupFragment getMarkup(final Component child) { // Border require an associated markup resource file IMarkupFragment markup = getAssociatedMarkup(); if (markup == null) { throw new MarkupException("Unable to find associated markup file for Border: " + this.toString()); } // Find <wicket:border> IMarkupFragment borderMarkup = null; for (int i = 0; i < markup.size(); i++) { MarkupElement elem = markup.get(i); if (TagUtils.isWicketBorderTag(elem)) { borderMarkup = new MarkupFragment(markup, i); break; } } if (borderMarkup == null) { throw new MarkupException(markup.getMarkupResourceStream(), "Unable to find <wicket:border> tag in associated markup file for Border: " + this.toString()); } // If child == null, return the markup fragment starting with the <wicket:border> tag if (child == null) { return borderMarkup; } // Is child == BorderBody? if (child == body) { // Get the <wicket:body> markup return body.getMarkup(); } // Find the markup for the child component IMarkupFragment childMarkup = borderMarkup.find(child.getId()); if (childMarkup != null) { return childMarkup; } return ((BorderMarkupSourcingStrategy)getMarkupSourcingStrategy()).findMarkupInAssociatedFileHeader( this, child); } /** * The container to be associated with the &lt;wicket:body&gt; tag */ public class BorderBodyContainer extends TransparentWebMarkupContainer { private static final long serialVersionUID = 1L; /** The markup */ private transient IMarkupFragment markup; // properly resolve borders added to borders protected boolean rendering; /** * Constructor * * @param id */ public BorderBodyContainer(final String id) { super(id); } @Override protected void onComponentTag(final ComponentTag tag) { // Convert open-close to open-body-close if (tag.isOpenClose()) { tag.setType(TagType.OPEN); tag.setModified(true); } super.onComponentTag(tag); } @Override public void onComponentTagBody(final MarkupStream markupStream, final ComponentTag openTag) { // skip the <wicket:body> body if (markupStream.getPreviousTag().isOpen()) { // Only RawMarkup is allowed within the preview region, // which gets stripped from output markupStream.skipRawMarkup(); } // Get the <span wicket:id="myBorder"> markup and render that instead IMarkupFragment markup = Border.this.getMarkup(); MarkupStream stream = new MarkupStream(markup); ComponentTag tag = stream.getTag(); stream.next(); super.onComponentTagBody(stream, tag); } @Override protected void onRender() { rendering = true; try { super.onRender(); } finally { rendering = false; } } /** * Get the &lt;wicket:body&gt; markup from the body's parent container */ @Override public IMarkupFragment getMarkup() { if (markup == null) { markup = findByName(getParent().getMarkup(null), BODY); } return markup; } /** * Search for &lt;wicket:'name' ...&gt; on the same level, but ignoring other "transparent" * tags such as &lt;wicket:enclosure&gt; etc. * * @param markup * @param name * @return null, if not found */ private final IMarkupFragment findByName(final IMarkupFragment markup, final String name) { Args.notEmpty(name, "name"); MarkupStream stream = new MarkupStream(markup); // Skip any raw markup stream.skipUntil(ComponentTag.class); // Skip <wicket:border> stream.next(); while (stream.skipUntil(ComponentTag.class)) { ComponentTag tag = stream.getTag(); if (tag.isOpen() || tag.isOpenClose()) { if (TagUtils.isWicketBodyTag(tag)) { return stream.getMarkupFragment(); } } stream.next(); } return null; } /** * Get the child markup which must be in between the &lt;span wicktet:id="myBorder"&gt; tags */ @Override public IMarkupFragment getMarkup(final Component child) { IMarkupFragment markup = Border.this.getMarkup(); if (markup == null) { return null; } if (child == null) { return markup; } return markup.find(child.getId()); } } }
BorderBodyContainer doesn't have to be a transparent resolver (IComponentResolver) git-svn-id: 5a74b5304d8e7e474561603514f78b697e5d94c4@1148922 13f79535-47bb-0310-9956-ffa450edef68
wicket-core/src/main/java/org/apache/wicket/markup/html/border/Border.java
BorderBodyContainer doesn't have to be a transparent resolver (IComponentResolver)
<ide><path>icket-core/src/main/java/org/apache/wicket/markup/html/border/Border.java <ide> import org.apache.wicket.markup.MarkupFragment; <ide> import org.apache.wicket.markup.MarkupStream; <ide> import org.apache.wicket.markup.TagUtils; <del>import org.apache.wicket.markup.html.TransparentWebMarkupContainer; <ide> import org.apache.wicket.markup.html.WebMarkupContainer; <ide> import org.apache.wicket.markup.html.panel.BorderMarkupSourcingStrategy; <ide> import org.apache.wicket.markup.html.panel.IMarkupSourcingStrategy; <ide> /** <ide> * The container to be associated with the &lt;wicket:body&gt; tag <ide> */ <del> public class BorderBodyContainer extends TransparentWebMarkupContainer <add> public class BorderBodyContainer extends WebMarkupContainer <ide> { <ide> private static final long serialVersionUID = 1L; <ide>
Java
bsd-3-clause
c607ed455a98025b344510e4560641e316d166bf
0
TeamParadise/Trevor
/* * Operator Interface methods */ package net.pvschools.robotics.javabot.practice; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.buttons.Button; import edu.wpi.first.wpilibj.buttons.JoystickButton; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import net.pvschools.robotics.javabot.practice.commands.PopFeedRollerSpeed; import net.pvschools.robotics.javabot.practice.commands.PushFeedRollerSpeed; import net.pvschools.robotics.javabot.practice.commands.StartPickup; import net.pvschools.robotics.javabot.practice.commands.StopPickup; import net.pvschools.robotics.javabot.practice.commands.Shoot; import net.pvschools.robotics.javabot.practice.commands.piston.CloseCatcher; import net.pvschools.robotics.javabot.practice.commands.piston.CloseLatch; import net.pvschools.robotics.javabot.practice.commands.piston.ExtendBigKicker; import net.pvschools.robotics.javabot.practice.commands.piston.ExtendLittleKicker; import net.pvschools.robotics.javabot.practice.commands.piston.ExtendPickup; import net.pvschools.robotics.javabot.practice.commands.piston.LowerRamp; import net.pvschools.robotics.javabot.practice.commands.piston.OpenCatcher; import net.pvschools.robotics.javabot.practice.commands.piston.OpenLatch; import net.pvschools.robotics.javabot.practice.commands.piston.RaiseRamp; import net.pvschools.robotics.javabot.practice.commands.piston.RetractBigKicker; import net.pvschools.robotics.javabot.practice.commands.piston.RetractLittleKicker; import net.pvschools.robotics.javabot.practice.commands.piston.RetractPickup; import net.pvschools.robotics.javabot.practice.subsystems.FeedRoller; public class OI { private static final OI instance = new OI(); private final Joystick mainJoystick = new Joystick(Map.joystickPort); /** Shoot */ private final Button button1 = new JoystickButton(mainJoystick, 1); /** Extend Feed <p> Keep extended while holding */ private final Button button2 = new JoystickButton(mainJoystick, 2); private final Button button3 = new JoystickButton(mainJoystick, 3); private final Button button5 = new JoystickButton(mainJoystick, 5); private final Button button4 = new JoystickButton(mainJoystick, 4); private final Button button6 = new JoystickButton(mainJoystick, 6); private final Button button7 = new JoystickButton(mainJoystick, 7); private final Button button8 = new JoystickButton(mainJoystick, 8); private final Button button9 = new JoystickButton(mainJoystick, 9); private final Button button10 = new JoystickButton(mainJoystick, 10); private final Button button11 = new JoystickButton(mainJoystick, 11); private final Button button12 = new JoystickButton(mainJoystick, 12); private OI() { SmartDashboard.putNumber("Dampening", .5); // Add commands to smart dashboard: SmartDashboard.putData("Open Catcher", new OpenCatcher()); SmartDashboard.putData("Close Catcher", new CloseCatcher()); SmartDashboard.putData("Raise Ramp", new RaiseRamp()); SmartDashboard.putData("Lower Ramp", new LowerRamp()); SmartDashboard.putData("Extend Pickup", new ExtendPickup()); SmartDashboard.putData("Retract Pickup", new RetractPickup()); SmartDashboard.putData("Extend Little Kicker", new ExtendLittleKicker()); SmartDashboard.putData("Retract Little Kicker", new RetractLittleKicker()); SmartDashboard.putData("Extend Big Kicker", new ExtendBigKicker()); SmartDashboard.putData("Retract Big Kicker", new RetractBigKicker()); SmartDashboard.putData("Open Latch", new OpenLatch()); SmartDashboard.putData("Close Latch", new CloseLatch()); //Button Command Initialization button2.whenPressed(new StartPickup()); button2.whenReleased(new StopPickup()); button11.whenPressed(new PushFeedRollerSpeed(FeedRoller.spewSpeed)); button11.whenReleased(new PopFeedRollerSpeed()); // private static Boolean catching; // if (button12.get()) // { // Sonar Sonar = new Sonar(Map.SonarPingChannel,Map.SonarEchoChannel); // if (Sonar.getDistanceInInches()<13 and !catching) // { // CloseCatcher Catcher = new CloseCatcher(); // Catcher.start(); // catching = true; // } else // { // catching = false; // } // } button1.whenPressed(new Shoot(button5.get())); } public double getDampening() { return SmartDashboard.getNumber("Dampening"); } public double getDriveThrottle() { return mainJoystick.getThrottle(); } public double getDriveX() { return mainJoystick.getY(); } public double getDriveY() { return mainJoystick.getX(); } public double getDriveTwist() { return mainJoystick.getTwist(); } public static OI getInstance() { return instance; } }
src/net/pvschools/robotics/javabot/practice/OI.java
/* * Operator Interface methods */ package net.pvschools.robotics.javabot.practice; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.buttons.Button; import edu.wpi.first.wpilibj.buttons.JoystickButton; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import net.pvschools.robotics.javabot.practice.commands.StartPickup; import net.pvschools.robotics.javabot.practice.commands.StopPickup; import net.pvschools.robotics.javabot.practice.commands.Shoot; import net.pvschools.robotics.javabot.practice.commands.piston.CloseCatcher; import net.pvschools.robotics.javabot.practice.commands.piston.CloseLatch; import net.pvschools.robotics.javabot.practice.commands.piston.ExtendBigKicker; import net.pvschools.robotics.javabot.practice.commands.piston.ExtendLittleKicker; import net.pvschools.robotics.javabot.practice.commands.piston.ExtendPickup; import net.pvschools.robotics.javabot.practice.commands.piston.LowerRamp; import net.pvschools.robotics.javabot.practice.commands.piston.OpenCatcher; import net.pvschools.robotics.javabot.practice.commands.piston.OpenLatch; import net.pvschools.robotics.javabot.practice.commands.piston.RaiseRamp; import net.pvschools.robotics.javabot.practice.commands.piston.RetractBigKicker; import net.pvschools.robotics.javabot.practice.commands.piston.RetractLittleKicker; import net.pvschools.robotics.javabot.practice.commands.piston.RetractPickup; import net.pvschools.robotics.javabot.practice.subsystems.Sonar; public class OI { private static final OI instance = new OI(); private final Joystick mainJoystick = new Joystick(Map.joystickPort); /** Shoot */ private final Button button1 = new JoystickButton(mainJoystick, 1); /** Extend Feed <p> Keep extended while holding */ private final Button button2 = new JoystickButton(mainJoystick, 2); /** Side Arms Down */ private final Button button3 = new JoystickButton(mainJoystick, 3); /** Side Arms Up */ private final Button button5 = new JoystickButton(mainJoystick, 5); /** Ramp Down */ private final Button button4 = new JoystickButton(mainJoystick, 4); /** Ramp Up */ private final Button button6 = new JoystickButton(mainJoystick, 6); private final Button button7 = new JoystickButton(mainJoystick, 7); private final Button button8 = new JoystickButton(mainJoystick, 8); private final Button button9 = new JoystickButton(mainJoystick, 9); private final Button button10 = new JoystickButton(mainJoystick, 10); private final Button button11 = new JoystickButton(mainJoystick, 11); /** Spew */ private final Button button12 = new JoystickButton(mainJoystick, 12); private OI() { SmartDashboard.putNumber("Dampening", .5); //Button Command Initialization button2.whenPressed(new StartPickup()); button2.whenReleased(new StopPickup()); // // button11.whenPressed(new PushFeedRollerSpeed(FeedRoller.spewSpeed)); // button11.whenReleased(new PopFeedRollerSpeed()); // private static Boolean catching; // if (button12.get()) // { // Sonar Sonar = new Sonar(Map.SonarPingChannel,Map.SonarEchoChannel); // if (Sonar.getDistanceInInches()<13 and !catching) // { // CloseCatcher Catcher = new CloseCatcher(); // Catcher.start(); // catching = true; // } else // { // catching = false; // } // } button7.whenPressed(new OpenCatcher()); button7.whenReleased(new CloseCatcher()); button8.whenPressed(new RaiseRamp()); button8.whenReleased(new LowerRamp()); button9.whenPressed(new ExtendPickup()); button9.whenReleased(new RetractPickup()); button10.whenPressed(new ExtendLittleKicker()); button10.whenReleased(new RetractLittleKicker()); button11.whenPressed(new ExtendBigKicker()); button11.whenReleased(new RetractBigKicker()); button12.whenPressed(new OpenLatch()); button12.whenReleased(new CloseLatch()); button1.whenPressed(new Shoot(button5.get())); } public double getDampening() { return SmartDashboard.getNumber("Dampening"); } public double getDriveThrottle() { return mainJoystick.getThrottle(); } public double getDriveX() { return mainJoystick.getY(); } public double getDriveY() { return mainJoystick.getX(); } public double getDriveTwist() { return mainJoystick.getTwist(); } public static OI getInstance() { return instance; } }
Add commands to smart dashboard for testing.
src/net/pvschools/robotics/javabot/practice/OI.java
Add commands to smart dashboard for testing.
<ide><path>rc/net/pvschools/robotics/javabot/practice/OI.java <ide> import edu.wpi.first.wpilibj.buttons.Button; <ide> import edu.wpi.first.wpilibj.buttons.JoystickButton; <ide> import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; <add>import net.pvschools.robotics.javabot.practice.commands.PopFeedRollerSpeed; <add>import net.pvschools.robotics.javabot.practice.commands.PushFeedRollerSpeed; <ide> import net.pvschools.robotics.javabot.practice.commands.StartPickup; <ide> import net.pvschools.robotics.javabot.practice.commands.StopPickup; <ide> import net.pvschools.robotics.javabot.practice.commands.Shoot; <ide> import net.pvschools.robotics.javabot.practice.commands.piston.RetractBigKicker; <ide> import net.pvschools.robotics.javabot.practice.commands.piston.RetractLittleKicker; <ide> import net.pvschools.robotics.javabot.practice.commands.piston.RetractPickup; <del>import net.pvschools.robotics.javabot.practice.subsystems.Sonar; <add>import net.pvschools.robotics.javabot.practice.subsystems.FeedRoller; <ide> <ide> public class OI <ide> { <ide> /** Extend Feed <p> Keep extended while holding */ <ide> private final Button button2 = new JoystickButton(mainJoystick, 2); <ide> <del> /** Side Arms Down */ <ide> private final Button button3 = new JoystickButton(mainJoystick, 3); <ide> <del> /** Side Arms Up */ <ide> private final Button button5 = new JoystickButton(mainJoystick, 5); <ide> <del> /** Ramp Down */ <ide> private final Button button4 = new JoystickButton(mainJoystick, 4); <ide> <del> /** Ramp Up */ <ide> private final Button button6 = new JoystickButton(mainJoystick, 6); <ide> <ide> private final Button button7 = new JoystickButton(mainJoystick, 7); <ide> <ide> private final Button button11 = new JoystickButton(mainJoystick, 11); <ide> <del> /** Spew */ <ide> private final Button button12 = new JoystickButton(mainJoystick, 12); <ide> <ide> private OI() <ide> { <ide> SmartDashboard.putNumber("Dampening", .5); <ide> <add> // Add commands to smart dashboard: <add> SmartDashboard.putData("Open Catcher", new OpenCatcher()); <add> SmartDashboard.putData("Close Catcher", new CloseCatcher()); <add> SmartDashboard.putData("Raise Ramp", new RaiseRamp()); <add> SmartDashboard.putData("Lower Ramp", new LowerRamp()); <add> SmartDashboard.putData("Extend Pickup", new ExtendPickup()); <add> SmartDashboard.putData("Retract Pickup", new RetractPickup()); <add> SmartDashboard.putData("Extend Little Kicker", new ExtendLittleKicker()); <add> SmartDashboard.putData("Retract Little Kicker", new RetractLittleKicker()); <add> SmartDashboard.putData("Extend Big Kicker", new ExtendBigKicker()); <add> SmartDashboard.putData("Retract Big Kicker", new RetractBigKicker()); <add> SmartDashboard.putData("Open Latch", new OpenLatch()); <add> SmartDashboard.putData("Close Latch", new CloseLatch()); <add> <ide> //Button Command Initialization <ide> button2.whenPressed(new StartPickup()); <ide> button2.whenReleased(new StopPickup()); <del>// <del>// button11.whenPressed(new PushFeedRollerSpeed(FeedRoller.spewSpeed)); <del>// button11.whenReleased(new PopFeedRollerSpeed()); <add> <add> button11.whenPressed(new PushFeedRollerSpeed(FeedRoller.spewSpeed)); <add> button11.whenReleased(new PopFeedRollerSpeed()); <add> <ide> // private static Boolean catching; <ide> // if (button12.get()) <ide> // { <ide> // } <ide> // } <ide> <del> button7.whenPressed(new OpenCatcher()); <del> button7.whenReleased(new CloseCatcher()); <del> button8.whenPressed(new RaiseRamp()); <del> button8.whenReleased(new LowerRamp()); <del> button9.whenPressed(new ExtendPickup()); <del> button9.whenReleased(new RetractPickup()); <del> button10.whenPressed(new ExtendLittleKicker()); <del> button10.whenReleased(new RetractLittleKicker()); <del> button11.whenPressed(new ExtendBigKicker()); <del> button11.whenReleased(new RetractBigKicker()); <del> button12.whenPressed(new OpenLatch()); <del> button12.whenReleased(new CloseLatch()); <del> <ide> button1.whenPressed(new Shoot(button5.get())); <del> <ide> } <ide> <ide> public double getDampening()
Java
mit
71e545e2010a615788adf03dfcf3a7693970848e
0
jeevatkm/digitalocean-api-java
/* * The MIT License * * Copyright (c) 2010-2015 Jeevanandam M. (myjeeva.com) * * 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. */ package com.myjeeva.digitalocean; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import junit.framework.TestCase; import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.myjeeva.digitalocean.common.ActionType; import com.myjeeva.digitalocean.common.ResourceType; import com.myjeeva.digitalocean.exception.DigitalOceanException; import com.myjeeva.digitalocean.exception.RequestUnsuccessfulException; import com.myjeeva.digitalocean.impl.DigitalOceanClient; import com.myjeeva.digitalocean.pojo.Account; import com.myjeeva.digitalocean.pojo.Action; import com.myjeeva.digitalocean.pojo.Actions; import com.myjeeva.digitalocean.pojo.Backup; import com.myjeeva.digitalocean.pojo.Backups; import com.myjeeva.digitalocean.pojo.Delete; import com.myjeeva.digitalocean.pojo.Domain; import com.myjeeva.digitalocean.pojo.DomainRecord; import com.myjeeva.digitalocean.pojo.DomainRecords; import com.myjeeva.digitalocean.pojo.Domains; import com.myjeeva.digitalocean.pojo.Droplet; import com.myjeeva.digitalocean.pojo.Droplets; import com.myjeeva.digitalocean.pojo.FloatingIP; import com.myjeeva.digitalocean.pojo.FloatingIPs; import com.myjeeva.digitalocean.pojo.Image; import com.myjeeva.digitalocean.pojo.Images; import com.myjeeva.digitalocean.pojo.Kernel; import com.myjeeva.digitalocean.pojo.Kernels; import com.myjeeva.digitalocean.pojo.Key; import com.myjeeva.digitalocean.pojo.Keys; import com.myjeeva.digitalocean.pojo.Neighbors; import com.myjeeva.digitalocean.pojo.Region; import com.myjeeva.digitalocean.pojo.Regions; import com.myjeeva.digitalocean.pojo.Size; import com.myjeeva.digitalocean.pojo.Sizes; import com.myjeeva.digitalocean.pojo.Snapshot; import com.myjeeva.digitalocean.pojo.Snapshots; /** * <p> * Junit Integration Test case for DigitalOcean API client wrapper methods * </p> * * <p> * <strong>Please Note:</strong> <i>Kindly through and update private variable value before using * executing this test case(s).</i> * </p> * * @author Jeevanandam M. ([email protected]) */ @Ignore // Marked as Ignore since its a Integration Test case with real values public class DigitalOceanIntegrationTest extends TestCase { private final Logger LOG = LoggerFactory.getLogger(DigitalOceanIntegrationTest.class); /** * This is testing values of my own respective to DigitalOcean account, to real-time integration * with API. So place your's for integration test case before use */ private String authTokenRW = ""; private Integer dropletIdForInfo = 10001; // to be placed before use private Integer imageId = 3445812; // Debian 7.0 x64 image id private String imageSlug = "ubuntu-12-04-x64"; private String domainName = ""; private String domainIp = "127.0.0.1"; private DigitalOcean apiClient = new DigitalOceanClient(authTokenRW); // Droplet test cases @Test public void testGetAvailableDroplets() throws DigitalOceanException, RequestUnsuccessfulException { Droplets droplets = apiClient.getAvailableDroplets(1, null); assertNotNull(droplets); assertTrue((droplets.getDroplets().size() > 0)); int i = 1; for (Droplet droplet : droplets.getDroplets()) { LOG.info(i++ + " -> " + droplet.toString()); } } @Test public void testGetAvailableKernels() throws DigitalOceanException, RequestUnsuccessfulException { Kernels kernels = apiClient.getAvailableKernels(dropletIdForInfo, 1, 20); assertNotNull(kernels); assertTrue((kernels.getKernels().size() > 0)); int i = 1; for (Kernel k : kernels.getKernels()) { LOG.info(i++ + " -> " + k.toString()); } } @Test public void testGetAvailableSnapshots() throws DigitalOceanException, RequestUnsuccessfulException { Snapshots snapshots = apiClient.getAvailableSnapshots(dropletIdForInfo, 1, 20); assertNotNull(snapshots); assertTrue((snapshots.getSnapshots().size() > 0)); for (Snapshot s : snapshots.getSnapshots()) { LOG.info(s.toString()); } } @Test public void testGetAvailableBackups() throws DigitalOceanException, RequestUnsuccessfulException { Backups backups = apiClient.getAvailableBackups(dropletIdForInfo, 1); assertNotNull(backups); assertTrue((backups.getBackups().size() > 0)); for (Backup b : backups.getBackups()) { LOG.info(b.toString()); } } @Test public void testGetDropletInfo() throws DigitalOceanException, RequestUnsuccessfulException { Droplet droplet = apiClient.getDropletInfo(dropletIdForInfo); assertNotNull(droplet); LOG.info(droplet.toString()); } @Test public void testCreateDropletByImageId() throws DigitalOceanException, RequestUnsuccessfulException { Droplet droplet = new Droplet(); droplet.setName("api-client-test-host-byid"); droplet.setSize("512mb"); droplet.setImage(new Image(1601)); droplet.setRegion(new Region("sgp1")); droplet.setEnableBackup(Boolean.TRUE); droplet.setEnableIpv6(Boolean.TRUE); droplet.setEnablePrivateNetworking(Boolean.TRUE); // Adding SSH key info List<Key> keys = new ArrayList<Key>(); keys.add(new Key(513618)); droplet.setKeys(keys); // Adding Metadata API - User Data /* * droplet .setUserData("#!/bin/bash" + "apt-get -y update" + "apt-get -y install nginx" + * "export HOSTNAME=$(curl -s http://169.254.169.254/metadata/v1/hostname)" + * "export PUBLIC_IPV4=$(curl -s http://169.254.169.254/metadata/v1/interfaces/public/0/ipv4/address)" * + "echo Droplet: $HOSTNAME, IP Address: $PUBLIC_IPV4 > /usr/share/nginx/html/index.html"); */ Droplet d = apiClient.createDroplet(droplet); assertNotNull(d); assertNotNull(d.getId()); LOG.info(d.toString()); } @Test public void testCreateDropletByImageSlug() throws DigitalOceanException, RequestUnsuccessfulException { Droplet droplet = new Droplet(); droplet.setName("api-client-test-host-byslug1"); droplet.setSize("512mb"); droplet.setImage(new Image("centos-5-8-x64")); droplet.setRegion(new Region("sgp1")); droplet.setEnableBackup(Boolean.TRUE); droplet.setEnableIpv6(Boolean.TRUE); droplet.setEnablePrivateNetworking(Boolean.TRUE); // Adding SSH key info List<Key> keys = new ArrayList<Key>(); keys.add(new Key(513618)); droplet.setKeys(keys); Droplet d = apiClient.createDroplet(droplet); assertNotNull(d); assertNotNull(d.getId()); LOG.info(d.toString()); } @Test public void testCreateDropletsByImageSlug() throws DigitalOceanException, RequestUnsuccessfulException { Droplet droplet = new Droplet(); droplet.setNames(Arrays.asList("sub-01.example.com", "sub-02.example.com")); droplet.setName("not allowed"); droplet.setSize("512mb"); droplet.setImage(new Image("ubuntu-14-04-x64")); droplet.setRegion(new Region("sgp1")); Droplets droplets = apiClient.createDroplets(droplet); assertNotNull(droplets); assertTrue((droplets.getDroplets().size() > 0)); for (Droplet d : droplets.getDroplets()) { LOG.info(d.toString()); } } @Test public void testDeleteDroplet() throws DigitalOceanException, RequestUnsuccessfulException { Delete result = apiClient.deleteDroplet(2258153); assertNotNull(result); LOG.info("Delete Request Object: " + result); } @Test public void testGetDropletNeighbors() throws DigitalOceanException, RequestUnsuccessfulException { Droplets droplets = apiClient.getDropletNeighbors(dropletIdForInfo, 1); assertNotNull(droplets); for (Droplet d : droplets.getDroplets()) { LOG.info(d.toString()); } } @Test public void testGetAllDropletNeighbors() throws DigitalOceanException, RequestUnsuccessfulException { Neighbors neighbors = apiClient.getAllDropletNeighbors(1); assertNotNull(neighbors); for (Droplet d : neighbors.getNeighbors()) { LOG.info(d.toString()); } } @Test public void testRebootDroplet() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.rebootDroplet(2258136); assertNotNull(action); LOG.info(action.toString()); } @Test public void testPowerCycleDroplet() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.rebootDroplet(2258136); assertNotNull(action); LOG.info(action.toString()); } @Test public void testShutdownDroplet() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.shutdownDroplet(4124871); // 2258168 assertNotNull(action); LOG.info(action.toString()); } @Test public void testPowerOffDroplet() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.powerOffDroplet(2258168); assertNotNull(action); LOG.info(action.toString()); } @Test public void testPowerOnDroplet() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.powerOnDroplet(2258136); assertNotNull(action); LOG.info(action.toString()); } @Test public void testResetDropletPassword() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.resetDropletPassword(2258168); assertNotNull(action); LOG.info(action.toString()); } @Test public void testResizeDroplet() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.resizeDroplet(2258136, "1gb"); assertNotNull(action); LOG.info(action.toString()); } @Test public void testTakeDropletSnapshot() throws DigitalOceanException, RequestUnsuccessfulException { // Action action = apiClient.takeDropletSnapshot(2258168, "api-client-test-snapshot1"); Action action = apiClient.takeDropletSnapshot(2258136); assertNotNull(action); LOG.info(action.toString()); } @Test public void testRestoreDroplet() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.restoreDroplet(2258168, 5489522); // Snapshot id assertNotNull(action); LOG.info(action.toString()); } @Test public void testRebuildDroplet() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.rebuildDroplet(2258136, 3445812); // Debian 7.0 x64 assertNotNull(action); LOG.info(action.toString()); } @Test public void testEnableDropletBackups() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.enableDropletBackups(9662284); assertNotNull(action); LOG.info(action.toString()); } @Test public void testDisableDropletBackups() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.disableDropletBackups(2258168); assertNotNull(action); LOG.info(action.toString()); } @Test public void testRenameDroplet() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.renameDroplet(2258168, "renamed-droplet-name-test"); assertNotNull(action); LOG.info(action.toString()); } @Test public void testChangeDropletKernel() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.changeDropletKernel(2258168, 1649); assertNotNull(action); LOG.info(action.toString()); } @Test public void testEnableDropletIpv6() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.enableDropletIpv6(2258168); assertNotNull(action); LOG.info(action.toString()); } @Test public void testEnableDropletPrivateNetworking() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.enableDropletPrivateNetworking(2258168); assertNotNull(action); LOG.info(action.toString()); } // Account Test cases @Test public void testGetAccountInfo() throws DigitalOceanException, RequestUnsuccessfulException { Account account = apiClient.getAccountInfo(); assertNotNull(account); LOG.info(account.toString()); } // Action Test cases @Test public void testGetAvailableActions() throws DigitalOceanException, RequestUnsuccessfulException { Actions actions = apiClient.getAvailableActions(2, 30); assertNotNull(actions); assertTrue((actions.getActions().size() > 0)); LOG.info(actions.getLinks().toString()); int i = 1; for (Action a : actions.getActions()) { LOG.info(i++ + " -> " + a.toString()); } } @Test public void testGetActionInfo() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.getActionInfo(28336352); assertNotNull(action); LOG.info(action.toString()); } @Test public void testGetAvailableDropletActions() throws DigitalOceanException, RequestUnsuccessfulException { Actions actions = apiClient.getAvailableDropletActions(dropletIdForInfo, 1, 20); Actions actions3 = apiClient.getAvailableDropletActions(dropletIdForInfo, 3, 20); assertNotNull(actions); assertTrue((actions.getActions().size() > 0)); assertNotNull(actions3); assertTrue((actions3.getActions().size() > 0)); for (Action a : actions.getActions()) { LOG.info(a.toString()); } } @Test public void testGetAvailableImageActions() throws DigitalOceanException, RequestUnsuccessfulException { Actions actions = apiClient.getAvailableImageActions(3794738, 1, 20); assertNotNull(actions); assertTrue((actions.getActions().size() > 0)); for (Action a : actions.getActions()) { LOG.info(a.toString()); } } @Test public void testGetAvailableFloatingIPActions() throws DigitalOceanException, RequestUnsuccessfulException { Actions actions = apiClient.getAvailableFloatingIPActions("159.203.146.100", 1, 10); LOG.info(actions.toString()); assertNotNull(actions); int i = 1; for (Action action : actions.getActions()) { LOG.info(i++ + " -> " + action.toString()); } } @Test public void testGetFloatingIPActionInfo() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.getFloatingIPActionInfo("159.203.146.100", 76697074); LOG.info(action.toString()); assertNotNull(action); } // Image test cases @Test public void testGetAvailableImages() throws DigitalOceanException, RequestUnsuccessfulException { Images images = apiClient.getAvailableImages(1, 20); assertNotNull(images); assertTrue((images.getImages().size() > 0)); for (Image img : images.getImages()) { LOG.info(img.toString()); } } @Test public void testGetAvailableImagesByDistribution() throws DigitalOceanException, RequestUnsuccessfulException { Images images = apiClient.getAvailableImages(1, 20, ActionType.DISTRIBUTION); assertNotNull(images); assertTrue((images.getImages().size() > 0)); for (Image img : images.getImages()) { LOG.info(img.toString()); } } @Test public void testGetAvailableImagesByApplication() throws DigitalOceanException, RequestUnsuccessfulException { Images images = apiClient.getAvailableImages(1, 20, ActionType.APPLICATION); assertNotNull(images); assertTrue((images.getImages().size() > 0)); for (Image img : images.getImages()) { LOG.info(img.toString()); } } @Test public void testGetAvailableImagesByIncorrrect() throws DigitalOceanException, RequestUnsuccessfulException { try { apiClient.getAvailableImages(1, 20, ActionType.BACKUP); } catch (DigitalOceanException doe) { LOG.info(doe.getMessage()); } } @Test public void testGetUserImages() throws DigitalOceanException, RequestUnsuccessfulException { Images images = apiClient.getUserImages(1, 20); assertNotNull(images); assertTrue((images.getImages().size() > 0)); for (Image img : images.getImages()) { LOG.info(img.toString()); } } @Test public void testGetImageInfoById() throws DigitalOceanException, RequestUnsuccessfulException { Image image = apiClient.getImageInfo(imageId); assertNotNull(image); LOG.info(image.toString()); } @Test public void testGetImageInfoBySlug() throws DigitalOceanException, RequestUnsuccessfulException { Image image = apiClient.getImageInfo(imageSlug); assertNotNull(image); LOG.info(image.toString()); } @Test public void testUpdateImageInfo() throws DigitalOceanException, RequestUnsuccessfulException { Image input = new Image(); input.setId(3897539); input.setName("test-myjeeva.com-before-wp-upgrade"); Image image = apiClient.updateImage(input); assertNotNull(image); LOG.info(image.toString()); } @Test public void testDeleteImage() throws DigitalOceanException, RequestUnsuccessfulException { Delete result = apiClient.deleteImage(3897539); assertNotNull(result); LOG.info("Delete Request result: " + result); } @Test public void testTransferImage() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.transferImage(5489522, "lon1"); assertNotNull(action); LOG.info(action.toString()); } @Test public void testConvertImage() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.convertImage(5489522); assertNotNull(action); LOG.info(action.toString()); } // Regions test cases @Test public void testGetAvailableRegions() throws DigitalOceanException, RequestUnsuccessfulException { Regions regions = apiClient.getAvailableRegions(1); assertNotNull(regions); assertTrue((regions.getRegions().size() > 0)); for (Region region : regions.getRegions()) { LOG.info(region.toString()); } } // Sizes test cases @Test public void testGetAvailableSizes() throws DigitalOceanException, RequestUnsuccessfulException { Sizes sizes = apiClient.getAvailableSizes(1); assertNotNull(sizes); assertTrue((sizes.getSizes().size() > 0)); for (Size size : sizes.getSizes()) { LOG.info(size.toString()); } } // Domain test cases @Test public void testGetAvailableDomains() throws DigitalOceanException, RequestUnsuccessfulException { Domains domains = apiClient.getAvailableDomains(1); assertNotNull(domains); assertTrue((domains.getDomains().size() > 0)); for (Domain d : domains.getDomains()) { LOG.info(d.toString()); } } @Test public void testGetDomainInfo() throws DigitalOceanException, RequestUnsuccessfulException { Domain domain = apiClient.getDomainInfo("jeeutil.com"); assertNotNull(domain); LOG.info(domain.toString()); } @Test public void testCreateDomain() throws DigitalOceanException, RequestUnsuccessfulException { Domain input = new Domain(domainName, domainIp); Domain domain = apiClient.createDomain(input); assertNotNull(domain); assertNotNull(domain.getName()); LOG.info(domain.toString()); } @Test public void testDeleteDomain() throws DigitalOceanException, RequestUnsuccessfulException { Delete result = apiClient.deleteDomain(domainName); assertNotNull(result); LOG.info("Delete Request Object: " + result); } @Test public void testGetDomainRecords() throws DigitalOceanException, RequestUnsuccessfulException { DomainRecords domainRecords = apiClient.getDomainRecords("jeeutil.com"); assertNotNull(domainRecords); assertTrue((domainRecords.getDomainRecords().size() > 0)); for (DomainRecord dr : domainRecords.getDomainRecords()) { LOG.info(dr.toString()); } } @Test public void testGetDomainRecordInfo() throws DigitalOceanException, RequestUnsuccessfulException { DomainRecord domainRecord = apiClient.getDomainRecordInfo("jeeutil.com", 160448); assertNotNull(domainRecord); LOG.info(domainRecord.toString()); } @Test public void testCreateDomainRecord() throws DigitalOceanException, RequestUnsuccessfulException { DomainRecord input = new DomainRecord("test1", "@", "CNAME"); DomainRecord domainRecord = apiClient.createDomainRecord("jeeutil.com", input); assertNotNull(domainRecord); LOG.info(domainRecord.toString()); } @Test public void testUpdateDomainRecord() throws DigitalOceanException, RequestUnsuccessfulException { DomainRecord record = new DomainRecord("testjs", "@", "CNAME"); DomainRecord domainRecord = apiClient.updateDomainRecord("example.me", 10989796, record); assertNotNull(domainRecord); LOG.info(domainRecord.toString()); } @Test public void testDeleteDomainRecord() throws DigitalOceanException, RequestUnsuccessfulException { Delete result = apiClient.deleteDomainRecord("jeeutil.com", 3253734); assertNotNull(result); LOG.info("Delete Request Object: " + result.toString()); } // SSH Key test cases @Test public void testGetAvailableKeys() throws DigitalOceanException, RequestUnsuccessfulException { Keys keys = apiClient.getAvailableKeys(1); assertNotNull(keys); assertTrue((keys.getKeys().size() > 0)); for (Key k : keys.getKeys()) { LOG.info(k.toString()); } } @Test public void testCreateKey() throws DigitalOceanException, RequestUnsuccessfulException { // Key key = new Key("TestKey1", // "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDDiyGRkL26BEFPkce1Xtv8u05t8IYHZ63EVDEoAfvg/HCM7SEauBogDGknd4aMd7p9XtxuEIiojiNDIpTnoYbS0RojzhtomefQ/Lx02Rpfsbj1U3zg1H/MMObgJILGIYyHwfT+1rkkRxJQBVcs2Yj7IOmsrmE6SkAZaDLnMxq74HWzd7sPHxx/Dmv6fE0VMaZa+l7Fwr/2Tm46RMF5vzb93QwwmShV+08Ik/0NjGgP7QcNzT11lrI1eCjwCFyT00sGXR+xa4n+M80NB3b8GqDJDAMKqxELcFkpGyGAqESlYt4DXoCRDmnUwhhHReOuutOUHqrSMCym94FFeJ6p6M1f [email protected]"); Key key = new Key( "TestKey1", "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCqMycrkDQdWJUuI5/yx5+Du2BD/W5CXRPnd1xr60MV1zSaRA7OI6sShBontgdI7iepq33hMNaBdr1VttagCjeVJpIsM78Dkcq2NmJ2DKqPnzmfcuJOfcVXO0al2kn4wkYhCKoCV1u3YFCSBW5h3KWOXnptUq30cLUnjgOpAHpugNatJS5Wk8h9V53V2m06FOOty9TY3L8BLQlG3Btl201XMQasFb25izoablwupRLeItzzOHSlwbXWDcrkEQz7o+doOsgpdUfPdQrC1Nv9ujV/Va7BIuUBVVQSznBddCvxmIv/9LIRR7S+Hk+jB8ZgSBcFdmfjdzdQxU39xri5OFTF madanje"); Key resultKey = apiClient.createKey(key); assertNotNull(resultKey); assertNotNull(resultKey.getId()); LOG.info(resultKey.toString()); } @Test public void testGetKeyById() throws DigitalOceanException, RequestUnsuccessfulException { Key resultKey = apiClient.getKeyInfo(245798); assertNotNull(resultKey); assertNotNull(resultKey.getId()); LOG.info(resultKey.toString()); } @Test public void testGetKeyByFingerprint() throws DigitalOceanException, RequestUnsuccessfulException { Key resultKey = apiClient.getKeyInfo("3b:0b:99:54:ef:75:cb:88:88:66:3c:8d:10:64:74:32"); assertNotNull(resultKey); assertNotNull(resultKey.getId()); LOG.info(resultKey.toString()); } @Test public void testUpdateKeyById() throws DigitalOceanException, RequestUnsuccessfulException { Key resultKey = apiClient.updateKey(245798, "TestKey5"); assertNotNull(resultKey); assertNotNull(resultKey.getId()); LOG.info(resultKey.toString()); } @Test public void testUpdateKeyByFingerprint() throws DigitalOceanException, RequestUnsuccessfulException { Key resultKey = apiClient.updateKey("3b:0b:99:54:ef:75:cb:88:88:66:3c:8d:10:64:74:32", "TestKey4"); assertNotNull(resultKey); assertNotNull(resultKey.getId()); LOG.info(resultKey.toString()); } @Test public void testDeleteKeyById() throws DigitalOceanException, RequestUnsuccessfulException { Delete result = apiClient.deleteKey(245798); assertNotNull(result); LOG.info("Delete Key Request Object: " + result); } @Test public void testDeleteKeyByFingerprint() throws DigitalOceanException, RequestUnsuccessfulException { Delete result = apiClient.deleteKey("3b:0b:99:54:ef:75:cb:88:88:66:3c:8d:10:64:74:32"); assertNotNull(result); LOG.info("Delete Key Request Object: " + result); } // Floating IPs test cases @Test public void testGetAvailableFloatingIPs() throws DigitalOceanException, RequestUnsuccessfulException { FloatingIPs floatingIPs = apiClient.getAvailableFloatingIPs(1, 10); LOG.info(floatingIPs.toString()); assertNotNull(floatingIPs); // assertTrue((floatingIPs.getFloatingIPs().size() > 0)); int i = 1; for (FloatingIP floatingIP : floatingIPs.getFloatingIPs()) { LOG.info(i++ + " -> " + floatingIP.toString()); } } @Test public void testCreateFloatingIPForDroplet() throws DigitalOceanException, RequestUnsuccessfulException { FloatingIP floatingIP = apiClient.createFloatingIP(9674996); assertNotNull(floatingIP); LOG.info(floatingIP.toString()); } @Test public void testCreateFloatingIPForRegion() throws DigitalOceanException, RequestUnsuccessfulException { FloatingIP floatingIP = apiClient.createFloatingIP("nyc3"); assertNotNull(floatingIP); LOG.info(floatingIP.toString()); } @Test public void testGetFloatingIPInfo(String ipAddress) throws DigitalOceanException, RequestUnsuccessfulException { FloatingIP floatingIP = apiClient.getFloatingIPInfo("159.203.146.100"); assertNotNull(floatingIP); LOG.info(floatingIP.toString()); } @Test public void testDeleteFloatingIP() throws DigitalOceanException, RequestUnsuccessfulException { Delete result = apiClient.deleteFloatingIP("159.203.146.109"); assertNotNull(result); LOG.info("Delete Floating IP Request Object: " + result); } @Test public void testAssignFloatingIP() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.assignFloatingIP(9674996, "159.203.146.100"); LOG.info(action.toString()); assertNotNull(action); assertEquals(ActionType.ASSIGN_FLOATING_IP, action.getType()); assertEquals(ResourceType.FLOATING_IP, action.getResourceType()); } @Test public void testUnassignFloatingIP() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.unassignFloatingIP("159.203.146.100"); LOG.info(action.toString()); assertNotNull(action); assertEquals(ActionType.UNASSIGN_FLOATING_IP, action.getType()); assertEquals(ResourceType.FLOATING_IP, action.getResourceType()); } }
src/test/java/com/myjeeva/digitalocean/DigitalOceanIntegrationTest.java
/* * The MIT License * * Copyright (c) 2010-2015 Jeevanandam M. (myjeeva.com) * * 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. */ package com.myjeeva.digitalocean; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import junit.framework.TestCase; import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.myjeeva.digitalocean.common.ActionType; import com.myjeeva.digitalocean.exception.DigitalOceanException; import com.myjeeva.digitalocean.exception.RequestUnsuccessfulException; import com.myjeeva.digitalocean.impl.DigitalOceanClient; import com.myjeeva.digitalocean.pojo.Account; import com.myjeeva.digitalocean.pojo.Action; import com.myjeeva.digitalocean.pojo.Actions; import com.myjeeva.digitalocean.pojo.Backup; import com.myjeeva.digitalocean.pojo.Backups; import com.myjeeva.digitalocean.pojo.Delete; import com.myjeeva.digitalocean.pojo.Domain; import com.myjeeva.digitalocean.pojo.DomainRecord; import com.myjeeva.digitalocean.pojo.DomainRecords; import com.myjeeva.digitalocean.pojo.Domains; import com.myjeeva.digitalocean.pojo.Droplet; import com.myjeeva.digitalocean.pojo.Droplets; import com.myjeeva.digitalocean.pojo.FloatingIP; import com.myjeeva.digitalocean.pojo.FloatingIPs; import com.myjeeva.digitalocean.pojo.Image; import com.myjeeva.digitalocean.pojo.Images; import com.myjeeva.digitalocean.pojo.Kernel; import com.myjeeva.digitalocean.pojo.Kernels; import com.myjeeva.digitalocean.pojo.Key; import com.myjeeva.digitalocean.pojo.Keys; import com.myjeeva.digitalocean.pojo.Neighbors; import com.myjeeva.digitalocean.pojo.Region; import com.myjeeva.digitalocean.pojo.Regions; import com.myjeeva.digitalocean.pojo.Size; import com.myjeeva.digitalocean.pojo.Sizes; import com.myjeeva.digitalocean.pojo.Snapshot; import com.myjeeva.digitalocean.pojo.Snapshots; /** * <p> * Junit Integration Test case for DigitalOcean API client wrapper methods * </p> * * <p> * <strong>Please Note:</strong> <i>Kindly through and update private variable value before using * executing this test case(s).</i> * </p> * * @author Jeevanandam M. ([email protected]) */ @Ignore // Marked as Ignore since its a Integration Test case with real values public class DigitalOceanIntegrationTest extends TestCase { private final Logger LOG = LoggerFactory.getLogger(DigitalOceanIntegrationTest.class); /** * This is testing values of my own respective to DigitalOcean account, to real-time integration * with API. So place your's for integration test case before use */ private String authTokenRW = ""; private Integer dropletIdForInfo = 10001; // to be placed before use private Integer imageId = 3445812; // Debian 7.0 x64 image id private String imageSlug = "ubuntu-12-04-x64"; private String domainName = ""; private String domainIp = "127.0.0.1"; private DigitalOcean apiClient = new DigitalOceanClient(authTokenRW); // Droplet test cases @Test public void testGetAvailableDroplets() throws DigitalOceanException, RequestUnsuccessfulException { Droplets droplets = apiClient.getAvailableDroplets(1, null); assertNotNull(droplets); assertTrue((droplets.getDroplets().size() > 0)); int i = 1; for (Droplet droplet : droplets.getDroplets()) { LOG.info(i++ + " -> " + droplet.toString()); } } @Test public void testGetAvailableKernels() throws DigitalOceanException, RequestUnsuccessfulException { Kernels kernels = apiClient.getAvailableKernels(dropletIdForInfo, 1, 20); assertNotNull(kernels); assertTrue((kernels.getKernels().size() > 0)); int i = 1; for (Kernel k : kernels.getKernels()) { LOG.info(i++ + " -> " + k.toString()); } } @Test public void testGetAvailableSnapshots() throws DigitalOceanException, RequestUnsuccessfulException { Snapshots snapshots = apiClient.getAvailableSnapshots(dropletIdForInfo, 1, 20); assertNotNull(snapshots); assertTrue((snapshots.getSnapshots().size() > 0)); for (Snapshot s : snapshots.getSnapshots()) { LOG.info(s.toString()); } } @Test public void testGetAvailableBackups() throws DigitalOceanException, RequestUnsuccessfulException { Backups backups = apiClient.getAvailableBackups(dropletIdForInfo, 1); assertNotNull(backups); assertTrue((backups.getBackups().size() > 0)); for (Backup b : backups.getBackups()) { LOG.info(b.toString()); } } @Test public void testGetDropletInfo() throws DigitalOceanException, RequestUnsuccessfulException { Droplet droplet = apiClient.getDropletInfo(dropletIdForInfo); assertNotNull(droplet); LOG.info(droplet.toString()); } @Test public void testCreateDropletByImageId() throws DigitalOceanException, RequestUnsuccessfulException { Droplet droplet = new Droplet(); droplet.setName("api-client-test-host-byid"); droplet.setSize("512mb"); droplet.setImage(new Image(1601)); droplet.setRegion(new Region("sgp1")); droplet.setEnableBackup(Boolean.TRUE); droplet.setEnableIpv6(Boolean.TRUE); droplet.setEnablePrivateNetworking(Boolean.TRUE); // Adding SSH key info List<Key> keys = new ArrayList<Key>(); keys.add(new Key(513618)); droplet.setKeys(keys); // Adding Metadata API - User Data /* * droplet .setUserData("#!/bin/bash" + "apt-get -y update" + "apt-get -y install nginx" + * "export HOSTNAME=$(curl -s http://169.254.169.254/metadata/v1/hostname)" + * "export PUBLIC_IPV4=$(curl -s http://169.254.169.254/metadata/v1/interfaces/public/0/ipv4/address)" * + "echo Droplet: $HOSTNAME, IP Address: $PUBLIC_IPV4 > /usr/share/nginx/html/index.html"); */ Droplet d = apiClient.createDroplet(droplet); assertNotNull(d); assertNotNull(d.getId()); LOG.info(d.toString()); } @Test public void testCreateDropletByImageSlug() throws DigitalOceanException, RequestUnsuccessfulException { Droplet droplet = new Droplet(); droplet.setName("api-client-test-host-byslug1"); droplet.setSize("512mb"); droplet.setImage(new Image("centos-5-8-x64")); droplet.setRegion(new Region("sgp1")); droplet.setEnableBackup(Boolean.TRUE); droplet.setEnableIpv6(Boolean.TRUE); droplet.setEnablePrivateNetworking(Boolean.TRUE); // Adding SSH key info List<Key> keys = new ArrayList<Key>(); keys.add(new Key(513618)); droplet.setKeys(keys); Droplet d = apiClient.createDroplet(droplet); assertNotNull(d); assertNotNull(d.getId()); LOG.info(d.toString()); } @Test public void testCreateDropletsByImageSlug() throws DigitalOceanException, RequestUnsuccessfulException { Droplet droplet = new Droplet(); droplet.setNames(Arrays.asList("sub-01.example.com", "sub-02.example.com")); droplet.setName("not allowed"); droplet.setSize("512mb"); droplet.setImage(new Image("ubuntu-14-04-x64")); droplet.setRegion(new Region("sgp1")); Droplets droplets = apiClient.createDroplets(droplet); assertNotNull(droplets); assertTrue((droplets.getDroplets().size() > 0)); for (Droplet d : droplets.getDroplets()) { LOG.info(d.toString()); } } @Test public void testDeleteDroplet() throws DigitalOceanException, RequestUnsuccessfulException { Delete result = apiClient.deleteDroplet(2258153); assertNotNull(result); LOG.info("Delete Request Object: " + result); } @Test public void testGetDropletNeighbors() throws DigitalOceanException, RequestUnsuccessfulException { Droplets droplets = apiClient.getDropletNeighbors(dropletIdForInfo, 1); assertNotNull(droplets); for (Droplet d : droplets.getDroplets()) { LOG.info(d.toString()); } } @Test public void testGetAllDropletNeighbors() throws DigitalOceanException, RequestUnsuccessfulException { Neighbors neighbors = apiClient.getAllDropletNeighbors(1); assertNotNull(neighbors); for (Droplet d : neighbors.getNeighbors()) { LOG.info(d.toString()); } } @Test public void testRebootDroplet() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.rebootDroplet(2258136); assertNotNull(action); LOG.info(action.toString()); } @Test public void testPowerCycleDroplet() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.rebootDroplet(2258136); assertNotNull(action); LOG.info(action.toString()); } @Test public void testShutdownDroplet() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.shutdownDroplet(4124871); // 2258168 assertNotNull(action); LOG.info(action.toString()); } @Test public void testPowerOffDroplet() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.powerOffDroplet(2258168); assertNotNull(action); LOG.info(action.toString()); } @Test public void testPowerOnDroplet() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.powerOnDroplet(2258136); assertNotNull(action); LOG.info(action.toString()); } @Test public void testResetDropletPassword() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.resetDropletPassword(2258168); assertNotNull(action); LOG.info(action.toString()); } @Test public void testResizeDroplet() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.resizeDroplet(2258136, "1gb"); assertNotNull(action); LOG.info(action.toString()); } @Test public void testTakeDropletSnapshot() throws DigitalOceanException, RequestUnsuccessfulException { // Action action = apiClient.takeDropletSnapshot(2258168, "api-client-test-snapshot1"); Action action = apiClient.takeDropletSnapshot(2258136); assertNotNull(action); LOG.info(action.toString()); } @Test public void testRestoreDroplet() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.restoreDroplet(2258168, 5489522); // Snapshot id assertNotNull(action); LOG.info(action.toString()); } @Test public void testRebuildDroplet() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.rebuildDroplet(2258136, 3445812); // Debian 7.0 x64 assertNotNull(action); LOG.info(action.toString()); } @Test public void testEnableDropletBackups() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.enableDropletBackups(9662284); assertNotNull(action); LOG.info(action.toString()); } @Test public void testDisableDropletBackups() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.disableDropletBackups(2258168); assertNotNull(action); LOG.info(action.toString()); } @Test public void testRenameDroplet() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.renameDroplet(2258168, "renamed-droplet-name-test"); assertNotNull(action); LOG.info(action.toString()); } @Test public void testChangeDropletKernel() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.changeDropletKernel(2258168, 1649); assertNotNull(action); LOG.info(action.toString()); } @Test public void testEnableDropletIpv6() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.enableDropletIpv6(2258168); assertNotNull(action); LOG.info(action.toString()); } @Test public void testEnableDropletPrivateNetworking() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.enableDropletPrivateNetworking(2258168); assertNotNull(action); LOG.info(action.toString()); } // Account Test cases @Test public void testGetAccountInfo() throws DigitalOceanException, RequestUnsuccessfulException { Account account = apiClient.getAccountInfo(); assertNotNull(account); LOG.info(account.toString()); } // Action Test cases @Test public void testGetAvailableActions() throws DigitalOceanException, RequestUnsuccessfulException { Actions actions = apiClient.getAvailableActions(2, 30); assertNotNull(actions); assertTrue((actions.getActions().size() > 0)); LOG.info(actions.getLinks().toString()); int i = 1; for (Action a : actions.getActions()) { LOG.info(i++ + " -> " + a.toString()); } } @Test public void testGetActionInfo() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.getActionInfo(28336352); assertNotNull(action); LOG.info(action.toString()); } @Test public void testGetAvailableDropletActions() throws DigitalOceanException, RequestUnsuccessfulException { Actions actions = apiClient.getAvailableDropletActions(dropletIdForInfo, 1, 20); Actions actions3 = apiClient.getAvailableDropletActions(dropletIdForInfo, 3, 20); assertNotNull(actions); assertTrue((actions.getActions().size() > 0)); assertNotNull(actions3); assertTrue((actions3.getActions().size() > 0)); for (Action a : actions.getActions()) { LOG.info(a.toString()); } } @Test public void testGetAvailableImageActions() throws DigitalOceanException, RequestUnsuccessfulException { Actions actions = apiClient.getAvailableImageActions(3794738, 1, 20); assertNotNull(actions); assertTrue((actions.getActions().size() > 0)); for (Action a : actions.getActions()) { LOG.info(a.toString()); } } // Image test cases @Test public void testGetAvailableImages() throws DigitalOceanException, RequestUnsuccessfulException { Images images = apiClient.getAvailableImages(1, 20); assertNotNull(images); assertTrue((images.getImages().size() > 0)); for (Image img : images.getImages()) { LOG.info(img.toString()); } } @Test public void testGetAvailableImagesByDistribution() throws DigitalOceanException, RequestUnsuccessfulException { Images images = apiClient.getAvailableImages(1, 20, ActionType.DISTRIBUTION); assertNotNull(images); assertTrue((images.getImages().size() > 0)); for (Image img : images.getImages()) { LOG.info(img.toString()); } } @Test public void testGetAvailableImagesByApplication() throws DigitalOceanException, RequestUnsuccessfulException { Images images = apiClient.getAvailableImages(1, 20, ActionType.APPLICATION); assertNotNull(images); assertTrue((images.getImages().size() > 0)); for (Image img : images.getImages()) { LOG.info(img.toString()); } } @Test public void testGetAvailableImagesByIncorrrect() throws DigitalOceanException, RequestUnsuccessfulException { try { apiClient.getAvailableImages(1, 20, ActionType.BACKUP); } catch (DigitalOceanException doe) { LOG.info(doe.getMessage()); } } @Test public void testGetUserImages() throws DigitalOceanException, RequestUnsuccessfulException { Images images = apiClient.getUserImages(1, 20); assertNotNull(images); assertTrue((images.getImages().size() > 0)); for (Image img : images.getImages()) { LOG.info(img.toString()); } } @Test public void testGetImageInfoById() throws DigitalOceanException, RequestUnsuccessfulException { Image image = apiClient.getImageInfo(imageId); assertNotNull(image); LOG.info(image.toString()); } @Test public void testGetImageInfoBySlug() throws DigitalOceanException, RequestUnsuccessfulException { Image image = apiClient.getImageInfo(imageSlug); assertNotNull(image); LOG.info(image.toString()); } @Test public void testUpdateImageInfo() throws DigitalOceanException, RequestUnsuccessfulException { Image input = new Image(); input.setId(3897539); input.setName("test-myjeeva.com-before-wp-upgrade"); Image image = apiClient.updateImage(input); assertNotNull(image); LOG.info(image.toString()); } @Test public void testDeleteImage() throws DigitalOceanException, RequestUnsuccessfulException { Delete result = apiClient.deleteImage(3897539); assertNotNull(result); LOG.info("Delete Request result: " + result); } @Test public void testTransferImage() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.transferImage(5489522, "lon1"); assertNotNull(action); LOG.info(action.toString()); } @Test public void testConvertImage() throws DigitalOceanException, RequestUnsuccessfulException { Action action = apiClient.convertImage(5489522); assertNotNull(action); LOG.info(action.toString()); } // Regions test cases @Test public void testGetAvailableRegions() throws DigitalOceanException, RequestUnsuccessfulException { Regions regions = apiClient.getAvailableRegions(1); assertNotNull(regions); assertTrue((regions.getRegions().size() > 0)); for (Region region : regions.getRegions()) { LOG.info(region.toString()); } } // Sizes test cases @Test public void testGetAvailableSizes() throws DigitalOceanException, RequestUnsuccessfulException { Sizes sizes = apiClient.getAvailableSizes(1); assertNotNull(sizes); assertTrue((sizes.getSizes().size() > 0)); for (Size size : sizes.getSizes()) { LOG.info(size.toString()); } } // Domain test cases @Test public void testGetAvailableDomains() throws DigitalOceanException, RequestUnsuccessfulException { Domains domains = apiClient.getAvailableDomains(1); assertNotNull(domains); assertTrue((domains.getDomains().size() > 0)); for (Domain d : domains.getDomains()) { LOG.info(d.toString()); } } @Test public void testGetDomainInfo() throws DigitalOceanException, RequestUnsuccessfulException { Domain domain = apiClient.getDomainInfo("jeeutil.com"); assertNotNull(domain); LOG.info(domain.toString()); } @Test public void testCreateDomain() throws DigitalOceanException, RequestUnsuccessfulException { Domain input = new Domain(domainName, domainIp); Domain domain = apiClient.createDomain(input); assertNotNull(domain); assertNotNull(domain.getName()); LOG.info(domain.toString()); } @Test public void testDeleteDomain() throws DigitalOceanException, RequestUnsuccessfulException { Delete result = apiClient.deleteDomain(domainName); assertNotNull(result); LOG.info("Delete Request Object: " + result); } @Test public void testGetDomainRecords() throws DigitalOceanException, RequestUnsuccessfulException { DomainRecords domainRecords = apiClient.getDomainRecords("jeeutil.com"); assertNotNull(domainRecords); assertTrue((domainRecords.getDomainRecords().size() > 0)); for (DomainRecord dr : domainRecords.getDomainRecords()) { LOG.info(dr.toString()); } } @Test public void testGetDomainRecordInfo() throws DigitalOceanException, RequestUnsuccessfulException { DomainRecord domainRecord = apiClient.getDomainRecordInfo("jeeutil.com", 160448); assertNotNull(domainRecord); LOG.info(domainRecord.toString()); } @Test public void testCreateDomainRecord() throws DigitalOceanException, RequestUnsuccessfulException { DomainRecord input = new DomainRecord("test1", "@", "CNAME"); DomainRecord domainRecord = apiClient.createDomainRecord("jeeutil.com", input); assertNotNull(domainRecord); LOG.info(domainRecord.toString()); } @Test public void testUpdateDomainRecord() throws DigitalOceanException, RequestUnsuccessfulException { DomainRecord record = new DomainRecord("testjs", "@", "CNAME"); DomainRecord domainRecord = apiClient.updateDomainRecord("example.me", 10989796, record); assertNotNull(domainRecord); LOG.info(domainRecord.toString()); } @Test public void testDeleteDomainRecord() throws DigitalOceanException, RequestUnsuccessfulException { Delete result = apiClient.deleteDomainRecord("jeeutil.com", 3253734); assertNotNull(result); LOG.info("Delete Request Object: " + result.toString()); } // SSH Key test cases @Test public void testGetAvailableKeys() throws DigitalOceanException, RequestUnsuccessfulException { Keys keys = apiClient.getAvailableKeys(1); assertNotNull(keys); assertTrue((keys.getKeys().size() > 0)); for (Key k : keys.getKeys()) { LOG.info(k.toString()); } } @Test public void testCreateKey() throws DigitalOceanException, RequestUnsuccessfulException { // Key key = new Key("TestKey1", // "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDDiyGRkL26BEFPkce1Xtv8u05t8IYHZ63EVDEoAfvg/HCM7SEauBogDGknd4aMd7p9XtxuEIiojiNDIpTnoYbS0RojzhtomefQ/Lx02Rpfsbj1U3zg1H/MMObgJILGIYyHwfT+1rkkRxJQBVcs2Yj7IOmsrmE6SkAZaDLnMxq74HWzd7sPHxx/Dmv6fE0VMaZa+l7Fwr/2Tm46RMF5vzb93QwwmShV+08Ik/0NjGgP7QcNzT11lrI1eCjwCFyT00sGXR+xa4n+M80NB3b8GqDJDAMKqxELcFkpGyGAqESlYt4DXoCRDmnUwhhHReOuutOUHqrSMCym94FFeJ6p6M1f [email protected]"); Key key = new Key( "TestKey1", "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCqMycrkDQdWJUuI5/yx5+Du2BD/W5CXRPnd1xr60MV1zSaRA7OI6sShBontgdI7iepq33hMNaBdr1VttagCjeVJpIsM78Dkcq2NmJ2DKqPnzmfcuJOfcVXO0al2kn4wkYhCKoCV1u3YFCSBW5h3KWOXnptUq30cLUnjgOpAHpugNatJS5Wk8h9V53V2m06FOOty9TY3L8BLQlG3Btl201XMQasFb25izoablwupRLeItzzOHSlwbXWDcrkEQz7o+doOsgpdUfPdQrC1Nv9ujV/Va7BIuUBVVQSznBddCvxmIv/9LIRR7S+Hk+jB8ZgSBcFdmfjdzdQxU39xri5OFTF madanje"); Key resultKey = apiClient.createKey(key); assertNotNull(resultKey); assertNotNull(resultKey.getId()); LOG.info(resultKey.toString()); } @Test public void testGetKeyById() throws DigitalOceanException, RequestUnsuccessfulException { Key resultKey = apiClient.getKeyInfo(245798); assertNotNull(resultKey); assertNotNull(resultKey.getId()); LOG.info(resultKey.toString()); } @Test public void testGetKeyByFingerprint() throws DigitalOceanException, RequestUnsuccessfulException { Key resultKey = apiClient.getKeyInfo("3b:0b:99:54:ef:75:cb:88:88:66:3c:8d:10:64:74:32"); assertNotNull(resultKey); assertNotNull(resultKey.getId()); LOG.info(resultKey.toString()); } @Test public void testUpdateKeyById() throws DigitalOceanException, RequestUnsuccessfulException { Key resultKey = apiClient.updateKey(245798, "TestKey5"); assertNotNull(resultKey); assertNotNull(resultKey.getId()); LOG.info(resultKey.toString()); } @Test public void testUpdateKeyByFingerprint() throws DigitalOceanException, RequestUnsuccessfulException { Key resultKey = apiClient.updateKey("3b:0b:99:54:ef:75:cb:88:88:66:3c:8d:10:64:74:32", "TestKey4"); assertNotNull(resultKey); assertNotNull(resultKey.getId()); LOG.info(resultKey.toString()); } @Test public void testDeleteKeyById() throws DigitalOceanException, RequestUnsuccessfulException { Delete result = apiClient.deleteKey(245798); assertNotNull(result); LOG.info("Delete Key Request Object: " + result); } @Test public void testDeleteKeyByFingerprint() throws DigitalOceanException, RequestUnsuccessfulException { Delete result = apiClient.deleteKey("3b:0b:99:54:ef:75:cb:88:88:66:3c:8d:10:64:74:32"); assertNotNull(result); LOG.info("Delete Key Request Object: " + result); } // Floating IPs test cases @Test public void testGetAvailableFloatingIPs() throws DigitalOceanException, RequestUnsuccessfulException { FloatingIPs floatingIPs = apiClient.getAvailableFloatingIPs(1, 10); LOG.info(floatingIPs.toString()); assertNotNull(floatingIPs); // assertTrue((floatingIPs.getFloatingIPs().size() > 0)); int i = 1; for (FloatingIP floatingIP : floatingIPs.getFloatingIPs()) { LOG.info(i++ + " -> " + floatingIP.toString()); } } @Test public void testCreateFloatingIPForDroplet() throws DigitalOceanException, RequestUnsuccessfulException { FloatingIP floatingIP = apiClient.createFloatingIP(9674996); assertNotNull(floatingIP); LOG.info(floatingIP.toString()); } @Test public void testCreateFloatingIPForRegion() throws DigitalOceanException, RequestUnsuccessfulException { FloatingIP floatingIP = apiClient.createFloatingIP("nyc3"); assertNotNull(floatingIP); LOG.info(floatingIP.toString()); } @Test public void testGetFloatingIPInfo(String ipAddress) throws DigitalOceanException, RequestUnsuccessfulException { FloatingIP floatingIP = apiClient.getFloatingIPInfo("159.203.146.100"); assertNotNull(floatingIP); LOG.info(floatingIP.toString()); } @Test public void testDeleteFloatingIP() throws DigitalOceanException, RequestUnsuccessfulException { Delete result = apiClient.deleteFloatingIP("159.203.146.109"); assertNotNull(result); LOG.info("Delete Floating IP Request Object: " + result); } }
#44 - test cases added for floating IPs
src/test/java/com/myjeeva/digitalocean/DigitalOceanIntegrationTest.java
#44 - test cases added for floating IPs
<ide><path>rc/test/java/com/myjeeva/digitalocean/DigitalOceanIntegrationTest.java <ide> import org.slf4j.LoggerFactory; <ide> <ide> import com.myjeeva.digitalocean.common.ActionType; <add>import com.myjeeva.digitalocean.common.ResourceType; <ide> import com.myjeeva.digitalocean.exception.DigitalOceanException; <ide> import com.myjeeva.digitalocean.exception.RequestUnsuccessfulException; <ide> import com.myjeeva.digitalocean.impl.DigitalOceanClient; <ide> } <ide> <ide> <add> @Test <add> public void testGetAvailableFloatingIPActions() throws DigitalOceanException, <add> RequestUnsuccessfulException { <add> Actions actions = apiClient.getAvailableFloatingIPActions("159.203.146.100", 1, 10); <add> <add> LOG.info(actions.toString()); <add> <add> assertNotNull(actions); <add> <add> int i = 1; <add> for (Action action : actions.getActions()) { <add> LOG.info(i++ + " -> " + action.toString()); <add> } <add> } <add> <add> @Test <add> public void testGetFloatingIPActionInfo() throws DigitalOceanException, <add> RequestUnsuccessfulException { <add> Action action = apiClient.getFloatingIPActionInfo("159.203.146.100", 76697074); <add> <add> LOG.info(action.toString()); <add> <add> assertNotNull(action); <add> } <add> <add> <ide> <ide> // Image test cases <ide> <ide> assertNotNull(result); <ide> LOG.info("Delete Floating IP Request Object: " + result); <ide> } <add> <add> @Test <add> public void testAssignFloatingIP() throws DigitalOceanException, RequestUnsuccessfulException { <add> Action action = apiClient.assignFloatingIP(9674996, "159.203.146.100"); <add> <add> LOG.info(action.toString()); <add> <add> assertNotNull(action); <add> assertEquals(ActionType.ASSIGN_FLOATING_IP, action.getType()); <add> assertEquals(ResourceType.FLOATING_IP, action.getResourceType()); <add> } <add> <add> @Test <add> public void testUnassignFloatingIP() throws DigitalOceanException, RequestUnsuccessfulException { <add> Action action = apiClient.unassignFloatingIP("159.203.146.100"); <add> <add> LOG.info(action.toString()); <add> <add> assertNotNull(action); <add> assertEquals(ActionType.UNASSIGN_FLOATING_IP, action.getType()); <add> assertEquals(ResourceType.FLOATING_IP, action.getResourceType()); <add> } <add> <ide> }
Java
mit
29a40e80450337fe660f7d5ad3a1aafff1cbaeb6
0
Bernardo-MG/spring-mvc-thymeleaf-maven-archetype,Bernardo-MG/spring-mvc-thymeleaf-maven-archetype,Bernardo-MG/spring-mvc-thymeleaf-maven-archetype
/** * The MIT License (MIT) * <p> * Copyright (c) ${currentYear} the original author or authors. * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p> * 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. */ /** * Form objects. These are DTOs mapping the data sent between the view and * controllers. */ package ${package}.model.form;
src/main/resources/archetype-resources/src/main/java/model/form/package-info.java
/** * The MIT License (MIT) * <p> * Copyright (c) ${currentYear} the original author or authors. * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p> * 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. */ /** * Form objects. These are DTOs mapping the data sent between the view and * controllers. */ package ${package}.controller.entity.bean;
Fixed package declaration
src/main/resources/archetype-resources/src/main/java/model/form/package-info.java
Fixed package declaration
<ide><path>rc/main/resources/archetype-resources/src/main/java/model/form/package-info.java <ide> * controllers. <ide> */ <ide> <del>package ${package}.controller.entity.bean; <add>package ${package}.model.form;
JavaScript
apache-2.0
4e8c9cbf7deadd19c788eca0c5548f1508ad0c3c
0
shackbarth/backbone-x,shackbarth/enyo-x
/*jshint bitwise:true, indent:2, curly:true eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true, regexp:true, undef:true, trailing:true white:true*/ /*global XT:true, XV:true, XM:true, _:true, enyo:true*/ (function () { var FETCH_TRIGGER = 100; var MODULE_MENU = 0; var PANEL_MENU = 1; enyo.kind({ name: "XV.Module", kind: "Panels", classes: "app enyo-unselectable", published: { label: "", modules: [] }, events: { onListAdded: "", onTogglePullout: "" }, handlers: { onParameterChange: "requery", onScroll: "scrolled", onListItemTapped: "listItemTapped" }, showPullout: true, arrangerKind: "CollapsingArranger", components: [ {kind: "FittableRows", classes: "left", components: [ {kind: "onyx.Toolbar", classes: "onyx-menu-toolbar", components: [ {kind: "onyx.Button", name: "backButton", content: "_logout".loc(), ontap: "backTapped"}, {kind: "Group", name: "iconButtonGroup", defaultKind: "onyx.IconButton", tag: null, components: [ {name: "historyIconButton", src: "assets/menu-icon-bookmark.png", ontap: "showHistory"}, {name: "searchIconButton", src: "assets/menu-icon-search.png", ontap: "showParameters"} ]}, {name: "leftLabel"}, {kind: "onyx.Popup", name: "logoutPopup", centered: true, modal: true, floating: true, components: [ {content: "_logoutConfirmation".loc() }, {tag: "br"}, {kind: "onyx.Button", content: "_ok".loc(), ontap: "logout"}, {kind: "onyx.Button", content: "_cancel".loc(), ontap: "closeLogoutPopup", classes: "onyx-blue"} ]} ]}, {name: "menuPanels", kind: "Panels", draggable: false, fit: true, components: [ {name: "moduleMenu", kind: "List", touch: true, onSetupItem: "setupModuleMenuItem", components: [ {name: "moduleItem", classes: "item enyo-border-box", ontap: "moduleItemTap"} ]}, {name: "panelMenu", kind: "List", touch: true, onSetupItem: "setupPanelMenuItem", components: [ {name: "listItem", classes: "item enyo-border-box", ontap: "menuItemTap"} ]}, {} // Why do panels only work when there are 3+ objects? ]} ]}, {kind: "FittableRows", components: [ {kind: "onyx.MoreToolbar", name: "contentToolbar", components: [ {kind: "onyx.Grabber"}, {name: "rightLabel", style: "text-align: center"}, {kind: "onyx.InputDecorator", style: "float: right;", components: [ {name: 'searchInput', kind: "onyx.Input", style: "width: 200px;", placeholder: "Search", onchange: "inputChanged"}, {kind: "Image", src: "assets/search-input-search.png"} ]}, {kind: "onyx.Button", content: "_new".loc(), ontap: "newRecord", style: "float: right;" } ]}, {name: "contentPanels", kind: "Panels", margin: 0, fit: true, draggable: false, panelCount: 0} ]}, {kind: "Signals", onModelSave: "refreshInfoObject"} ], fetched: {}, activate: function () { this.setMenuPanel(MODULE_MENU); }, backTapped: function () { var index = this.$.menuPanels.getIndex(); if (index === MODULE_MENU) { this.warnLogout(); } else { this.setMenuPanel(MODULE_MENU); } }, create: function () { this.inherited(arguments); var modules = this.getModules() || [], label = this.getLabel(), panels, panel, i, n; this.$.leftLabel.setContent(label); // Build panels for (i = 0; i < modules.length; i++) { panels = modules[i].panels || []; for (n = 0; n < panels.length; n++) { // Keep track of where this panel is being placed for later reference panels[n].index = this.$.contentPanels.panelCount++; panel = this.$.contentPanels.createComponent(panels[n]); if (panel instanceof XV.List) { // Bubble parameter widget up to pullout this.doListAdded(panel); } } } this.$.moduleMenu.setCount(modules.length); }, getSelectedModule: function (index) { return this._selectedModule; }, inputChanged: function (inSender, inEvent) { var index = this.$.contentPanels.getIndex(), list = this.panels[index].name; this.fetched = {}; this.fetch(list); }, listItemTapped: function (inSender, inEvent) { var list = this.$.contentPanels.getActive(), workspace = list.getWorkspace(), id = list.getModel(inEvent.index).id; // Transition to workspace view, including the model id payload this.bubble("workspace", { eventName: "workspace", workspace: workspace, id: id }); return true; }, fetch: function (index, options) { index = index || this.$.contentPanels.getIndex(); var panel = this.$.contentPanels.getPanels()[index], name = panel ? panel.name : "", query, input, parameterWidget, parameters; if (!panel instanceof XV.List) { return; } query = panel.getQuery() || {}; input = this.$.searchInput.getValue(); parameterWidget = XT.app ? XT.app.getPullout().getItem(name) : null; parameters = parameterWidget ? parameterWidget.getParameters() : []; options = options ? _.clone(options) : {}; options.showMore = _.isBoolean(options.showMore) ? options.showMore : false; // Build parameters if (input || parameters.length) { query.parameters = []; // Input search parameters if (input) { query.parameters = [{ attribute: panel.getSearchableAttributes(), operator: 'MATCHES', value: this.$.searchInput.getValue() }]; } // Advanced parameters if (parameters) { query.parameters = query.parameters.concat(parameters); } } else { delete query.parameters; } panel.setQuery(query); panel.fetch(options); this.fetched[index] = true; }, newRecord: function (inSender, inEvent) { var list = this.$.contentPanels.getActive(), workspace = list.getWorkspace(); this.bubble("workspace", { eventName: "workspace", workspace: workspace }); return true; }, menuItemTap: function (inSender, inEvent) { this.setContentPanel(inEvent.index); }, moduleItemTap: function (inSender, inEvent) { //this.setModule(inEvent.index); }, requery: function (inSender, inEvent) { this.fetch(); }, scrolled: function (inSender, inEvent) { if (inEvent.originator instanceof XV.List === false) { return; } var list = inEvent.originator, max = list.getScrollBounds().maxTop - list.rowHeight * FETCH_TRIGGER, options = {}; if (list.getIsMore() && list.getScrollPosition() > max && !list.getIsFetching()) { list.setIsFetching(true); options.showMore = true; this.fetch(list.name, options); } }, setContentPanel: function (index) { var module = this.getSelectedModule(), panelIndex = module && module.panels ? module.panels[index].index : -1, panel = panelIndex > -1 ? this.$.contentPanels.getPanels()[panelIndex] : null, label = panel ? panel.getLabel() : ""; if (!panel) { return; } // Select panelMenu if (!this.$.panelMenu.isSelected(index)) { this.$.panelMenu.select(index); } // Select list if (this.$.contentPanels.getIndex() !== panelIndex) { this.$.contentPanels.setIndex(panelIndex); } this.$.rightLabel.setContent(label); if (panel.fetch && !this.fetched[panelIndex]) { this.fetch(panelIndex); } }, setMenuPanel: function (index) { var label = index ? "_back".loc() : "_logout".loc(); this.$.menuPanels.setIndex(index); this.$.menuPanels.getActive().select(0); this.setContentPanel(0); this.$.backButton.setContent(label); }, setModule: function (index) { var module = this.getModules()[index], panels = module.panels || []; if (module !== this._selectedModule) { this._selectedModule = module; if (panels.length) { this.$.panelMenu.setCount(panels.length); this.setMenuPanel(PANEL_MENU); } } }, setupModuleMenuItem: function (inSender, inEvent) { var index = inEvent.index, label = this.modules[index].label, isSelected = inSender.isSelected(index); this.$.moduleItem.setContent(label); this.$.moduleItem.addRemoveClass("onyx-selected", isSelected); if (isSelected) { this.setModule(index); } }, setupPanelMenuItem: function (inSender, inEvent) { var module = this.getSelectedModule(), panel; panel = module.panels[inEvent.index].name; this.$.listItem.setContent(this.$.contentPanels.$[panel].getLabel()); this.$.listItem.addRemoveClass("onyx-selected", inSender.isSelected(inEvent.index)); }, showHistory: function (inSender, inEvent) { var panel = {name: 'history'}; this.doTogglePullout(panel); }, showParameters: function (inSender, inEvent) { var panel = this.$.contentPanels.getActive(); this.doTogglePullout(panel); }, /** * If a model has changed, check the panels of this module to see if we can * update the info object in the list. * XXX if there are multiple modules alive then all of them will catch * XXX the signal, which isn't ideal for performance */ refreshInfoObject: function (inSender, inPayload) { // obnoxious massaging. Can't think of an elegant way to do this. // salt in wounds: in setup we massage by adding List on the end, but with // crm we massage by adding List on the end. This is horrible. // XXX not sustainable var listBase = XV.util.stripModelNamePrefix(inPayload.recordType).camelize(), listName = this.name === "setup" ? listBase + "List" : listBase + "List", list = this.$.contentPanels.$[listName]; /** * If the update model is part of a cached collection, refresh the cache * XXX This string massaging should be refactored into intelligence within * the collection itself. * XXX this part will happen for each living module. But it only needs to * be refreshed once. Moving away from signals would solve this. Or we * could create a dedicated signal event. */ var cacheName; if (listBase.charAt(listBase.length - 1) === 'y') { cacheName = listBase.substring(0, listBase.length - 1) + 'ies'; } else { cacheName = listBase + 's'; } if (XM[cacheName]) { XM[cacheName].fetch(); // no need to fetch the model itself, but we do want to tell the // module that contains the list to refresh that list by setting // the fetched property to false if (this.fetched[listName]) { this.fetched[listName] = false; } return; } /** * Update the model itself */ if (!list) { // we don't have this model on our list. No need to update return; } var model = _.find(list.collection.models, function (model) { return model.id === inPayload.id; }); if (!model) { // this model isn't in the list. No need to update return; } model.fetch(); }, /** Logout management. We show the user a warning popup before we log them out. */ warnLogout: function () { this.$.logoutPopup.show(); }, closeLogoutPopup: function () { this.$.logoutPopup.hide(); }, logout: function () { this.$.logoutPopup.hide(); XT.session.logout(); }, /** Manually set one of the icon buttons to be active. Note passing null as the parameter will disactivate all icons. */ setActiveIconButton: function (buttonName) { var activeIconButton = null; if (buttonName === 'search') { activeIconButton = this.$.searchIconButton; } else if (buttonName === 'history') { activeIconButton = this.$.historyIconButton; } this.$.iconButtonGroup.setActive(activeIconButton); } }); }());
source/xv/views/module.js
/*jshint bitwise:true, indent:2, curly:true eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true, regexp:true, undef:true, trailing:true white:true*/ /*global XT:true, XV:true, XM:true, _:true, enyo:true*/ (function () { var FETCH_TRIGGER = 100; var MODULE_MENU = 0; var PANEL_MENU = 1; enyo.kind({ name: "XV.Module", kind: "Panels", classes: "app enyo-unselectable", published: { label: "", modules: [] }, events: { onListAdded: "", onTogglePullout: "" }, handlers: { onParameterChange: "requery", onScroll: "scrolled", onListItemTapped: "listItemTapped" }, showPullout: true, arrangerKind: "CollapsingArranger", components: [ {kind: "FittableRows", classes: "left", components: [ {kind: "onyx.Toolbar", classes: "onyx-menu-toolbar", components: [ {kind: "onyx.Button", name: "backButton", content: "_logout".loc(), ontap: "backTapped"}, {kind: "Group", name: "iconButtonGroup", defaultKind: "onyx.IconButton", tag: null, components: [ {name: "historyIconButton", src: "assets/menu-icon-bookmark.png", ontap: "showHistory"}, {name: "searchIconButton", src: "assets/menu-icon-search.png", ontap: "showParameters"} ]}, {name: "leftLabel"}, {kind: "onyx.Popup", name: "logoutPopup", centered: true, modal: true, floating: true, components: [ {content: "_logoutConfirmation".loc() }, {tag: "br"}, {kind: "onyx.Button", content: "_ok".loc(), ontap: "logout"}, {kind: "onyx.Button", content: "_cancel".loc(), ontap: "closeLogoutPopup", classes: "onyx-blue"} ]} ]}, {name: "menuPanels", kind: "Panels", draggable: false, fit: true, components: [ {name: "moduleMenu", kind: "List", touch: true, onSetupItem: "setupModuleMenuItem", components: [ {name: "moduleItem", classes: "item enyo-border-box", ontap: "moduleItemTap"} ]}, {name: "panelMenu", kind: "List", touch: true, onSetupItem: "setupPanelMenuItem", components: [ {name: "listItem", classes: "item enyo-border-box", ontap: "menuItemTap"} ]}, {} // Why do panels only work when there are 3+ objects? ]} ]}, {kind: "FittableRows", components: [ {kind: "onyx.MoreToolbar", name: "contentToolbar", components: [ {kind: "onyx.Grabber"}, {name: "rightLabel", style: "text-align: center"}, {kind: "onyx.InputDecorator", style: "float: right;", components: [ {name: 'searchInput', kind: "onyx.Input", style: "width: 200px;", placeholder: "Search", onchange: "inputChanged"}, {kind: "Image", src: "assets/search-input-search.png"} ]}, {kind: "onyx.Button", content: "_new".loc(), ontap: "newRecord", style: "float: right;" } ]}, {name: "contentPanels", kind: "Panels", arrangerKind: "LeftRightArranger", margin: 0, fit: true, panelCount: 0, onTransitionFinish: "finishedTransition"} ]}, {kind: "Signals", onModelSave: "refreshInfoObject"} ], fetched: {}, activate: function () { this.setMenuPanel(MODULE_MENU); }, backTapped: function () { var index = this.$.menuPanels.getIndex(); if (index === MODULE_MENU) { this.warnLogout(); } else { this.setMenuPanel(MODULE_MENU); } }, create: function () { this.inherited(arguments); var modules = this.getModules() || [], label = this.getLabel(), panels, panel, i, n; this.$.leftLabel.setContent(label); // Build panels for (i = 0; i < modules.length; i++) { panels = modules[i].panels || []; for (n = 0; n < panels.length; n++) { // Keep track of where this panel is being placed for later reference panels[n].index = this.$.contentPanels.panelCount++; panel = this.$.contentPanels.createComponent(panels[n]); if (panel instanceof XV.List) { // Bubble parameter widget up to pullout this.doListAdded(panel); } } } this.$.moduleMenu.setCount(modules.length); }, finishedTransition: function (inSender, inEvent) { this.setContentPanel(inSender.index); }, getSelectedModule: function (index) { return this._selectedModule; }, inputChanged: function (inSender, inEvent) { var index = this.$.contentPanels.getIndex(), list = this.panels[index].name; this.fetched = {}; this.fetch(list); }, listItemTapped: function (inSender, inEvent) { var list = this.$.contentPanels.getActive(), workspace = list.getWorkspace(), id = list.getModel(inEvent.index).id; // Transition to workspace view, including the model id payload this.bubble("workspace", { eventName: "workspace", workspace: workspace, id: id }); return true; }, fetch: function (index, options) { index = index || this.$.contentPanels.getIndex(); var panel = this.$.contentPanels.getPanels()[index], name = panel ? panel.name : "", query, input, parameterWidget, parameters; if (!panel instanceof XV.List) { return; } query = panel.getQuery() || {}; input = this.$.searchInput.getValue(); parameterWidget = XT.app ? XT.app.getPullout().getItem(name) : null; parameters = parameterWidget ? parameterWidget.getParameters() : []; options = options ? _.clone(options) : {}; options.showMore = _.isBoolean(options.showMore) ? options.showMore : false; // Build parameters if (input || parameters.length) { query.parameters = []; // Input search parameters if (input) { query.parameters = [{ attribute: panel.getSearchableAttributes(), operator: 'MATCHES', value: this.$.searchInput.getValue() }]; } // Advanced parameters if (parameters) { query.parameters = query.parameters.concat(parameters); } } else { delete query.parameters; } panel.setQuery(query); panel.fetch(options); this.fetched[index] = true; }, newRecord: function (inSender, inEvent) { var list = this.$.contentPanels.getActive(), workspace = list.getWorkspace(); this.bubble("workspace", { eventName: "workspace", workspace: workspace }); return true; }, menuItemTap: function (inSender, inEvent) { this.setContentPanel(inEvent.index); }, moduleItemTap: function (inSender, inEvent) { //this.setModule(inEvent.index); }, requery: function (inSender, inEvent) { this.fetch(); }, scrolled: function (inSender, inEvent) { if (inEvent.originator instanceof XV.List === false) { return; } var list = inEvent.originator, max = list.getScrollBounds().maxTop - list.rowHeight * FETCH_TRIGGER, options = {}; if (list.getIsMore() && list.getScrollPosition() > max && !list.getIsFetching()) { list.setIsFetching(true); options.showMore = true; this.fetch(list.name, options); } }, setContentPanel: function (index) { var module = this.getSelectedModule(), panelIndex = module && module.panels ? module.panels[index].index : -1, panel = panelIndex > -1 ? this.$.contentPanels.getPanels()[panelIndex] : null, label = panel ? panel.getLabel() : ""; if (!panel) { return; } // Select panelMenu if (!this.$.panelMenu.isSelected(index)) { this.$.panelMenu.select(index); } // Select list if (this.$.contentPanels.getIndex() !== panelIndex) { this.$.contentPanels.setIndex(panelIndex); } this.$.rightLabel.setContent(label); if (panel.fetch && !this.fetched[panelIndex]) { this.fetch(panelIndex); } }, setMenuPanel: function (index) { var label = index ? "_back".loc() : "_logout".loc(); this.$.menuPanels.setIndex(index); this.$.menuPanels.getActive().select(0); this.setContentPanel(0); this.$.backButton.setContent(label); }, setModule: function (index) { var module = this.getModules()[index], panels = module.panels || []; if (module !== this._selectedModule) { this._selectedModule = module; if (panels.length) { this.$.panelMenu.setCount(panels.length); this.setMenuPanel(PANEL_MENU); } } }, setupModuleMenuItem: function (inSender, inEvent) { var index = inEvent.index, label = this.modules[index].label, isSelected = inSender.isSelected(index); this.$.moduleItem.setContent(label); this.$.moduleItem.addRemoveClass("onyx-selected", isSelected); if (isSelected) { this.setModule(index); } }, setupPanelMenuItem: function (inSender, inEvent) { var module = this.getSelectedModule(), panel; panel = module.panels[inEvent.index].name; this.$.listItem.setContent(this.$.contentPanels.$[panel].getLabel()); this.$.listItem.addRemoveClass("onyx-selected", inSender.isSelected(inEvent.index)); }, showHistory: function (inSender, inEvent) { var panel = {name: 'history'}; this.doTogglePullout(panel); }, showParameters: function (inSender, inEvent) { var panel = this.$.contentPanels.getActive(); this.doTogglePullout(panel); }, /** * If a model has changed, check the panels of this module to see if we can * update the info object in the list. * XXX if there are multiple modules alive then all of them will catch * XXX the signal, which isn't ideal for performance */ refreshInfoObject: function (inSender, inPayload) { // obnoxious massaging. Can't think of an elegant way to do this. // salt in wounds: in setup we massage by adding List on the end, but with // crm we massage by adding List on the end. This is horrible. // XXX not sustainable var listBase = XV.util.stripModelNamePrefix(inPayload.recordType).camelize(), listName = this.name === "setup" ? listBase + "List" : listBase + "List", list = this.$.contentPanels.$[listName]; /** * If the update model is part of a cached collection, refresh the cache * XXX This string massaging should be refactored into intelligence within * the collection itself. * XXX this part will happen for each living module. But it only needs to * be refreshed once. Moving away from signals would solve this. Or we * could create a dedicated signal event. */ var cacheName; if (listBase.charAt(listBase.length - 1) === 'y') { cacheName = listBase.substring(0, listBase.length - 1) + 'ies'; } else { cacheName = listBase + 's'; } if (XM[cacheName]) { XM[cacheName].fetch(); // no need to fetch the model itself, but we do want to tell the // module that contains the list to refresh that list by setting // the fetched property to false if (this.fetched[listName]) { this.fetched[listName] = false; } return; } /** * Update the model itself */ if (!list) { // we don't have this model on our list. No need to update return; } var model = _.find(list.collection.models, function (model) { return model.id === inPayload.id; }); if (!model) { // this model isn't in the list. No need to update return; } model.fetch(); }, /** Logout management. We show the user a warning popup before we log them out. */ warnLogout: function () { this.$.logoutPopup.show(); }, closeLogoutPopup: function () { this.$.logoutPopup.hide(); }, logout: function () { this.$.logoutPopup.hide(); XT.session.logout(); }, /** Manually set one of the icon buttons to be active. Note passing null as the parameter will disactivate all icons. */ setActiveIconButton: function (buttonName) { var activeIconButton = null; if (buttonName === 'search') { activeIconButton = this.$.searchIconButton; } else if (buttonName === 'history') { activeIconButton = this.$.historyIconButton; } this.$.iconButtonGroup.setActive(activeIconButton); } }); }());
getting there...
source/xv/views/module.js
getting there...
<ide><path>ource/xv/views/module.js <ide> {kind: "onyx.Button", content: "_new".loc(), ontap: "newRecord", <ide> style: "float: right;" } <ide> ]}, <del> {name: "contentPanels", kind: "Panels", arrangerKind: "LeftRightArranger", <del> margin: 0, fit: true, panelCount: 0, onTransitionFinish: "finishedTransition"} <add> {name: "contentPanels", kind: "Panels", margin: 0, fit: true, <add> draggable: false, panelCount: 0} <ide> ]}, <ide> {kind: "Signals", onModelSave: "refreshInfoObject"} <ide> ], <ide> } <ide> } <ide> this.$.moduleMenu.setCount(modules.length); <del> }, <del> finishedTransition: function (inSender, inEvent) { <del> this.setContentPanel(inSender.index); <ide> }, <ide> getSelectedModule: function (index) { <ide> return this._selectedModule;
JavaScript
apache-2.0
4aa8463d0a53f3765f4b150d4c9ac8e6b01c0968
0
oxygenxml/webapp-charpicker-plugin,oxygenxml/webapp-charpicker-plugin,oxygenxml/webapp-charpicker-plugin
(function () { goog.events.listen(workspace, sync.api.Workspace.EventType.BEFORE_EDITOR_LOADED, function (e) { //quickly change urls that have the plugin name hardcoded var pluginResourcesFolder = 'char-picker'; var localStorageUsable = function () { if (typeof (Storage) !== 'undefined') { return 1; } else { console.log('localstorage not supported'); return 0; } }; var storedRecentChars = function () { if (localStorage.getItem("recentlyUsedCharacters")) { return 1; } else{ console.log('there are no recentCharacters set'); return 0; } }; var removeDuplicates = function (arr) { return arr.filter(function(item, pos) { return arr.indexOf(item) == pos; }); }; var capitalizeWords = function(text) { var splitText = text.toLowerCase().split(' '); for(var i = 0; i < splitText.length; i++) { splitText[i] = splitText[i].substr(0,1).toUpperCase() + splitText[i].substring(1); } return splitText.join(' '); }; var displayRecentCharacters = function () { var defaultRecentCharacters = ["\u20ac", "\u00a3", "\u00a5", "\u00a2", "\u00a9", "\u00ae", "\u2122", "\u03b1", "\u03b2", "\u03c0", "\u03bc", "\u03a3", "\u03a9", "\u2264", "\u2265", "\u2260", "\u221e", "\u00b1", "\u00f7", "\u00d7", "\u21d2"] /* selector for targeting the recent characters container */ var container = document.querySelector('.recentCharactersGrid'); /* remove all recent characters to add the new ones again */ var fc = container.firstChild; while( fc ) { container.removeChild( fc ); fc = container.firstChild; } var characters = []; if (localStorageUsable()) { if (storedRecentChars()) { characters = JSON.parse(localStorage.getItem("recentlyUsedCharacters")); } } /* adjust the character array so it is the desired length. Fill it up with default recent characters if needed. */ var maxChars = 21; if (characters.length < maxChars) { characters = characters.concat(defaultRecentCharacters); characters = removeDuplicates(characters).slice(0, maxChars); localStorage.setItem("recentlyUsedCharacters", JSON.stringify(characters)); } else if (characters.length > maxChars) { characters = characters.slice(0, maxChars); localStorage.setItem("recentlyUsedCharacters", JSON.stringify(characters)); } /* add the characters to the container */ for (i = 0; i < characters.length; i++) { container.appendChild(goog.dom.createDom('div', { 'class': 'goog-inline-block goog-flat-button char-select-button' }, characters[i])); } }; var updateCharPreview = function(e) { var symbol = e.target.innerHTML; var symbolCode = e.target.getAttribute('data-symbol-hexcode'); var symbolName = e.target.getAttribute('data-symbol-name'); document.getElementById('previewCharacterDetails').innerHTML = '<div id="previewSymbol">' + symbol + '</div><div id="previewSymbolName">' + symbolName + ' <span style="white-space: nowrap; vertical-align: top">(' + symbolCode + ')</span></div>'; }; var InsertFromMenuAction = function (editor) { this.editor = editor; this.dialog = workspace.createDialog(); this.dialog.setTitle('Insert Special Characters'); }; InsertFromMenuAction.prototype = new sync.actions.AbstractAction(''); InsertFromMenuAction.prototype.getDisplayName = function () { return 'insert from menu'; }; var myIconUrl = sync.util.computeHdpiIcon('../plugin-resources/' + pluginResourcesFolder + '/InsertFromCharactersMap24.png'); InsertFromMenuAction.prototype.getLargeIcon = function () { return myIconUrl; }; InsertFromMenuAction.prototype.displayDialog = function () { window.charsToBeInserted = []; // if dialog has not been opened yet, load it if(document.getElementById('charpickeriframe') === null) { var tabContainer = goog.dom.createDom('div', {class: 'tabsContainer'}); tabContainer.innerHTML = '<ul><li><input type="radio" name="tabsContainer-0" id="tabsContainer-0-0" checked="checked" />' + '<label for="tabsContainer-0-0">By name</label><div id="charpicker-search-by-name"></div></li>' + '<li><input type="radio" name="tabsContainer-0" id="tabsContainer-0-1" />' + '<label for="tabsContainer-0-1">By categories<span class="low-width-hide"> or hex code</span></label><div id="charpicker-advanced"></div></li></ul>'; var charPickerIframe = goog.dom.createDom('iframe', { 'id': 'charpickeriframe', 'src': '../plugin-resources/' + pluginResourcesFolder + '/charpicker.html' }); this.dialog.getElement().id = 'charPicker'; this.dialog.getElement().appendChild(tabContainer); this.dialog.getElement().parentElement.classList.add("dialogContainer"); var searchByNameContainer = document.getElementById("charpicker-search-by-name"); searchByNameContainer.innerHTML = '<div style="line-height: 1.2em; height:57px;">Name of character to search for: <br> <input type="text" class="charpicker-input" name="searchName" id="searchName"></div>' + '<div id="foundByNameList"></div>'; var previewCharacterDetails = goog.dom.createDom('div', {'id': 'previewCharacterDetails'}); document.getElementById('charpicker-search-by-name').appendChild(previewCharacterDetails); goog.events.listen(document.getElementById('foundByNameList'), goog.events.EventType.MOUSEOVER, function (e){ if(e.target.id !== 'foundByNameList'){ updateCharPreview(e); } } ); goog.events.listen(document.getElementById('foundByNameList'), goog.events.EventType.CLICK, function (e){ if(e.target.id !== 'foundByNameList'){ updateCharPreview(e); var symbol = e.target.innerHTML; charsToBeInserted.push(symbol); document.getElementById('special_characters').value += symbol; } } ); goog.require('goog.net.XhrIo'); var findCharByName = function() { var name = document.getElementById("searchName").value; // clear boxes to get ready for results document.getElementById("foundByNameList").innerHTML = ''; document.getElementById("previewCharacterDetails").innerHTML = ''; if(name.length !== 0){ var url = "../plugins-dispatcher/charpicker-plugin?q=" + encodeURIComponent(name); goog.net.XhrIo.send(url, function(e){ var xhr = e.target; var obj = xhr.getResponseJson(); for(var code in obj) { var foundByNameItem = goog.dom.createDom('div', {'class': 'characterListSymbol', 'data-symbol-name': capitalizeWords(obj[code]), 'data-symbol-hexcode': code}); var decimalCode = parseInt(code, 16); foundByNameItem.innerHTML = String.fromCharCode(decimalCode); document.getElementById("foundByNameList").appendChild(foundByNameItem); } localStorage.setItem("lastCharacterSearch", name); }, "GET"); } }; // execute query automatically after user stops typing var typingPause = 500; var timeoutfunction; // execute query immediately when user presses enter in the input, prevent dialog closing goog.events.listen(document.getElementById('searchName'), goog.events.EventType.KEYDOWN, function(e){ if(e.keyCode === 13) { e.preventDefault(); clearTimeout(timeoutfunction); findCharByName(); } } ); // execute query after delay on keyup goog.events.listen(document.getElementById("searchName"), goog.events.EventType.KEYUP, function(e) { // if the key is enter a search is triggered already on keydown if (e.keyCode !== 13){ clearTimeout(timeoutfunction); timeoutfunction = setTimeout(findCharByName, typingPause); } } ); document.getElementById('charpicker-advanced').appendChild(charPickerIframe); var div = goog.dom.createDom('div'); div.id = "selectedCharsWrapper"; div.innerHTML = '<span>Selected characters:</span>' + '<input type="text" name="charsToBeInserted" class="charpicker-input" id="special_characters" onFocus="this.setSelectionRange(0, this.value.length)" readonly/>' + '<button id="removeLastChar" class="goog-button goog-char-picker-okbutton" title="Remove last character" value=""></button>'; this.dialog.getElement().appendChild(div); var textarea = document.getElementById('special_characters'); textarea.scrollTop = textarea.scrollHeight; goog.events.listen(this.dialog.getElement().querySelector('#removeLastChar'), goog.events.EventType.CLICK, function(){ var preview = document.getElementById('special_characters'); preview.value = ''; charsToBeInserted.pop(); for(var i=0;i<charsToBeInserted.length;i++){ preview.value += charsToBeInserted[i]; } }); } // if dialog has been populated already just reset the textboxes else { this.dialog.getElement().querySelector('#special_characters').value = ''; var searchbox = this.dialog.getElement().querySelector('#searchName'); searchbox.value = ''; if(localStorage.getItem("lastCharacterSearch") !== null){ searchbox.setAttribute("placeholder", localStorage.getItem("lastCharacterSearch") ); } var iframe = this.dialog.getElement().querySelector('#charpickeriframe'); var iframeContent = (iframe.contentWindow || iframe.contentDocument); if (iframeContent.document) { iframeContent = iframeContent.document; iframeContent.querySelector('.goog-char-picker-input-box').value = ''; } else { console.log('failed to get iframe contents'); } } this.dialog.onSelect(function (key) { // DIALOG INSERT GRID if (key == 'ok') { var dialogInsertChars = charsToBeInserted; if (dialogInsertChars) { var stringifiedText = ''; for(i = 0; i < dialogInsertChars.length; i++){ stringifiedText += dialogInsertChars[i]; } editor.getActionsManager().invokeOperation( 'ro.sync.ecss.extensions.commons.operations.InsertOrReplaceFragmentOperation', { fragment: stringifiedText }, function () { if (localStorageUsable()) { /* if using the localStorage is possible, add the text to the START of the array - queue system */ if (storedRecentChars()) { var characters = JSON.parse(localStorage.getItem("recentlyUsedCharacters")); characters = (dialogInsertChars.reverse()).concat(characters); characters = removeDuplicates(characters); localStorage.setItem("recentlyUsedCharacters", JSON.stringify(characters)); displayRecentCharacters(); } else { characters = dialogInsertChars; localStorage.setItem("recentlyUsedCharacters", JSON.stringify(characters)); displayRecentCharacters(); } } }) } } }); this.dialog.show(); }; InsertFromMenuAction.prototype.init = function () { window.charsToBeInserted = []; this.csmenu = new goog.ui.PopupMenu(); //overwrite the handleBlur function to prevent the popup from closing after inserting a character this.csmenu.handleBlur = function () { }; var moreSymbols = new goog.ui.MenuItem('More symbols...'); this.csmenu.addChild(moreSymbols, true); moreSymbols.setId('moreSymbolsButton'); var charPickerDialog = new InsertFromMenuAction(this.editor); goog.events.listen(moreSymbols, goog.ui.Component.EventType.ACTION, goog.bind(charPickerDialog.displayDialog, charPickerDialog)); this.csmenu.render(document.body); goog.dom.setProperties(this.csmenu.getElement(), {'id': 'pickermenu'}); // add the characters grid before the "more symbols..." button var parentElement = this.csmenu.getElement(); var theFirstChild = parentElement.firstChild; var newElement = goog.dom.createDom('div', { 'class': 'goog-char-picker-grid recentCharactersGrid', 'id': 'simplePickerGrid' }); parentElement.insertBefore(newElement, theFirstChild); this.csmenu.setToggleMode(true); // QUICK INSERT GRID goog.events.listen(document.querySelector('.goog-char-picker-grid'), goog.events.EventType.CLICK, function (e) { if (goog.dom.classlist.contains(e.target, 'goog-flat-button')) { editor.getActionsManager().invokeOperation( 'ro.sync.ecss.extensions.commons.operations.InsertOrReplaceFragmentOperation', { fragment: e.target.innerHTML }, function () { var quickInsertChar = e.target.innerHTML; if (localStorageUsable()) { /* if using the localStorage is possible, add the character to the START of the array - queue system */ if (storedRecentChars()) { var characters = JSON.parse(localStorage.getItem("recentlyUsedCharacters")); characters.unshift(quickInsertChar); characters = removeDuplicates(characters); localStorage.setItem("recentlyUsedCharacters", JSON.stringify(characters)); } else { characters = []; characters.unshift(quickInsertChar); localStorage.setItem("recentlyUsedCharacters", JSON.stringify(characters)); } } }) } }); }; InsertFromMenuAction.prototype.actionPerformed = function (callback) { if (this.csmenu.isOrWasRecentlyVisible()) { this.csmenu.hide(); } else { displayRecentCharacters(); this.csmenu.showAtElement( document.querySelector('[name=insertfrommenu]'), goog.positioning.Corner.BOTTOM_START); } }; var editor = e.editor; var insertFromMenu = new InsertFromMenuAction(editor); editor.getActionsManager().registerAction('insertfrommenu', insertFromMenu); var addActionOnce = 0; addToFrameworkToolbar(editor); function addToFrameworkToolbar(editor) { goog.events.listen(editor, sync.api.Editor.EventTypes.ACTIONS_LOADED, function (e) { var actionsConfig = e.actionsConfiguration; var frameworkToolbar = null; if (actionsConfig.toolbars) { for (var i = 0; i < actionsConfig.toolbars.length; i++) { var toolbar = actionsConfig.toolbars[i]; if (toolbar.name !== "Review" && toolbar.name !== "Builtin") { frameworkToolbar = toolbar; } } } // adds the action only once, on the first toolbar that is not Review or Builtin if (frameworkToolbar && addActionOnce === 0) { addActionOnce++; frameworkToolbar.children.push({ id: 'insertfrommenu', type: "action" }); setTimeout(function () { insertFromMenu.init(); document.getElementsByName("insertfrommenu")[0].setAttribute("title", "Insert a special character."); alert("charpicker loaded"); }, 0) } }); }; sync.util.loadCSSFile("../plugin-resources/" + pluginResourcesFolder + "/css/plugin.css"); }) })();
web/plugin.js
(function () { goog.events.listen(workspace, sync.api.Workspace.EventType.BEFORE_EDITOR_LOADED, function (e) { //quickly change urls that have the plugin name hardcoded var pluginResourcesFolder = 'char-picker'; var localStorageUsable = function () { if (typeof (Storage) !== 'undefined') { return 1; } else { console.log('localstorage not supported'); return 0; } }; var storedRecentChars = function () { if (localStorage.getItem("recentlyUsedCharacters")) { return 1; } else{ console.log('there are no recentCharacters set'); return 0; } }; var removeDuplicates = function (arr) { return arr.filter(function(item, pos) { return arr.indexOf(item) == pos; }); }; var capitalizeWords = function(text) { var splitText = text.toLowerCase().split(' '); for(var i = 0; i < splitText.length; i++) { splitText[i] = splitText[i].substr(0,1).toUpperCase() + splitText[i].substring(1); } return splitText.join(' '); }; var displayRecentCharacters = function () { var defaultRecentCharacters = ["\u20ac", "\u00a3", "\u00a5", "\u00a2", "\u00a9", "\u00ae", "\u2122", "\u03b1", "\u03b2", "\u03c0", "\u03bc", "\u03a3", "\u03a9", "\u2264", "\u2265", "\u2260", "\u221e", "\u00b1", "\u00f7", "\u00d7", "\u21d2"] /* selector for targeting the recent characters container */ var container = document.querySelector('.recentCharactersGrid'); /* remove all recent characters to add the new ones again */ var fc = container.firstChild; while( fc ) { container.removeChild( fc ); fc = container.firstChild; } var characters = []; if (localStorageUsable()) { if (storedRecentChars()) { characters = JSON.parse(localStorage.getItem("recentlyUsedCharacters")); } } /* adjust the character array so it is the desired length. Fill it up with default recent characters if needed. */ var maxChars = 21; if (characters.length < maxChars) { characters = characters.concat(defaultRecentCharacters); characters = removeDuplicates(characters).slice(0, maxChars); localStorage.setItem("recentlyUsedCharacters", JSON.stringify(characters)); } else if (characters.length > maxChars) { characters = characters.slice(0, maxChars); localStorage.setItem("recentlyUsedCharacters", JSON.stringify(characters)); } /* add the characters to the container */ for (i = 0; i < characters.length; i++) { container.appendChild(goog.dom.createDom('div', { 'class': 'goog-inline-block goog-flat-button char-select-button' }, characters[i])); } }; var updateCharPreview = function(e) { var symbol = e.target.innerHTML; var symbolCode = e.target.getAttribute('data-symbol-hexcode'); var symbolName = e.target.getAttribute('data-symbol-name'); document.getElementById('previewCharacterDetails').innerHTML = '<div id="previewSymbol">' + symbol + '</div><div id="previewSymbolName">' + symbolName + ' <span style="white-space: nowrap; vertical-align: top">(' + symbolCode + ')</span></div>'; }; var InsertFromMenuAction = function (editor) { this.editor = editor; this.dialog = workspace.createDialog(); this.dialog.setTitle('Insert Special Characters'); }; InsertFromMenuAction.prototype = new sync.actions.AbstractAction(''); InsertFromMenuAction.prototype.getDisplayName = function () { return 'insert from menu'; }; var myIconUrl = sync.util.computeHdpiIcon('../plugin-resources/' + pluginResourcesFolder + '/InsertFromCharactersMap24.png'); InsertFromMenuAction.prototype.getLargeIcon = function () { return myIconUrl; }; InsertFromMenuAction.prototype.displayDialog = function () { window.charsToBeInserted = []; // if dialog has not been opened yet, load it if(document.getElementById('charpickeriframe') === null) { var tabContainer = goog.dom.createDom('div', {class: 'tabsContainer'}); tabContainer.innerHTML = '<ul><li><input type="radio" name="tabsContainer-0" id="tabsContainer-0-0" checked="checked" />' + '<label for="tabsContainer-0-0">By name</label><div id="charpicker-search-by-name"></div></li>' + '<li><input type="radio" name="tabsContainer-0" id="tabsContainer-0-1" />' + '<label for="tabsContainer-0-1">By categories<span class="low-width-hide"> or hex code</span></label><div id="charpicker-advanced"></div></li></ul>'; var charPickerIframe = goog.dom.createDom('iframe', { 'id': 'charpickeriframe', 'src': '../plugin-resources/' + pluginResourcesFolder + '/charpicker.html' }); this.dialog.getElement().id = 'charPicker'; this.dialog.getElement().appendChild(tabContainer); this.dialog.getElement().parentElement.classList.add("dialogContainer"); var searchByNameContainer = document.getElementById("charpicker-search-by-name"); searchByNameContainer.innerHTML = '<div style="line-height: 1.2em; height:57px;">Name of character to search for: <br> <input type="text" class="charpicker-input" name="searchName" id="searchName"></div>' + '<div id="foundByNameList"></div>'; var previewCharacterDetails = goog.dom.createDom('div', {'id': 'previewCharacterDetails'}); document.getElementById('charpicker-search-by-name').appendChild(previewCharacterDetails); goog.events.listen(document.getElementById('foundByNameList'), goog.events.EventType.MOUSEOVER, function (e){ if(e.target.id !== 'foundByNameList'){ updateCharPreview(e); } } ); goog.events.listen(document.getElementById('foundByNameList'), goog.events.EventType.CLICK, function (e){ if(e.target.id !== 'foundByNameList'){ updateCharPreview(e); var symbol = e.target.innerHTML; charsToBeInserted.push(symbol); document.getElementById('special_characters').value += symbol; } } ); goog.require('goog.net.XhrIo'); var findCharByName = function() { var name = document.getElementById("searchName").value; // clear boxes to get ready for results document.getElementById("foundByNameList").innerHTML = ''; document.getElementById("previewCharacterDetails").innerHTML = ''; if(name.length !== 0){ var url = "../plugins-dispatcher/charpicker-plugin?q=" + encodeURIComponent(name); goog.net.XhrIo.send(url, function(e){ var xhr = e.target; var obj = xhr.getResponseJson(); for(var code in obj) { var foundByNameItem = goog.dom.createDom('div', {'class': 'characterListSymbol', 'data-symbol-name': capitalizeWords(obj[code]), 'data-symbol-hexcode': code}); var decimalCode = parseInt(code, 16); foundByNameItem.innerHTML = String.fromCharCode(decimalCode); document.getElementById("foundByNameList").appendChild(foundByNameItem); } localStorage.setItem("lastCharacterSearch", name); }, "GET"); } }; // execute query automatically after user stops typing var typingPause = 500; var timeoutfunction; // execute query immediately when user presses enter in the input, prevent dialog closing goog.events.listen(document.getElementById('searchName'), goog.events.EventType.KEYDOWN, function(e){ if(e.keyCode === 13) { e.preventDefault(); clearTimeout(timeoutfunction); findCharByName(); } } ); // execute query after delay on keyup goog.events.listen(document.getElementById("searchName"), goog.events.EventType.KEYUP, function(e) { // if the key is enter a search is triggered already on keydown if (e.keyCode !== 13){ clearTimeout(timeoutfunction); timeoutfunction = setTimeout(findCharByName, typingPause); } } ); document.getElementById('charpicker-advanced').appendChild(charPickerIframe); var div = goog.dom.createDom('div'); div.id = "selectedCharsWrapper"; div.innerHTML = '<span>Selected characters:</span>' + '<input type="text" name="charsToBeInserted" class="charpicker-input" id="special_characters" onFocus="this.setSelectionRange(0, this.value.length)" readonly/>' + '<button id="removeLastChar" class="goog-button goog-char-picker-okbutton" title="Remove last character" value=""></button>'; this.dialog.getElement().appendChild(div); var textarea = document.getElementById('special_characters'); textarea.scrollTop = textarea.scrollHeight; goog.events.listen(this.dialog.getElement().querySelector('#removeLastChar'), goog.events.EventType.CLICK, function(){ var preview = document.getElementById('special_characters'); preview.value = ''; charsToBeInserted.pop(); for(var i=0;i<charsToBeInserted.length;i++){ preview.value += charsToBeInserted[i]; } }); } // if dialog has been populated already just reset the textboxes else { this.dialog.getElement().querySelector('#special_characters').value = ''; var searchbox = this.dialog.getElement().querySelector('#searchName'); searchbox.value = ''; if(localStorage.getItem("lastCharacterSearch") !== null){ searchbox.setAttribute("placeholder", localStorage.getItem("lastCharacterSearch") ); } var iframe = this.dialog.getElement().querySelector('#charpickeriframe'); var iframeContent = (iframe.contentWindow || iframe.contentDocument); if (iframeContent.document) { iframeContent = iframeContent.document; iframeContent.querySelector('.goog-char-picker-input-box').value = ''; } else { console.log('failed to get iframe contents'); } } this.dialog.onSelect(function (key) { // DIALOG INSERT GRID if (key == 'ok') { var dialogInsertChars = charsToBeInserted; if (dialogInsertChars) { var stringifiedText = ''; for(i = 0; i < dialogInsertChars.length; i++){ stringifiedText += dialogInsertChars[i]; } editor.getActionsManager().invokeOperation( 'ro.sync.ecss.extensions.commons.operations.InsertOrReplaceFragmentOperation', { fragment: stringifiedText }, function () { if (localStorageUsable()) { /* if using the localStorage is possible, add the text to the START of the array - queue system */ if (storedRecentChars()) { var characters = JSON.parse(localStorage.getItem("recentlyUsedCharacters")); characters = (dialogInsertChars.reverse()).concat(characters); characters = removeDuplicates(characters); localStorage.setItem("recentlyUsedCharacters", JSON.stringify(characters)); displayRecentCharacters(); } else { characters = dialogInsertChars; localStorage.setItem("recentlyUsedCharacters", JSON.stringify(characters)); displayRecentCharacters(); } } }) } } }); this.dialog.show(); }; InsertFromMenuAction.prototype.init = function () { window.charsToBeInserted = []; this.csmenu = new goog.ui.PopupMenu(); //overwrite the handleBlur function to prevent the popup from closing after inserting a character this.csmenu.handleBlur = function () { }; var moreSymbols = new goog.ui.MenuItem('More symbols...'); this.csmenu.addChild(moreSymbols, true); moreSymbols.setId('moreSymbolsButton'); var charPickerDialog = new InsertFromMenuAction(this.editor); goog.events.listen(moreSymbols, goog.ui.Component.EventType.ACTION, goog.bind(charPickerDialog.displayDialog, charPickerDialog)); this.csmenu.render(document.body); goog.dom.setProperties(this.csmenu.getElement(), {'id': 'pickermenu'}); // add the characters grid before the "more symbols..." button var parentElement = this.csmenu.getElement(); var theFirstChild = parentElement.firstChild; var newElement = goog.dom.createDom('div', { 'class': 'goog-char-picker-grid recentCharactersGrid', 'id': 'simplePickerGrid' }); parentElement.insertBefore(newElement, theFirstChild); this.csmenu.setToggleMode(true); // QUICK INSERT GRID goog.events.listen(document.querySelector('.goog-char-picker-grid'), goog.events.EventType.CLICK, function (e) { if (goog.dom.classlist.contains(e.target, 'goog-flat-button')) { editor.getActionsManager().invokeOperation( 'ro.sync.ecss.extensions.commons.operations.InsertOrReplaceFragmentOperation', { fragment: e.target.innerHTML }, function () { var quickInsertChar = e.target.innerHTML; if (localStorageUsable()) { /* if using the localStorage is possible, add the character to the START of the array - queue system */ if (storedRecentChars()) { var characters = JSON.parse(localStorage.getItem("recentlyUsedCharacters")); characters.unshift(quickInsertChar); characters = removeDuplicates(characters); localStorage.setItem("recentlyUsedCharacters", JSON.stringify(characters)); } else { characters = []; characters.unshift(quickInsertChar); localStorage.setItem("recentlyUsedCharacters", JSON.stringify(characters)); } } }) } }); }; InsertFromMenuAction.prototype.actionPerformed = function (callback) { if (this.csmenu.isOrWasRecentlyVisible()) { this.csmenu.hide(); } else { displayRecentCharacters(); this.csmenu.showAtElement( document.querySelector('[name=insertfrommenu]'), goog.positioning.Corner.BOTTOM_START); } }; var editor = e.editor; var insertFromMenu = new InsertFromMenuAction(editor); editor.getActionsManager().registerAction('insertfrommenu', insertFromMenu); var addActionOnce = 0; addToFrameworkToolbar(editor); function addToFrameworkToolbar(editor) { goog.events.listen(editor, sync.api.Editor.EventTypes.ACTIONS_LOADED, function (e) { var actionsConfig = e.actionsConfiguration; var frameworkToolbar = null; if (actionsConfig.toolbars) { for (var i = 0; i < actionsConfig.toolbars.length; i++) { var toolbar = actionsConfig.toolbars[i]; if (toolbar.name !== "Review" && toolbar.name !== "Builtin") { frameworkToolbar = toolbar; } } } // adds the action only once, on the first toolbar that is not Review or Builtin if (frameworkToolbar && addActionOnce === 0) { addActionOnce++; frameworkToolbar.children.push({ id: 'insertfrommenu', type: "action" }); setTimeout(function () { insertFromMenu.init(); document.getElementsByName("insertfrommenu")[0].setAttribute("title", "Insert a special character."); }, 0) } }); }; sync.util.loadCSSFile("../plugin-resources/" + pluginResourcesFolder + "/css/plugin.css"); }) })();
added alert for selenium tests
web/plugin.js
added alert for selenium tests
<ide><path>eb/plugin.js <ide> setTimeout(function () { <ide> insertFromMenu.init(); <ide> document.getElementsByName("insertfrommenu")[0].setAttribute("title", "Insert a special character."); <add> alert("charpicker loaded"); <ide> }, 0) <ide> } <ide> });
Java
apache-2.0
366855e229fd9863ccc0cf3d4420e0ebb5a451ff
0
compomics/pride-asa-pipeline
package com.compomics.pride_asa_pipeline.config; import com.compomics.pride_asa_pipeline.util.FileUtils; import java.io.File; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.log4j.Logger; /** * Created by IntelliJ IDEA. User: niels Date: 9/11/11 Time: 13:41 To change * this template use File | Settings | File Templates. */ public class PropertiesConfigurationHolder extends PropertiesConfiguration { private static final Logger LOGGER = Logger.getLogger(PropertiesConfigurationHolder.class); private static PropertiesConfigurationHolder ourInstance; static { try { File propertiesFile = FileUtils.getFileByRelativePath("resources/pride_asa_pipeline.properties"); ourInstance = new PropertiesConfigurationHolder(propertiesFile); } catch (ConfigurationException e) { LOGGER.error(e.getMessage(), e); } } /** * Gets the PropertiesConfiguration instance * * @return */ public static PropertiesConfigurationHolder getInstance() { return ourInstance; } private PropertiesConfigurationHolder(File propertiesFile) throws ConfigurationException { super(propertiesFile); } }
src/main/java/com/compomics/pride_asa_pipeline/config/PropertiesConfigurationHolder.java
package com.compomics.pride_asa_pipeline.config; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.log4j.Logger; /** * Created by IntelliJ IDEA. * User: niels * Date: 9/11/11 * Time: 13:41 * To change this template use File | Settings | File Templates. */ public class PropertiesConfigurationHolder extends PropertiesConfiguration { private static final Logger LOGGER = Logger.getLogger(PropertiesConfigurationHolder.class); private static PropertiesConfigurationHolder ourInstance; static { try { ourInstance = new PropertiesConfigurationHolder("resources/pride_asa_pipeline.properties"); } catch (ConfigurationException e) { LOGGER.error(e.getMessage(), e); } } /** * Gets the PropertiesConfiguration instance * * @return */ public static PropertiesConfigurationHolder getInstance() { return ourInstance; } private PropertiesConfigurationHolder(String propertiesFileName) throws ConfigurationException { super(propertiesFileName); } }
changed holder: now using file constructor instead of string constructor
src/main/java/com/compomics/pride_asa_pipeline/config/PropertiesConfigurationHolder.java
changed holder: now using file constructor instead of string constructor
<ide><path>rc/main/java/com/compomics/pride_asa_pipeline/config/PropertiesConfigurationHolder.java <ide> package com.compomics.pride_asa_pipeline.config; <ide> <add>import com.compomics.pride_asa_pipeline.util.FileUtils; <add>import java.io.File; <ide> import org.apache.commons.configuration.ConfigurationException; <ide> import org.apache.commons.configuration.PropertiesConfiguration; <ide> import org.apache.log4j.Logger; <ide> <ide> /** <del> * Created by IntelliJ IDEA. <del> * User: niels <del> * Date: 9/11/11 <del> * Time: 13:41 <del> * To change this template use File | Settings | File Templates. <add> * Created by IntelliJ IDEA. User: niels Date: 9/11/11 Time: 13:41 To change <add> * this template use File | Settings | File Templates. <ide> */ <ide> public class PropertiesConfigurationHolder extends PropertiesConfiguration { <del> <add> <ide> private static final Logger LOGGER = Logger.getLogger(PropertiesConfigurationHolder.class); <del> <ide> private static PropertiesConfigurationHolder ourInstance; <ide> <ide> static { <ide> try { <del> ourInstance = new PropertiesConfigurationHolder("resources/pride_asa_pipeline.properties"); <add> File propertiesFile = FileUtils.getFileByRelativePath("resources/pride_asa_pipeline.properties"); <add> ourInstance = new PropertiesConfigurationHolder(propertiesFile); <ide> } catch (ConfigurationException e) { <ide> LOGGER.error(e.getMessage(), e); <ide> } <ide> } <del> <add> <ide> /** <ide> * Gets the PropertiesConfiguration instance <del> * <del> * @return <add> * <add> * @return <ide> */ <ide> public static PropertiesConfigurationHolder getInstance() { <ide> return ourInstance; <ide> } <ide> <del> private PropertiesConfigurationHolder(String propertiesFileName) throws ConfigurationException { <del> super(propertiesFileName); <add> private PropertiesConfigurationHolder(File propertiesFile) throws ConfigurationException { <add> super(propertiesFile); <ide> } <del> <ide> }
Java
lgpl-2.1
2c71d1d55f5e65c393f5821e704b08152a9e0886
0
brltty/brltty,brltty/brltty,brltty/brltty,brltty/brltty,brltty/brltty,brltty/brltty
/* * BRLTTY - A background process providing access to the console screen (when in * text mode) for a blind person using a refreshable braille display. * * Copyright (C) 1995-2013 by The BRLTTY Developers. * * BRLTTY comes with ABSOLUTELY NO WARRANTY. * * This is free software, placed under the terms of the * GNU General Public License, as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any * later version. Please see the file LICENSE-GPL for details. * * Web Page: http://mielke.cc/brltty/ * * This software is maintained by Dave Mielke <[email protected]>. */ package org.a11y.brltty.android; import org.a11y.brltty.core.*; import java.util.Collections; import java.util.ArrayList; import java.util.Map; import java.util.Set; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.File; import java.io.FileOutputStream; import android.util.Log; import android.content.Context; import android.content.res.AssetManager; import android.content.SharedPreferences; public class CoreThread extends Thread { private static final String LOG_TAG = CoreThread.class.getName(); private final Context coreContext; public static final int DATA_MODE = Context.MODE_PRIVATE; public static final String DATA_TYPE_TABLES = "tables"; public static final String DATA_TYPE_DRIVERS = "drivers"; public static final String DATA_TYPE_STATE = "state"; private final File getDataDirectory (String type) { return coreContext.getDir(type, DATA_MODE); } private final void extractAsset (AssetManager assets, String type, File path) { String asset = new File(type, path.getName()).getPath(); Log.d(LOG_TAG, "extracting asset: " + asset + " -> " + path); try { InputStream input = null; OutputStream output = null; try { input = assets.open(asset); output = new FileOutputStream(path); byte[] buffer = new byte[0X4000]; int count; while ((count = input.read(buffer)) > 0) { output.write(buffer, 0, count); } } finally { if (input != null) { input.close(); } if (output != null) { output.close(); } } } catch (IOException exception) { Log.e(LOG_TAG, "cannot extract asset: " + asset + " -> " + path, exception); } } private final void extractAssets (AssetManager assets, String type, boolean executable) { File directory = getDataDirectory(type); if (!directory.canWrite()) { directory.setWritable(true, true); } for (File file : directory.listFiles()) { file.delete(); } try { String[] files = assets.list(type); for (String file : files) { File path = new File(directory, file); extractAsset(assets, type, path); path.setReadOnly(); if (executable) { path.setExecutable(true, false); } } directory.setReadOnly(); } catch (IOException exception) { Log.e(LOG_TAG, "cannot list assets directory: " + type, exception); } } private final void extractAssets () { AssetManager assets = coreContext.getAssets(); extractAssets(assets, DATA_TYPE_TABLES, false); extractAssets(assets, DATA_TYPE_DRIVERS, true); } CoreThread () { super("Core"); coreContext = ApplicationHooks.getContext(); } private String getStringResource (int resource) { return coreContext.getResources().getString(resource); } private String getStringSetting (int key, String defaultValue) { return ApplicationUtilities.getSharedPreferences().getString(getStringResource(key), defaultValue); } private String getStringSetting (int key, int defaultValue) { return getStringSetting(key, getStringResource(defaultValue)); } private String getStringSetting (int key) { return ApplicationUtilities.getSharedPreferences().getString(getStringResource(key), ""); } private Set<String> getStringSetSetting (int key) { return ApplicationUtilities.getSharedPreferences().getStringSet(getStringResource(key), Collections.EMPTY_SET); } private String[] makeArguments () { ArgumentsBuilder builder = new ArgumentsBuilder(); builder.setForegroundExecution(true); builder.setReleaseDevice(true); builder.setTablesDirectory(getDataDirectory(DATA_TYPE_TABLES).getPath()); builder.setDriversDirectory(getDataDirectory(DATA_TYPE_DRIVERS).getPath()); builder.setWritableDirectory(coreContext.getFilesDir().getPath()); File stateDirectory = getDataDirectory(DATA_TYPE_STATE); builder.setConfigurationFile(new File(stateDirectory, "default.conf").getPath()); builder.setPreferencesFile(new File(stateDirectory, "default.prefs").getPath()); builder.setTextTable(getStringSetting(R.string.PREF_KEY_TEXT_TABLE, R.string.DEFAULT_TEXT_TABLE)); builder.setAttributesTable(getStringSetting(R.string.PREF_KEY_ATTRIBUTES_TABLE, R.string.DEFAULT_ATTRIBUTES_TABLE)); builder.setContractionTable(getStringSetting(R.string.PREF_KEY_CONTRACTION_TABLE, R.string.DEFAULT_CONTRACTION_TABLE)); builder.setKeyTable(getStringSetting(R.string.PREF_KEY_KEY_TABLE, R.string.DEFAULT_KEY_TABLE)); if ((new File(ApplicationParameters.B2G_DEVICE_PATH)).exists()) { builder.setBrailleDevice(ApplicationParameters.B2G_DEVICE_PATH); builder.setBrailleDriver(ApplicationParameters.B2G_DRIVER_CODE); } else { String name = getStringSetting(R.string.PREF_KEY_SELECTED_DEVICE); if (name.length() > 0) { Map<String, String> properties = SettingsActivity.getProperties( name, SettingsActivity.devicePropertyKeys, ApplicationUtilities.getSharedPreferences() ); String qualifier = properties.get(SettingsActivity.PREF_KEY_DEVICE_QUALIFIER); if (qualifier.length() > 0) { String reference = properties.get(SettingsActivity.PREF_KEY_DEVICE_REFERENCE); if (reference.length() > 0) { String driver = properties.get(SettingsActivity.PREF_KEY_DEVICE_DRIVER); if (driver.length() > 0) { builder.setBrailleDevice(qualifier + ":" + reference); builder.setBrailleDriver(driver); } } } } } builder.setSpeechDriver(getStringSetting(R.string.PREF_KEY_SPEECH_SUPPORT, R.string.DEFAULT_SPEECH_SUPPORT)); builder.setQuietIfNoBraille(true); { ArrayList<String> keywords = new ArrayList<String>(); keywords.add(getStringSetting(R.string.PREF_KEY_LOG_LEVEL, R.string.DEFAULT_LOG_LEVEL)); keywords.addAll(getStringSetSetting(R.string.PREF_KEY_LOG_CATEGORIES)); StringBuilder operand = new StringBuilder(); for (String keyword : keywords) { if (keyword.length() > 0) { if (operand.length() > 0) operand.append(','); operand.append(keyword); } } builder.setLogLevel(operand.toString()); } return builder.getArguments(); } @Override public void run () { { SharedPreferences prefs = ApplicationUtilities.getSharedPreferences(); File file = new File(coreContext.getPackageCodePath()); String prefKey_size = getStringResource(R.string.PREF_KEY_PACKAGE_SIZE); long oldSize = prefs.getLong(prefKey_size, -1); long newSize = file.length(); String prefKey_time = getStringResource(R.string.PREF_KEY_PACKAGE_TIME); long oldTime = prefs.getLong(prefKey_time, -1); long newTime = file.lastModified(); if ((newSize != oldSize) || (newTime != oldTime)) { Log.d(LOG_TAG, "package size: " + oldSize + " -> " + newSize); Log.d(LOG_TAG, "package time: " + oldTime + " -> " + newTime); extractAssets(); { SharedPreferences.Editor editor = prefs.edit(); editor.putLong(prefKey_size, newSize); editor.putLong(prefKey_time, newTime); editor.commit(); } } } BrailleRenderer.setBrailleRenderer(getStringSetting(R.string.PREF_KEY_NAVIGATION_MODE, R.string.DEFAULT_NAVIGATION_MODE)); UsbHelper.begin(); CoreWrapper.run(makeArguments()); UsbHelper.end(); } }
Android/Application/src/org/a11y/brltty/android/CoreThread.java
/* * BRLTTY - A background process providing access to the console screen (when in * text mode) for a blind person using a refreshable braille display. * * Copyright (C) 1995-2013 by The BRLTTY Developers. * * BRLTTY comes with ABSOLUTELY NO WARRANTY. * * This is free software, placed under the terms of the * GNU General Public License, as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any * later version. Please see the file LICENSE-GPL for details. * * Web Page: http://mielke.cc/brltty/ * * This software is maintained by Dave Mielke <[email protected]>. */ package org.a11y.brltty.android; import org.a11y.brltty.core.*; import java.util.Collections; import java.util.ArrayList; import java.util.Map; import java.util.Set; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.File; import java.io.FileOutputStream; import android.util.Log; import android.content.Context; import android.content.res.AssetManager; import android.content.SharedPreferences; public class CoreThread extends Thread { private static final String LOG_TAG = CoreThread.class.getName(); private final Context coreContext; public static final int DATA_MODE = Context.MODE_PRIVATE; public static final String DATA_TYPE_TABLES = "tables"; public static final String DATA_TYPE_DRIVERS = "drivers"; public static final String DATA_TYPE_STATE = "state"; private final File getDataDirectory (String type) { return coreContext.getDir(type, DATA_MODE); } private final void extractAsset (AssetManager assets, String type, File path) { String asset = new File(type, path.getName()).getPath(); Log.d(LOG_TAG, "extracting asset: " + asset + " -> " + path); try { InputStream input = null; OutputStream output = null; try { input = assets.open(asset); output = new FileOutputStream(path); byte[] buffer = new byte[0X4000]; int count; while ((count = input.read(buffer)) > 0) { output.write(buffer, 0, count); } } finally { if (input != null) { input.close(); } if (output != null) { output.close(); } } } catch (IOException exception) { Log.e(LOG_TAG, "cannot extract asset: " + asset + " -> " + path, exception); } } private final void extractAssets (AssetManager assets, String type, boolean executable) { File directory = getDataDirectory(type); if (!directory.canWrite()) { directory.setWritable(true, true); } for (File file : directory.listFiles()) { file.delete(); } try { String[] files = assets.list(type); for (String file : files) { File path = new File(directory, file); extractAsset(assets, type, path); path.setReadOnly(); if (executable) { path.setExecutable(true, false); } } directory.setReadOnly(); } catch (IOException exception) { Log.e(LOG_TAG, "cannot list assets directory: " + type, exception); } } private final void extractAssets () { AssetManager assets = coreContext.getAssets(); extractAssets(assets, DATA_TYPE_TABLES, false); extractAssets(assets, DATA_TYPE_DRIVERS, true); } CoreThread () { super("Core"); coreContext = ApplicationHooks.getContext(); } private String getStringResource (int resource) { return coreContext.getResources().getString(resource); } private String getStringSetting (int key, String defaultValue) { return ApplicationUtilities.getSharedPreferences().getString(getStringResource(key), defaultValue); } private String getStringSetting (int key, int defaultValue) { return getStringSetting(key, getStringResource(defaultValue)); } private String getStringSetting (int key) { return ApplicationUtilities.getSharedPreferences().getString(getStringResource(key), ""); } private Set<String> getStringSetSetting (int key) { return ApplicationUtilities.getSharedPreferences().getStringSet(getStringResource(key), Collections.EMPTY_SET); } private String[] makeArguments () { ArgumentsBuilder builder = new ArgumentsBuilder(); builder.setForegroundExecution(true); builder.setReleaseDevice(true); builder.setTablesDirectory(getDataDirectory(DATA_TYPE_TABLES).getPath()); builder.setDriversDirectory(getDataDirectory(DATA_TYPE_DRIVERS).getPath()); builder.setWritableDirectory(coreContext.getFilesDir().getPath()); File stateDirectory = getDataDirectory(DATA_TYPE_STATE); builder.setConfigurationFile(new File(stateDirectory, "default.conf").getPath()); builder.setPreferencesFile(new File(stateDirectory, "default.prefs").getPath()); builder.setTextTable(getStringSetting(R.string.PREF_KEY_TEXT_TABLE, R.string.DEFAULT_TEXT_TABLE)); builder.setAttributesTable(getStringSetting(R.string.PREF_KEY_ATTRIBUTES_TABLE, R.string.DEFAULT_ATTRIBUTES_TABLE)); builder.setContractionTable(getStringSetting(R.string.PREF_KEY_CONTRACTION_TABLE, R.string.DEFAULT_CONTRACTION_TABLE)); builder.setKeyTable(getStringSetting(R.string.PREF_KEY_KEY_TABLE, R.string.DEFAULT_KEY_TABLE)); if ((new File(ApplicationParameters.B2G_DEVICE_PATH)).exists()) { builder.setBrailleDevice(ApplicationParameters.B2G_DEVICE_PATH); builder.setBrailleDriver(ApplicationParameters.B2G_DRIVER_CODE); } else { String name = getStringSetting(R.string.PREF_KEY_SELECTED_DEVICE); if (name.length() > 0) { Map<String, String> properties = SettingsActivity.getProperties( name, SettingsActivity.devicePropertyKeys, ApplicationUtilities.getSharedPreferences() ); String qualifier = properties.get(SettingsActivity.PREF_KEY_DEVICE_QUALIFIER); if (qualifier.length() > 0) { String reference = properties.get(SettingsActivity.PREF_KEY_DEVICE_REFERENCE); if (reference.length() > 0) { String driver = properties.get(SettingsActivity.PREF_KEY_DEVICE_DRIVER); if (driver.length() > 0) { builder.setBrailleDevice(qualifier + ":" + reference); builder.setBrailleDriver(driver); } } } } } builder.setSpeechDriver(getStringSetting(R.string.PREF_KEY_SPEECH_SUPPORT, R.string.DEFAULT_SPEECH_SUPPORT)); { ArrayList<String> keywords = new ArrayList<String>(); keywords.add(getStringSetting(R.string.PREF_KEY_LOG_LEVEL, R.string.DEFAULT_LOG_LEVEL)); keywords.addAll(getStringSetSetting(R.string.PREF_KEY_LOG_CATEGORIES)); StringBuilder operand = new StringBuilder(); for (String keyword : keywords) { if (keyword.length() > 0) { if (operand.length() > 0) operand.append(','); operand.append(keyword); } } builder.setLogLevel(operand.toString()); } return builder.getArguments(); } @Override public void run () { { SharedPreferences prefs = ApplicationUtilities.getSharedPreferences(); File file = new File(coreContext.getPackageCodePath()); String prefKey_size = getStringResource(R.string.PREF_KEY_PACKAGE_SIZE); long oldSize = prefs.getLong(prefKey_size, -1); long newSize = file.length(); String prefKey_time = getStringResource(R.string.PREF_KEY_PACKAGE_TIME); long oldTime = prefs.getLong(prefKey_time, -1); long newTime = file.lastModified(); if ((newSize != oldSize) || (newTime != oldTime)) { Log.d(LOG_TAG, "package size: " + oldSize + " -> " + newSize); Log.d(LOG_TAG, "package time: " + oldTime + " -> " + newTime); extractAssets(); { SharedPreferences.Editor editor = prefs.edit(); editor.putLong(prefKey_size, newSize); editor.putLong(prefKey_time, newTime); editor.commit(); } } } BrailleRenderer.setBrailleRenderer(getStringSetting(R.string.PREF_KEY_NAVIGATION_MODE, R.string.DEFAULT_NAVIGATION_MODE)); UsbHelper.begin(); CoreWrapper.run(makeArguments()); UsbHelper.end(); } }
Don't assume autospeak when braille isn't being used on Android. (dm) git-svn-id: 30a5f035a20f1bc647618dbad7eea2a951b61b7c@7318 91a5dbb7-01b9-0310-9b5f-b28072856b6e
Android/Application/src/org/a11y/brltty/android/CoreThread.java
Don't assume autospeak when braille isn't being used on Android. (dm)
<ide><path>ndroid/Application/src/org/a11y/brltty/android/CoreThread.java <ide> } <ide> <ide> builder.setSpeechDriver(getStringSetting(R.string.PREF_KEY_SPEECH_SUPPORT, R.string.DEFAULT_SPEECH_SUPPORT)); <add> builder.setQuietIfNoBraille(true); <ide> <ide> { <ide> ArrayList<String> keywords = new ArrayList<String>();
Java
apache-2.0
2ea99472f08c9df32e5dd6f6d3db9a42f1748fce
0
takahirom/MaterialHome
/* * Copyright (C) 2012 The Android Open Source Project * * 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.kogitune.launcher3; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.animation.TimeInterpolator; import android.animation.ValueAnimator; import android.animation.ValueAnimator.AnimatorUpdateListener; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color;import android.graphics.Matrix; import android.graphics.PointF; import android.graphics.Rect; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.Log; import android.view.InputDevice; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.ViewParent; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityManager; import android.view.accessibility.AccessibilityNodeInfo; import android.view.animation.AnimationUtils; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import android.view.animation.LinearInterpolator; import android.widget.Scroller; import android.widget.Toast; import java.util.ArrayList; interface Page { public int getPageChildCount(); public View getChildOnPageAt(int i); public void removeAllViewsOnPage(); public void removeViewOnPageAt(int i); public int indexOfChildOnPage(View v); } /** * An abstraction of the original Workspace which supports browsing through a * sequential list of "pages" */ public abstract class PagedView extends ViewGroup implements ViewGroup.OnHierarchyChangeListener { private static final String TAG = "PagedView"; protected static final boolean DEBUG = true; protected static final int INVALID_PAGE = -1; // the min drag distance for a fling to register, to prevent random page shifts private static final int MIN_LENGTH_FOR_FLING = 25; protected static final int PAGE_SNAP_ANIMATION_DURATION = 750; protected static final int SLOW_PAGE_SNAP_ANIMATION_DURATION = 950; protected static final float NANOTIME_DIV = 1000000000.0f; private static final float OVERSCROLL_ACCELERATE_FACTOR = 2; private static final float OVERSCROLL_DAMP_FACTOR = 0.14f; private static final float RETURN_TO_ORIGINAL_PAGE_THRESHOLD = 0.33f; // The page is moved more than halfway, automatically move to the next page on touch up. private static final float SIGNIFICANT_MOVE_THRESHOLD = 0.4f; // The following constants need to be scaled based on density. The scaled versions will be // assigned to the corresponding member variables below. private static final int FLING_THRESHOLD_VELOCITY = 500; private static final int MIN_SNAP_VELOCITY = 1500; private static final int MIN_FLING_VELOCITY = 250; // We are disabling touch interaction of the widget region for factory ROM. private static final boolean DISABLE_TOUCH_INTERACTION = false; private static final boolean DISABLE_TOUCH_SIDE_PAGES = true; private static final boolean DISABLE_FLING_TO_DELETE = true; public static final int INVALID_RESTORE_PAGE = -1001; private boolean mFreeScroll = false; private int mFreeScrollMinScrollX = -1; private int mFreeScrollMaxScrollX = -1; static final int AUTOMATIC_PAGE_SPACING = -1; protected int mFlingThresholdVelocity; protected int mMinFlingVelocity; protected int mMinSnapVelocity; protected float mDensity; protected float mSmoothingTime; protected float mTouchX; protected boolean mFirstLayout = true; private int mNormalChildHeight; protected int mCurrentPage; protected int mRestorePage = INVALID_RESTORE_PAGE; protected int mChildCountOnLastLayout; protected int mNextPage = INVALID_PAGE; protected int mMaxScrollX; protected Scroller mScroller; private VelocityTracker mVelocityTracker; private float mParentDownMotionX; private float mParentDownMotionY; private float mDownMotionX; private float mDownMotionY; private float mDownScrollX; private float mDragViewBaselineLeft; protected float mLastMotionX; protected float mLastMotionXRemainder; protected float mLastMotionY; protected float mTotalMotionX; private int mLastScreenCenter = -1; private boolean mCancelTap; private int[] mPageScrolls; protected final static int TOUCH_STATE_REST = 0; protected final static int TOUCH_STATE_SCROLLING = 1; protected final static int TOUCH_STATE_PREV_PAGE = 2; protected final static int TOUCH_STATE_NEXT_PAGE = 3; protected final static int TOUCH_STATE_REORDERING = 4; protected final static float ALPHA_QUANTIZE_LEVEL = 0.0001f; protected int mTouchState = TOUCH_STATE_REST; protected boolean mForceScreenScrolled = false; protected OnLongClickListener mLongClickListener; protected int mTouchSlop; private int mPagingTouchSlop; private int mMaximumVelocity; protected int mPageSpacing; protected int mPageLayoutPaddingTop; protected int mPageLayoutPaddingBottom; protected int mPageLayoutPaddingLeft; protected int mPageLayoutPaddingRight; protected int mPageLayoutWidthGap; protected int mPageLayoutHeightGap; protected int mCellCountX = 0; protected int mCellCountY = 0; protected boolean mCenterPagesVertically; protected boolean mAllowOverScroll = true; protected int mUnboundedScrollX; protected int[] mTempVisiblePagesRange = new int[2]; protected boolean mForceDrawAllChildrenNextFrame; // mOverScrollX is equal to getScrollX() when we're within the normal scroll range. Otherwise // it is equal to the scaled overscroll position. We use a separate value so as to prevent // the screens from continuing to translate beyond the normal bounds. protected int mOverScrollX; protected static final int INVALID_POINTER = -1; protected int mActivePointerId = INVALID_POINTER; private PageSwitchListener mPageSwitchListener; protected ArrayList<Boolean> mDirtyPageContent; // If true, syncPages and syncPageItems will be called to refresh pages protected boolean mContentIsRefreshable = true; // If true, modify alpha of neighboring pages as user scrolls left/right protected boolean mFadeInAdjacentScreens = false; // It true, use a different slop parameter (pagingTouchSlop = 2 * touchSlop) for deciding // to switch to a new page protected boolean mUsePagingTouchSlop = true; // If true, the subclass should directly update scrollX itself in its computeScroll method // (SmoothPagedView does this) protected boolean mDeferScrollUpdate = false; protected boolean mDeferLoadAssociatedPagesUntilScrollCompletes = false; protected boolean mIsPageMoving = false; // All syncs and layout passes are deferred until data is ready. protected boolean mIsDataReady = false; protected boolean mAllowLongPress = true; // Page Indicator private int mPageIndicatorViewId; private PageIndicator mPageIndicator; private boolean mAllowPagedViewAnimations = true; // The viewport whether the pages are to be contained (the actual view may be larger than the // viewport) private Rect mViewport = new Rect(); // Reordering // We use the min scale to determine how much to expand the actually PagedView measured // dimensions such that when we are zoomed out, the view is not clipped private int REORDERING_DROP_REPOSITION_DURATION = 200; protected int REORDERING_REORDER_REPOSITION_DURATION = 300; protected int REORDERING_ZOOM_IN_OUT_DURATION = 250; private int REORDERING_SIDE_PAGE_HOVER_TIMEOUT = 80; private float mMinScale = 1f; private boolean mUseMinScale = false; protected View mDragView; protected AnimatorSet mZoomInOutAnim; private Runnable mSidePageHoverRunnable; private int mSidePageHoverIndex = -1; // This variable's scope is only for the duration of startReordering() and endReordering() private boolean mReorderingStarted = false; // This variable's scope is for the duration of startReordering() and after the zoomIn() // animation after endReordering() private boolean mIsReordering; // The runnable that settles the page after snapToPage and animateDragViewToOriginalPosition private int NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT = 2; private int mPostReorderingPreZoomInRemainingAnimationCount; private Runnable mPostReorderingPreZoomInRunnable; // Convenience/caching private Matrix mTmpInvMatrix = new Matrix(); private float[] mTmpPoint = new float[2]; private int[] mTmpIntPoint = new int[2]; private Rect mTmpRect = new Rect(); private Rect mAltTmpRect = new Rect(); // Fling to delete private int FLING_TO_DELETE_FADE_OUT_DURATION = 350; private float FLING_TO_DELETE_FRICTION = 0.035f; // The degrees specifies how much deviation from the up vector to still consider a fling "up" private float FLING_TO_DELETE_MAX_FLING_DEGREES = 65f; protected int mFlingToDeleteThresholdVelocity = -1400; // Drag to delete private boolean mDeferringForDelete = false; private int DELETE_SLIDE_IN_SIDE_PAGE_DURATION = 250; private int DRAG_TO_DELETE_FADE_OUT_DURATION = 350; // Drop to delete private View mDeleteDropTarget; private boolean mAutoComputePageSpacing = false; private boolean mRecomputePageSpacing = false; // Bouncer private boolean mTopAlignPageWhenShrinkingForBouncer = false; protected final Rect mInsets = new Rect(); protected int mFirstChildLeft; public interface PageSwitchListener { void onPageSwitch(View newPage, int newPageIndex); } public PagedView(Context context) { this(context, null); } public PagedView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public PagedView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PagedView, defStyle, 0); setPageSpacing(a.getDimensionPixelSize(R.styleable.PagedView_pageSpacing, 0)); if (mPageSpacing < 0) { mAutoComputePageSpacing = mRecomputePageSpacing = true; } mPageLayoutPaddingTop = a.getDimensionPixelSize( R.styleable.PagedView_pageLayoutPaddingTop, 0); mPageLayoutPaddingBottom = a.getDimensionPixelSize( R.styleable.PagedView_pageLayoutPaddingBottom, 0); mPageLayoutPaddingLeft = a.getDimensionPixelSize( R.styleable.PagedView_pageLayoutPaddingLeft, 0); mPageLayoutPaddingRight = a.getDimensionPixelSize( R.styleable.PagedView_pageLayoutPaddingRight, 0); mPageLayoutWidthGap = a.getDimensionPixelSize( R.styleable.PagedView_pageLayoutWidthGap, 0); mPageLayoutHeightGap = a.getDimensionPixelSize( R.styleable.PagedView_pageLayoutHeightGap, 0); mPageIndicatorViewId = a.getResourceId(R.styleable.PagedView_pageIndicator, -1); a.recycle(); setHapticFeedbackEnabled(false); init(); } /** * Initializes various states for this workspace. */ protected void init() { mDirtyPageContent = new ArrayList<Boolean>(); mDirtyPageContent.ensureCapacity(32); mScroller = new Scroller(getContext(), new ScrollInterpolator()); mCurrentPage = 0; mCenterPagesVertically = true; final ViewConfiguration configuration = ViewConfiguration.get(getContext()); mTouchSlop = configuration.getScaledPagingTouchSlop(); mPagingTouchSlop = configuration.getScaledPagingTouchSlop(); mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); mDensity = getResources().getDisplayMetrics().density; // Scale the fling-to-delete threshold by the density mFlingToDeleteThresholdVelocity = (int) (mFlingToDeleteThresholdVelocity * mDensity); mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * mDensity); mMinFlingVelocity = (int) (MIN_FLING_VELOCITY * mDensity); mMinSnapVelocity = (int) (MIN_SNAP_VELOCITY * mDensity); setOnHierarchyChangeListener(this); } protected void onAttachedToWindow() { super.onAttachedToWindow(); // Hook up the page indicator ViewGroup parent = (ViewGroup) getParent(); if (mPageIndicator == null && mPageIndicatorViewId > -1) { mPageIndicator = (PageIndicator) parent.findViewById(mPageIndicatorViewId); mPageIndicator.removeAllMarkers(mAllowPagedViewAnimations); ArrayList<PageIndicator.PageMarkerResources> markers = new ArrayList<PageIndicator.PageMarkerResources>(); for (int i = 0; i < getChildCount(); ++i) { markers.add(getPageIndicatorMarker(i)); } mPageIndicator.addMarkers(markers, mAllowPagedViewAnimations); OnClickListener listener = getPageIndicatorClickListener(); if (listener != null) { mPageIndicator.setOnClickListener(listener); } mPageIndicator.setContentDescription(getPageIndicatorDescription()); } } protected String getPageIndicatorDescription() { return getCurrentPageDescription(); } protected OnClickListener getPageIndicatorClickListener() { return null; } protected void onDetachedFromWindow() { // Unhook the page indicator mPageIndicator = null; } void setDeleteDropTarget(View v) { mDeleteDropTarget = v; } // Convenience methods to map points from self to parent and vice versa float[] mapPointFromViewToParent(View v, float x, float y) { mTmpPoint[0] = x; mTmpPoint[1] = y; v.getMatrix().mapPoints(mTmpPoint); mTmpPoint[0] += v.getLeft(); mTmpPoint[1] += v.getTop(); return mTmpPoint; } float[] mapPointFromParentToView(View v, float x, float y) { mTmpPoint[0] = x - v.getLeft(); mTmpPoint[1] = y - v.getTop(); v.getMatrix().invert(mTmpInvMatrix); mTmpInvMatrix.mapPoints(mTmpPoint); return mTmpPoint; } void updateDragViewTranslationDuringDrag() { if (mDragView != null) { float x = (mLastMotionX - mDownMotionX) + (getScrollX() - mDownScrollX) + (mDragViewBaselineLeft - mDragView.getLeft()); float y = mLastMotionY - mDownMotionY; mDragView.setTranslationX(x); mDragView.setTranslationY(y); if (DEBUG) Log.d(TAG, "PagedView.updateDragViewTranslationDuringDrag(): " + x + ", " + y); } } public void setMinScale(float f) { mMinScale = f; mUseMinScale = true; requestLayout(); } @Override public void setScaleX(float scaleX) { super.setScaleX(scaleX); if (isReordering(true)) { float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY); mLastMotionX = p[0]; mLastMotionY = p[1]; updateDragViewTranslationDuringDrag(); } } // Convenience methods to get the actual width/height of the PagedView (since it is measured // to be larger to account for the minimum possible scale) int getViewportWidth() { return mViewport.width(); } int getViewportHeight() { return mViewport.height(); } // Convenience methods to get the offset ASSUMING that we are centering the pages in the // PagedView both horizontally and vertically int getViewportOffsetX() { return (getMeasuredWidth() - getViewportWidth()) / 2; } int getViewportOffsetY() { return (getMeasuredHeight() - getViewportHeight()) / 2; } PageIndicator getPageIndicator() { return mPageIndicator; } protected PageIndicator.PageMarkerResources getPageIndicatorMarker(int pageIndex) { return new PageIndicator.PageMarkerResources(); } public void setPageSwitchListener(PageSwitchListener pageSwitchListener) { mPageSwitchListener = pageSwitchListener; if (mPageSwitchListener != null) { mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage); } } /** * Note: this is a reimplementation of View.isLayoutRtl() since that is currently hidden api. */ public boolean isLayoutRtl() { return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); } /** * Called by subclasses to mark that data is ready, and that we can begin loading and laying * out pages. */ protected void setDataIsReady() { mIsDataReady = true; } protected boolean isDataReady() { return mIsDataReady; } /** * Returns the index of the currently displayed page. * * @return The index of the currently displayed page. */ int getCurrentPage() { return mCurrentPage; } int getNextPage() { return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage; } int getPageCount() { return getChildCount(); } View getPageAt(int index) { return getChildAt(index); } protected int indexToPage(int index) { return index; } /** * Updates the scroll of the current page immediately to its final scroll position. We use this * in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of * the previous tab page. */ protected void updateCurrentPageScroll() { // If the current page is invalid, just reset the scroll position to zero int newX = 0; if (0 <= mCurrentPage && mCurrentPage < getPageCount()) { newX = getScrollForPage(mCurrentPage); } scrollTo(newX, 0); mScroller.setFinalX(newX); mScroller.forceFinished(true); } /** * Called during AllApps/Home transitions to avoid unnecessary work. When that other animation * ends, {@link #resumeScrolling()} should be called, along with * {@link #updateCurrentPageScroll()} to correctly set the final state and re-enable scrolling. */ void pauseScrolling() { mScroller.forceFinished(true); } /** * Enables scrolling again. * @see #pauseScrolling() */ void resumeScrolling() { } /** * Sets the current page. */ void setCurrentPage(int currentPage) { if (!mScroller.isFinished()) { mScroller.abortAnimation(); // We need to clean up the next page here to avoid computeScrollHelper from // updating current page on the pass. mNextPage = INVALID_PAGE; } // don't introduce any checks like mCurrentPage == currentPage here-- if we change the // the default if (getChildCount() == 0) { return; } mForceScreenScrolled = true; mCurrentPage = Math.max(0, Math.min(currentPage, getPageCount() - 1)); updateCurrentPageScroll(); notifyPageSwitchListener(); invalidate(); } /** * The restore page will be set in place of the current page at the next (likely first) * layout. */ void setRestorePage(int restorePage) { mRestorePage = restorePage; } protected void notifyPageSwitchListener() { if (mPageSwitchListener != null) { mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage); } // Update the page indicator (when we aren't reordering) if (mPageIndicator != null && !isReordering(false)) { mPageIndicator.setActiveMarker(getNextPage()); } } protected void pageBeginMoving() { if (!mIsPageMoving) { mIsPageMoving = true; onPageBeginMoving(); } } protected void pageEndMoving() { if (mIsPageMoving) { mIsPageMoving = false; onPageEndMoving(); } } protected boolean isPageMoving() { return mIsPageMoving; } // a method that subclasses can override to add behavior protected void onPageBeginMoving() { } // a method that subclasses can override to add behavior protected void onPageEndMoving() { } /** * Registers the specified listener on each page contained in this workspace. * * @param l The listener used to respond to long clicks. */ @Override public void setOnLongClickListener(OnLongClickListener l) { mLongClickListener = l; final int count = getPageCount(); for (int i = 0; i < count; i++) { getPageAt(i).setOnLongClickListener(l); } super.setOnLongClickListener(l); } @Override public void scrollBy(int x, int y) { scrollTo(mUnboundedScrollX + x, getScrollY() + y); } @Override public void scrollTo(int x, int y) { // In free scroll mode, we clamp the scrollX if (mFreeScroll) { x = Math.min(x, mFreeScrollMaxScrollX); x = Math.max(x, mFreeScrollMinScrollX); } final boolean isRtl = isLayoutRtl(); mUnboundedScrollX = x; boolean isXBeforeFirstPage = isRtl ? (x > mMaxScrollX) : (x < 0); boolean isXAfterLastPage = isRtl ? (x < 0) : (x > mMaxScrollX); if (isXBeforeFirstPage) { super.scrollTo(0, y); if (mAllowOverScroll) { if (isRtl) { overScroll(x - mMaxScrollX); } else { overScroll(x); } } } else if (isXAfterLastPage) { super.scrollTo(mMaxScrollX, y); if (mAllowOverScroll) { if (isRtl) { overScroll(x); } else { overScroll(x - mMaxScrollX); } } } else { mOverScrollX = x; super.scrollTo(x, y); } mTouchX = x; mSmoothingTime = System.nanoTime() / NANOTIME_DIV; // Update the last motion events when scrolling if (isReordering(true)) { float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY); mLastMotionX = p[0]; mLastMotionY = p[1]; updateDragViewTranslationDuringDrag(); } } private void sendScrollAccessibilityEvent() { AccessibilityManager am = (AccessibilityManager) getContext().getSystemService(Context.ACCESSIBILITY_SERVICE); if (am.isEnabled()) { AccessibilityEvent ev = AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED); ev.setItemCount(getChildCount()); ev.setFromIndex(mCurrentPage); final int action; if (getNextPage() >= mCurrentPage) { action = AccessibilityNodeInfo.ACTION_SCROLL_FORWARD; } else { action = AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD; } ev.setAction(action); sendAccessibilityEventUnchecked(ev); } } // we moved this functionality to a helper function so SmoothPagedView can reuse it protected boolean computeScrollHelper() { if (mScroller.computeScrollOffset()) { // Don't bother scrolling if the page does not need to be moved if (getScrollX() != mScroller.getCurrX() || getScrollY() != mScroller.getCurrY() || mOverScrollX != mScroller.getCurrX()) { float scaleX = mFreeScroll ? getScaleX() : 1f; int scrollX = (int) (mScroller.getCurrX() * (1 / scaleX)); scrollTo(scrollX, mScroller.getCurrY()); } invalidate(); return true; } else if (mNextPage != INVALID_PAGE) { sendScrollAccessibilityEvent(); mCurrentPage = Math.max(0, Math.min(mNextPage, getPageCount() - 1)); mNextPage = INVALID_PAGE; notifyPageSwitchListener(); // Load the associated pages if necessary if (mDeferLoadAssociatedPagesUntilScrollCompletes) { loadAssociatedPages(mCurrentPage); mDeferLoadAssociatedPagesUntilScrollCompletes = false; } // We don't want to trigger a page end moving unless the page has settled // and the user has stopped scrolling if (mTouchState == TOUCH_STATE_REST) { pageEndMoving(); } onPostReorderingAnimationCompleted(); AccessibilityManager am = (AccessibilityManager) getContext().getSystemService(Context.ACCESSIBILITY_SERVICE); if (am.isEnabled()) { // Notify the user when the page changes announceForAccessibility(getCurrentPageDescription()); } return true; } return false; } @Override public void computeScroll() { computeScrollHelper(); } protected boolean shouldSetTopAlignedPivotForWidget(int childIndex) { return mTopAlignPageWhenShrinkingForBouncer; } public static class LayoutParams extends ViewGroup.LayoutParams { public boolean isFullScreenPage = false; /** * {@inheritDoc} */ public LayoutParams(int width, int height) { super(width, height); } public LayoutParams(ViewGroup.LayoutParams source) { super(source); } } protected LayoutParams generateDefaultLayoutParams() { return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); } public void addFullScreenPage(View page) { LayoutParams lp = generateDefaultLayoutParams(); lp.isFullScreenPage = true; super.addView(page, 0, lp); } public int getNormalChildHeight() { return mNormalChildHeight; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (!mIsDataReady || getChildCount() == 0) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); return; } // We measure the dimensions of the PagedView to be larger than the pages so that when we // zoom out (and scale down), the view is still contained in the parent int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); // NOTE: We multiply by 1.5f to account for the fact that depending on the offset of the // viewport, we can be at most one and a half screens offset once we scale down DisplayMetrics dm = getResources().getDisplayMetrics(); int maxSize = Math.max(dm.widthPixels, dm.heightPixels + mInsets.top + mInsets.bottom); int parentWidthSize, parentHeightSize; int scaledWidthSize, scaledHeightSize; if (mUseMinScale) { parentWidthSize = (int) (1.5f * maxSize); parentHeightSize = maxSize; scaledWidthSize = (int) (parentWidthSize / mMinScale); scaledHeightSize = (int) (parentHeightSize / mMinScale); } else { scaledWidthSize = widthSize; scaledHeightSize = heightSize; } mViewport.set(0, 0, widthSize, heightSize); if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); return; } // Return early if we aren't given a proper dimension if (widthSize <= 0 || heightSize <= 0) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); return; } /* Allow the height to be set as WRAP_CONTENT. This allows the particular case * of the All apps view on XLarge displays to not take up more space then it needs. Width * is still not allowed to be set as WRAP_CONTENT since many parts of the code expect * each page to have the same width. */ final int verticalPadding = getPaddingTop() + getPaddingBottom(); final int horizontalPadding = getPaddingLeft() + getPaddingRight(); // The children are given the same width and height as the workspace // unless they were set to WRAP_CONTENT if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize); if (DEBUG) Log.d(TAG, "PagedView.scaledSize: " + scaledWidthSize + ", " + scaledHeightSize); //if (DEBUG) Log.d(TAG, "PagedView.parentSize: " + parentWidthSize + ", " + parentHeightSize); if (DEBUG) Log.d(TAG, "PagedView.horizontalPadding: " + horizontalPadding); if (DEBUG) Log.d(TAG, "PagedView.verticalPadding: " + verticalPadding); final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { // disallowing padding in paged view (just pass 0) final View child = getPageAt(i); if (child.getVisibility() != GONE) { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); int childWidthMode; int childHeightMode; int childWidth; int childHeight; if (!lp.isFullScreenPage) { if (lp.width == LayoutParams.WRAP_CONTENT) { childWidthMode = MeasureSpec.AT_MOST; } else { childWidthMode = MeasureSpec.EXACTLY; } if (lp.height == LayoutParams.WRAP_CONTENT) { childHeightMode = MeasureSpec.AT_MOST; } else { childHeightMode = MeasureSpec.EXACTLY; } childWidth = widthSize - horizontalPadding; childHeight = heightSize - verticalPadding - mInsets.top - mInsets.bottom; mNormalChildHeight = childHeight; } else { childWidthMode = MeasureSpec.EXACTLY; childHeightMode = MeasureSpec.EXACTLY; if (mUseMinScale) { childWidth = getViewportWidth(); childHeight = getViewportHeight(); } else { childWidth = widthSize - getPaddingLeft() - getPaddingRight(); childHeight = heightSize - getPaddingTop() - getPaddingBottom(); } } final int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidth, childWidthMode); final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeight, childHeightMode); child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } } setMeasuredDimension(scaledWidthSize, scaledHeightSize); if (childCount > 0) { // Calculate the variable page spacing if necessary if (mAutoComputePageSpacing && mRecomputePageSpacing) { // The gap between pages in the PagedView should be equal to the gap from the page // to the edge of the screen (so it is not visible in the current screen). To // account for unequal padding on each side of the paged view, we take the maximum // of the left/right gap and use that as the gap between each page. int offset = (getViewportWidth() - getChildWidth(0)) / 2; int spacing = Math.max(offset, widthSize - offset - getChildAt(0).getMeasuredWidth()); setPageSpacing(spacing); mRecomputePageSpacing = false; } } } public void setPageSpacing(int pageSpacing) { mPageSpacing = pageSpacing; requestLayout(); } protected int getFirstChildLeft() { return mFirstChildLeft; } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { if (!mIsDataReady || getChildCount() == 0) { return; } if (DEBUG) Log.d(TAG, "PagedView.onLayout()"); final int childCount = getChildCount(); int screenWidth = getViewportWidth(); int offsetX = getViewportOffsetX(); int offsetY = getViewportOffsetY(); // Update the viewport offsets mViewport.offset(offsetX, offsetY); final boolean isRtl = isLayoutRtl(); final int startIndex = isRtl ? childCount - 1 : 0; final int endIndex = isRtl ? -1 : childCount; final int delta = isRtl ? -1 : 1; int verticalPadding = getPaddingTop() + getPaddingBottom(); int childLeft = mFirstChildLeft = offsetX + (screenWidth - getChildWidth(startIndex)) / 2; if (mPageScrolls == null || getChildCount() != mChildCountOnLastLayout) { mPageScrolls = new int[getChildCount()]; } for (int i = startIndex; i != endIndex; i += delta) { final View child = getPageAt(i); if (child.getVisibility() != View.GONE) { LayoutParams lp = (LayoutParams) child.getLayoutParams(); int childTop; if (lp.isFullScreenPage) { childTop = offsetY; } else { childTop = offsetY + getPaddingTop() + mInsets.top; if (mCenterPagesVertically) { childTop += (getViewportHeight() - mInsets.top - mInsets.bottom - verticalPadding - child.getMeasuredHeight()) / 2; } } final int childWidth = child.getMeasuredWidth(); final int childHeight = child.getMeasuredHeight(); if (DEBUG) Log.d(TAG, "\tlayout-child" + i + ": " + childLeft + ", " + childTop); child.layout(childLeft, childTop, childLeft + child.getMeasuredWidth(), childTop + childHeight); // We assume the left and right padding are equal, and hence center the pages // horizontally int scrollOffset = (getViewportWidth() - childWidth) / 2; mPageScrolls[i] = childLeft - scrollOffset - offsetX; if (i != endIndex - delta) { childLeft += childWidth + scrollOffset; int nextScrollOffset = (getViewportWidth() - getChildWidth(i + delta)) / 2; childLeft += nextScrollOffset; } } } if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) { setHorizontalScrollBarEnabled(false); updateCurrentPageScroll(); setHorizontalScrollBarEnabled(true); mFirstLayout = false; } if (childCount > 0) { final int index = isLayoutRtl() ? 0 : childCount - 1; mMaxScrollX = getScrollForPage(index); } else { mMaxScrollX = 0; } if (mScroller.isFinished() && mChildCountOnLastLayout != getChildCount() && !mDeferringForDelete) { if (mRestorePage != INVALID_RESTORE_PAGE) { setCurrentPage(mRestorePage); mRestorePage = INVALID_RESTORE_PAGE; } else { setCurrentPage(getNextPage()); } } mChildCountOnLastLayout = getChildCount(); if (isReordering(true)) { updateDragViewTranslationDuringDrag(); } } protected void screenScrolled(int screenCenter) { boolean isInOverscroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX; if (mFadeInAdjacentScreens && !isInOverscroll) { for (int i = 0; i < getChildCount(); i++) { View child = getChildAt(i); if (child != null) { float scrollProgress = getScrollProgress(screenCenter, child, i); float alpha = 1 - Math.abs(scrollProgress); child.setAlpha(alpha); } } invalidate(); } } protected void enablePagedViewAnimations() { mAllowPagedViewAnimations = true; } protected void disablePagedViewAnimations() { mAllowPagedViewAnimations = false; } @Override public void onChildViewAdded(View parent, View child) { // Update the page indicator, we don't update the page indicator as we // add/remove pages if (mPageIndicator != null && !isReordering(false)) { int pageIndex = indexOfChild(child); mPageIndicator.addMarker(pageIndex, getPageIndicatorMarker(pageIndex), mAllowPagedViewAnimations); } // This ensures that when children are added, they get the correct transforms / alphas // in accordance with any scroll effects. mForceScreenScrolled = true; mRecomputePageSpacing = true; updateFreescrollBounds(); invalidate(); } @Override public void onChildViewRemoved(View parent, View child) { mForceScreenScrolled = true; updateFreescrollBounds(); invalidate(); } private void removeMarkerForView(int index) { // Update the page indicator, we don't update the page indicator as we // add/remove pages if (mPageIndicator != null && !isReordering(false)) { mPageIndicator.removeMarker(index, mAllowPagedViewAnimations); } } @Override public void removeView(View v) { // XXX: We should find a better way to hook into this before the view // gets removed form its parent... removeMarkerForView(indexOfChild(v)); super.removeView(v); } @Override public void removeViewInLayout(View v) { // XXX: We should find a better way to hook into this before the view // gets removed form its parent... removeMarkerForView(indexOfChild(v)); super.removeViewInLayout(v); } @Override public void removeViewAt(int index) { // XXX: We should find a better way to hook into this before the view // gets removed form its parent... removeViewAt(index); super.removeViewAt(index); } @Override public void removeAllViewsInLayout() { // Update the page indicator, we don't update the page indicator as we // add/remove pages if (mPageIndicator != null) { mPageIndicator.removeAllMarkers(mAllowPagedViewAnimations); } super.removeAllViewsInLayout(); } protected int getChildOffset(int index) { if (index < 0 || index > getChildCount() - 1) return 0; int offset = getPageAt(index).getLeft() - getViewportOffsetX(); return offset; } protected void getOverviewModePages(int[] range) { range[0] = 0; range[1] = Math.max(0, getChildCount() - 1); } protected void getVisiblePages(int[] range) { final int pageCount = getChildCount(); mTmpIntPoint[0] = mTmpIntPoint[1] = 0; range[0] = -1; range[1] = -1; if (pageCount > 0) { int viewportWidth = getViewportWidth(); int curScreen = 0; int count = getChildCount(); for (int i = 0; i < count; i++) { View currPage = getPageAt(i); mTmpIntPoint[0] = 0; Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false); if (mTmpIntPoint[0] > viewportWidth) { if (range[0] == -1) { continue; } else { break; } } mTmpIntPoint[0] = currPage.getMeasuredWidth(); Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false); if (mTmpIntPoint[0] < 0) { if (range[0] == -1) { continue; } else { break; } } curScreen = i; if (range[0] < 0) { range[0] = curScreen; } } range[1] = curScreen; } else { range[0] = -1; range[1] = -1; } } protected boolean shouldDrawChild(View child) { return child.getAlpha() > 0 && child.getVisibility() == VISIBLE; } @Override protected void dispatchDraw(Canvas canvas) { int halfScreenSize = getViewportWidth() / 2; // mOverScrollX is equal to getScrollX() when we're within the normal scroll range. // Otherwise it is equal to the scaled overscroll position. int screenCenter = mOverScrollX + halfScreenSize; if (screenCenter != mLastScreenCenter || mForceScreenScrolled) { // set mForceScreenScrolled before calling screenScrolled so that screenScrolled can // set it for the next frame mForceScreenScrolled = false; screenScrolled(screenCenter); mLastScreenCenter = screenCenter; } // Find out which screens are visible; as an optimization we only call draw on them final int pageCount = getChildCount(); if (pageCount > 0) { getVisiblePages(mTempVisiblePagesRange); final int leftScreen = mTempVisiblePagesRange[0]; final int rightScreen = mTempVisiblePagesRange[1]; if (leftScreen != -1 && rightScreen != -1) { final long drawingTime = getDrawingTime(); // Clip to the bounds canvas.save(); canvas.clipRect(getScrollX(), getScrollY(), getScrollX() + getRight() - getLeft(), getScrollY() + getBottom() - getTop()); // Draw all the children, leaving the drag view for last for (int i = pageCount - 1; i >= 0; i--) { final View v = getPageAt(i); if (v == mDragView) continue; if (mForceDrawAllChildrenNextFrame || (leftScreen <= i && i <= rightScreen && shouldDrawChild(v))) { //v.setBackgroundColor(Color.argb(55,255,0,0)); drawChild(canvas, v, drawingTime); } } // Draw the drag view on top (if there is one) if (mDragView != null) { drawChild(canvas, mDragView, drawingTime); } mForceDrawAllChildrenNextFrame = false; canvas.restore(); } } } @Override public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) { int page = indexToPage(indexOfChild(child)); if (page != mCurrentPage || !mScroller.isFinished()) { snapToPage(page); return true; } return false; } @Override protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) { int focusablePage; if (mNextPage != INVALID_PAGE) { focusablePage = mNextPage; } else { focusablePage = mCurrentPage; } View v = getPageAt(focusablePage); if (v != null) { return v.requestFocus(direction, previouslyFocusedRect); } return false; } @Override public boolean dispatchUnhandledMove(View focused, int direction) { // XXX-RTL: This will be fixed in a future CL if (direction == View.FOCUS_LEFT) { if (getCurrentPage() > 0) { snapToPage(getCurrentPage() - 1); return true; } } else if (direction == View.FOCUS_RIGHT) { if (getCurrentPage() < getPageCount() - 1) { snapToPage(getCurrentPage() + 1); return true; } } return super.dispatchUnhandledMove(focused, direction); } @Override public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { // XXX-RTL: This will be fixed in a future CL if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) { getPageAt(mCurrentPage).addFocusables(views, direction, focusableMode); } if (direction == View.FOCUS_LEFT) { if (mCurrentPage > 0) { getPageAt(mCurrentPage - 1).addFocusables(views, direction, focusableMode); } } else if (direction == View.FOCUS_RIGHT){ if (mCurrentPage < getPageCount() - 1) { getPageAt(mCurrentPage + 1).addFocusables(views, direction, focusableMode); } } } /** * If one of our descendant views decides that it could be focused now, only * pass that along if it's on the current page. * * This happens when live folders requery, and if they're off page, they * end up calling requestFocus, which pulls it on page. */ @Override public void focusableViewAvailable(View focused) { View current = getPageAt(mCurrentPage); View v = focused; while (true) { if (v == current) { super.focusableViewAvailable(focused); return; } if (v == this) { return; } ViewParent parent = v.getParent(); if (parent instanceof View) { v = (View)v.getParent(); } else { return; } } } /** * {@inheritDoc} */ @Override public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { if (disallowIntercept) { // We need to make sure to cancel our long press if // a scrollable widget takes over touch events final View currentPage = getPageAt(mCurrentPage); currentPage.cancelLongPress(); } super.requestDisallowInterceptTouchEvent(disallowIntercept); } /** * Return true if a tap at (x, y) should trigger a flip to the previous page. */ protected boolean hitsPreviousPage(float x, float y) { int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2; if (isLayoutRtl()) { return (x > (getViewportOffsetX() + getViewportWidth() - offset + mPageSpacing)); } return (x < getViewportOffsetX() + offset - mPageSpacing); } /** * Return true if a tap at (x, y) should trigger a flip to the next page. */ protected boolean hitsNextPage(float x, float y) { int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2; if (isLayoutRtl()) { return (x < getViewportOffsetX() + offset - mPageSpacing); } return (x > (getViewportOffsetX() + getViewportWidth() - offset + mPageSpacing)); } /** Returns whether x and y originated within the buffered viewport */ private boolean isTouchPointInViewportWithBuffer(int x, int y) { mTmpRect.set(mViewport.left - mViewport.width() / 2, mViewport.top, mViewport.right + mViewport.width() / 2, mViewport.bottom); return mTmpRect.contains(x, y); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { if (DISABLE_TOUCH_INTERACTION) { return false; } /* * This method JUST determines whether we want to intercept the motion. * If we return true, onTouchEvent will be called and we do the actual * scrolling there. */ acquireVelocityTrackerAndAddMovement(ev); // Skip touch handling if there are no pages to swipe if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev); /* * Shortcut the most recurring case: the user is in the dragging * state and he is moving his finger. We want to intercept this * motion. */ final int action = ev.getAction(); if ((action == MotionEvent.ACTION_MOVE) && (mTouchState == TOUCH_STATE_SCROLLING)) { return true; } switch (action & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_MOVE: { /* * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check * whether the user has moved far enough from his original down touch. */ if (mActivePointerId != INVALID_POINTER) { determineScrollingStart(ev); } // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN // event. in that case, treat the first occurence of a move event as a ACTION_DOWN // i.e. fall through to the next case (don't break) // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events // while it's small- this was causing a crash before we checked for INVALID_POINTER) break; } case MotionEvent.ACTION_DOWN: { final float x = ev.getX(); final float y = ev.getY(); // Remember location of down touch mDownMotionX = x; mDownMotionY = y; mDownScrollX = getScrollX(); mLastMotionX = x; mLastMotionY = y; float[] p = mapPointFromViewToParent(this, x, y); mParentDownMotionX = p[0]; mParentDownMotionY = p[1]; mLastMotionXRemainder = 0; mTotalMotionX = 0; mActivePointerId = ev.getPointerId(0); /* * If being flinged and user touches the screen, initiate drag; * otherwise don't. mScroller.isFinished should be false when * being flinged. */ final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX()); final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop); if (finishedScrolling) { mTouchState = TOUCH_STATE_REST; mScroller.abortAnimation(); } else { if (isTouchPointInViewportWithBuffer((int) mDownMotionX, (int) mDownMotionY)) { mTouchState = TOUCH_STATE_SCROLLING; } else { mTouchState = TOUCH_STATE_REST; } } // check if this can be the beginning of a tap on the side of the pages // to scroll the current page if (!DISABLE_TOUCH_SIDE_PAGES) { if (mTouchState != TOUCH_STATE_PREV_PAGE && mTouchState != TOUCH_STATE_NEXT_PAGE) { if (getChildCount() > 0) { if (hitsPreviousPage(x, y)) { mTouchState = TOUCH_STATE_PREV_PAGE; } else if (hitsNextPage(x, y)) { mTouchState = TOUCH_STATE_NEXT_PAGE; } } } } break; } case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: resetTouchState(); break; case MotionEvent.ACTION_POINTER_UP: onSecondaryPointerUp(ev); releaseVelocityTracker(); break; } /* * The only time we want to intercept motion events is if we are in the * drag mode. */ return mTouchState != TOUCH_STATE_REST; } protected void determineScrollingStart(MotionEvent ev) { determineScrollingStart(ev, 1.0f); } /* * Determines if we should change the touch state to start scrolling after the * user moves their touch point too far. */ protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) { // Disallow scrolling if we don't have a valid pointer index final int pointerIndex = ev.findPointerIndex(mActivePointerId); if (pointerIndex == -1) return; // Disallow scrolling if we started the gesture from outside the viewport final float x = ev.getX(pointerIndex); final float y = ev.getY(pointerIndex); if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) return; final int xDiff = (int) Math.abs(x - mLastMotionX); final int yDiff = (int) Math.abs(y - mLastMotionY); final int touchSlop = Math.round(touchSlopScale * mTouchSlop); boolean xPaged = xDiff > mPagingTouchSlop; boolean xMoved = xDiff > touchSlop; boolean yMoved = yDiff > touchSlop; if (xMoved || xPaged || yMoved) { if (mUsePagingTouchSlop ? xPaged : xMoved) { // Scroll if the user moved far enough along the X axis mTouchState = TOUCH_STATE_SCROLLING; mTotalMotionX += Math.abs(mLastMotionX - x); mLastMotionX = x; mLastMotionXRemainder = 0; mTouchX = getViewportOffsetX() + getScrollX(); mSmoothingTime = System.nanoTime() / NANOTIME_DIV; pageBeginMoving(); } } } protected float getMaxScrollProgress() { return 1.0f; } protected void cancelCurrentPageLongPress() { if (mAllowLongPress) { //mAllowLongPress = false; // Try canceling the long press. It could also have been scheduled // by a distant descendant, so use the mAllowLongPress flag to block // everything final View currentPage = getPageAt(mCurrentPage); if (currentPage != null) { currentPage.cancelLongPress(); } } } protected float getBoundedScrollProgress(int screenCenter, View v, int page) { final int halfScreenSize = getViewportWidth() / 2; screenCenter = Math.min(getScrollX() + halfScreenSize, screenCenter); screenCenter = Math.max(halfScreenSize, screenCenter); return getScrollProgress(screenCenter, v, page); } protected float getScrollProgress(int screenCenter, View v, int page) { final int halfScreenSize = getViewportWidth() / 2; int totalDistance = v.getMeasuredWidth() + mPageSpacing; int delta = screenCenter - (getScrollForPage(page) + halfScreenSize); float scrollProgress = delta / (totalDistance * 1.0f); scrollProgress = Math.min(scrollProgress, getMaxScrollProgress()); scrollProgress = Math.max(scrollProgress, - getMaxScrollProgress()); return scrollProgress; } public int getScrollForPage(int index) { if (mPageScrolls == null || index >= mPageScrolls.length || index < 0) { return 0; } else { return mPageScrolls[index]; } } // While layout transitions are occurring, a child's position may stray from its baseline // position. This method returns the magnitude of this stray at any given time. public int getLayoutTransitionOffsetForPage(int index) { if (mPageScrolls == null || index >= mPageScrolls.length || index < 0) { return 0; } else { View child = getChildAt(index); int scrollOffset = (getViewportWidth() - child.getMeasuredWidth()) / 2; int baselineX = mPageScrolls[index] + scrollOffset + getViewportOffsetX(); return (int) (child.getX() - baselineX); } } // This curve determines how the effect of scrolling over the limits of the page dimishes // as the user pulls further and further from the bounds private float overScrollInfluenceCurve(float f) { f -= 1.0f; return f * f * f + 1.0f; } protected void acceleratedOverScroll(float amount) { int screenSize = getViewportWidth(); // We want to reach the max over scroll effect when the user has // over scrolled half the size of the screen float f = OVERSCROLL_ACCELERATE_FACTOR * (amount / screenSize); if (f == 0) return; // Clamp this factor, f, to -1 < f < 1 if (Math.abs(f) >= 1) { f /= Math.abs(f); } int overScrollAmount = (int) Math.round(f * screenSize); if (amount < 0) { mOverScrollX = overScrollAmount; super.scrollTo(0, getScrollY()); } else { mOverScrollX = mMaxScrollX + overScrollAmount; super.scrollTo(mMaxScrollX, getScrollY()); } invalidate(); } protected void dampedOverScroll(float amount) { int screenSize = getViewportWidth(); float f = (amount / screenSize); if (f == 0) return; f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f))); // Clamp this factor, f, to -1 < f < 1 if (Math.abs(f) >= 1) { f /= Math.abs(f); } int overScrollAmount = (int) Math.round(OVERSCROLL_DAMP_FACTOR * f * screenSize); if (amount < 0) { mOverScrollX = overScrollAmount; super.scrollTo(0, getScrollY()); } else { mOverScrollX = mMaxScrollX + overScrollAmount; super.scrollTo(mMaxScrollX, getScrollY()); } invalidate(); } protected void overScroll(float amount) { dampedOverScroll(amount); } protected float maxOverScroll() { // Using the formula in overScroll, assuming that f = 1.0 (which it should generally not // exceed). Used to find out how much extra wallpaper we need for the over scroll effect float f = 1.0f; f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f))); return OVERSCROLL_DAMP_FACTOR * f; } protected void enableFreeScroll() { setEnableFreeScroll(true, -1); } protected void disableFreeScroll(int snapPage) { setEnableFreeScroll(false, snapPage); } void updateFreescrollBounds() { getOverviewModePages(mTempVisiblePagesRange); if (isLayoutRtl()) { mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[1]); mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[0]); } else { mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[0]); mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[1]); } } private void setEnableFreeScroll(boolean freeScroll, int snapPage) { mFreeScroll = freeScroll; if (snapPage == -1) { snapPage = getPageNearestToCenterOfScreen(); } if (!mFreeScroll) { snapToPage(snapPage); } else { updateFreescrollBounds(); getOverviewModePages(mTempVisiblePagesRange); if (getCurrentPage() < mTempVisiblePagesRange[0]) { setCurrentPage(mTempVisiblePagesRange[0]); } else if (getCurrentPage() > mTempVisiblePagesRange[1]) { setCurrentPage(mTempVisiblePagesRange[1]); } } setEnableOverscroll(!freeScroll); } private void setEnableOverscroll(boolean enable) { mAllowOverScroll = enable; } int getNearestHoverOverPageIndex() { if (mDragView != null) { int dragX = (int) (mDragView.getLeft() + (mDragView.getMeasuredWidth() / 2) + mDragView.getTranslationX()); getOverviewModePages(mTempVisiblePagesRange); int minDistance = Integer.MAX_VALUE; int minIndex = indexOfChild(mDragView); for (int i = mTempVisiblePagesRange[0]; i <= mTempVisiblePagesRange[1]; i++) { View page = getPageAt(i); int pageX = (int) (page.getLeft() + page.getMeasuredWidth() / 2); int d = Math.abs(dragX - pageX); if (d < minDistance) { minIndex = i; minDistance = d; } } return minIndex; } return -1; } @Override public boolean onTouchEvent(MotionEvent ev) { if (DISABLE_TOUCH_INTERACTION) { return false; } super.onTouchEvent(ev); // Skip touch handling if there are no pages to swipe if (getChildCount() <= 0) return super.onTouchEvent(ev); acquireVelocityTrackerAndAddMovement(ev); final int action = ev.getAction(); switch (action & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: /* * If being flinged and user touches, stop the fling. isFinished * will be false if being flinged. */ if (!mScroller.isFinished()) { mScroller.abortAnimation(); } // Remember where the motion event started mDownMotionX = mLastMotionX = ev.getX(); mDownMotionY = mLastMotionY = ev.getY(); mDownScrollX = getScrollX(); float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY); mParentDownMotionX = p[0]; mParentDownMotionY = p[1]; mLastMotionXRemainder = 0; mTotalMotionX = 0; mActivePointerId = ev.getPointerId(0); if (mTouchState == TOUCH_STATE_SCROLLING) { pageBeginMoving(); } break; case MotionEvent.ACTION_MOVE: if (mTouchState == TOUCH_STATE_SCROLLING) { // Scroll to follow the motion event final int pointerIndex = ev.findPointerIndex(mActivePointerId); if (pointerIndex == -1) return true; final float x = ev.getX(pointerIndex); final float deltaX = mLastMotionX + mLastMotionXRemainder - x; mTotalMotionX += Math.abs(deltaX); // Only scroll and update mLastMotionX if we have moved some discrete amount. We // keep the remainder because we are actually testing if we've moved from the last // scrolled position (which is discrete). if (Math.abs(deltaX) >= 1.0f) { mTouchX += deltaX; mSmoothingTime = System.nanoTime() / NANOTIME_DIV; if (!mDeferScrollUpdate) { scrollBy((int) deltaX * 2, 0); if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX); } else { invalidate(); } mLastMotionX = x; mLastMotionXRemainder = deltaX - (int) deltaX; } else { awakenScrollBars(); } } else if (mTouchState == TOUCH_STATE_REORDERING) { // Update the last motion position mLastMotionX = ev.getX(); mLastMotionY = ev.getY(); // Update the parent down so that our zoom animations take this new movement into // account float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY); mParentDownMotionX = pt[0]; mParentDownMotionY = pt[1]; updateDragViewTranslationDuringDrag(); // Find the closest page to the touch point final int dragViewIndex = indexOfChild(mDragView); // Change the drag view if we are hovering over the drop target boolean isHoveringOverDelete = isHoveringOverDeleteDropTarget( (int) mParentDownMotionX, (int) mParentDownMotionY); setPageHoveringOverDeleteDropTarget(dragViewIndex, isHoveringOverDelete); if (DEBUG) Log.d(TAG, "mLastMotionX: " + mLastMotionX); if (DEBUG) Log.d(TAG, "mLastMotionY: " + mLastMotionY); if (DEBUG) Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX); if (DEBUG) Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY); final int pageUnderPointIndex = getNearestHoverOverPageIndex(); if (pageUnderPointIndex > -1 && pageUnderPointIndex != indexOfChild(mDragView) && !isHoveringOverDelete) { mTempVisiblePagesRange[0] = 0; mTempVisiblePagesRange[1] = getPageCount() - 1; getOverviewModePages(mTempVisiblePagesRange); if (mTempVisiblePagesRange[0] <= pageUnderPointIndex && pageUnderPointIndex <= mTempVisiblePagesRange[1] && pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) { mSidePageHoverIndex = pageUnderPointIndex; mSidePageHoverRunnable = new Runnable() { @Override public void run() { // Setup the scroll to the correct page before we swap the views snapToPage(pageUnderPointIndex); // For each of the pages between the paged view and the drag view, // animate them from the previous position to the new position in // the layout (as a result of the drag view moving in the layout) int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1; int lowerIndex = (dragViewIndex < pageUnderPointIndex) ? dragViewIndex + 1 : pageUnderPointIndex; int upperIndex = (dragViewIndex > pageUnderPointIndex) ? dragViewIndex - 1 : pageUnderPointIndex; for (int i = lowerIndex; i <= upperIndex; ++i) { View v = getChildAt(i); // dragViewIndex < pageUnderPointIndex, so after we remove the // drag view all subsequent views to pageUnderPointIndex will // shift down. int oldX = getViewportOffsetX() + getChildOffset(i); int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta); // Animate the view translation from its old position to its new // position AnimatorSet anim = (AnimatorSet) v.getTag(ANIM_TAG_KEY); if (anim != null) { anim.cancel(); } v.setTranslationX(oldX - newX); anim = new AnimatorSet(); anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION); anim.playTogether( ObjectAnimator.ofFloat(v, "translationX", 0f)); anim.start(); v.setTag(anim); } removeView(mDragView); onRemoveView(mDragView, false); addView(mDragView, pageUnderPointIndex); onAddView(mDragView, pageUnderPointIndex); mSidePageHoverIndex = -1; mPageIndicator.setActiveMarker(getNextPage()); } }; postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT); } } else { removeCallbacks(mSidePageHoverRunnable); mSidePageHoverIndex = -1; } } else { determineScrollingStart(ev); } break; case MotionEvent.ACTION_UP: if (mTouchState == TOUCH_STATE_SCROLLING) { final int activePointerId = mActivePointerId; final int pointerIndex = ev.findPointerIndex(activePointerId); final float x = ev.getX(pointerIndex); final VelocityTracker velocityTracker = mVelocityTracker; velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); int velocityX = (int) velocityTracker.getXVelocity(activePointerId); final int deltaX = (int) (x - mDownMotionX); final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth(); boolean isSignificantMove = Math.abs(deltaX) > pageWidth * SIGNIFICANT_MOVE_THRESHOLD; mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x); boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING && Math.abs(velocityX) > mFlingThresholdVelocity; if (!mFreeScroll) { // In the case that the page is moved far to one direction and then is flung // in the opposite direction, we use a threshold to determine whether we should // just return to the starting page, or if we should skip one further. boolean returnToOriginalPage = false; if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD && Math.signum(velocityX) != Math.signum(deltaX) && isFling) { returnToOriginalPage = true; } int finalPage; // We give flings precedence over large moves, which is why we short-circuit our // test for a large move if a fling has been registered. That is, a large // move to the left and fling to the right will register as a fling to the right. final boolean isRtl = isLayoutRtl(); boolean isDeltaXLeft = isRtl ? deltaX > 0 : deltaX < 0; boolean isVelocityXLeft = isRtl ? velocityX > 0 : velocityX < 0; if (((isSignificantMove && !isDeltaXLeft && !isFling) || (isFling && !isVelocityXLeft)) && mCurrentPage > 0) { finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1; snapToPageWithVelocity(finalPage, velocityX); } else if (((isSignificantMove && isDeltaXLeft && !isFling) || (isFling && isVelocityXLeft)) && mCurrentPage < getChildCount() - 1) { finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1; snapToPageWithVelocity(finalPage, velocityX); } else { snapToDestination(); } } else if (mTouchState == TOUCH_STATE_PREV_PAGE) { // at this point we have not moved beyond the touch slop // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so // we can just page int nextPage = Math.max(0, mCurrentPage - 1); if (nextPage != mCurrentPage) { snapToPage(nextPage); } else { snapToDestination(); } } else { if (!mScroller.isFinished()) { mScroller.abortAnimation(); } float scaleX = getScaleX(); int vX = (int) (-velocityX * scaleX); int initialScrollX = (int) (getScrollX() * scaleX); mScroller.fling(initialScrollX, getScrollY(), vX, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0); invalidate(); } } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) { // at this point we have not moved beyond the touch slop // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so // we can just page int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1); if (nextPage != mCurrentPage) { snapToPage(nextPage); } else { snapToDestination(); } } else if (mTouchState == TOUCH_STATE_REORDERING) { // Update the last motion position mLastMotionX = ev.getX(); mLastMotionY = ev.getY(); // Update the parent down so that our zoom animations take this new movement into // account float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY); mParentDownMotionX = pt[0]; mParentDownMotionY = pt[1]; updateDragViewTranslationDuringDrag(); boolean handledFling = false; if (!DISABLE_FLING_TO_DELETE) { // Check the velocity and see if we are flinging-to-delete PointF flingToDeleteVector = isFlingingToDelete(); if (flingToDeleteVector != null) { onFlingToDelete(flingToDeleteVector); handledFling = true; } } if (!handledFling && isHoveringOverDeleteDropTarget((int) mParentDownMotionX, (int) mParentDownMotionY)) { onDropToDelete(); } } else { if (!mCancelTap) { onUnhandledTap(ev); } } // Remove the callback to wait for the side page hover timeout removeCallbacks(mSidePageHoverRunnable); // End any intermediate reordering states resetTouchState(); break; case MotionEvent.ACTION_CANCEL: if (mTouchState == TOUCH_STATE_SCROLLING) { snapToDestination(); } resetTouchState(); break; case MotionEvent.ACTION_POINTER_UP: onSecondaryPointerUp(ev); releaseVelocityTracker(); break; } return true; } public void onFlingToDelete(View v) {} public void onRemoveView(View v, boolean deletePermanently) {} public void onRemoveViewAnimationCompleted() {} public void onAddView(View v, int index) {} private void resetTouchState() { releaseVelocityTracker(); endReordering(); mCancelTap = false; mTouchState = TOUCH_STATE_REST; mActivePointerId = INVALID_POINTER; } protected void onUnhandledTap(MotionEvent ev) { ((Launcher) getContext()).onClick(this); } @Override public boolean onGenericMotionEvent(MotionEvent event) { if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { switch (event.getAction()) { case MotionEvent.ACTION_SCROLL: { // Handle mouse (or ext. device) by shifting the page depending on the scroll final float vscroll; final float hscroll; if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) { vscroll = 0; hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL); } else { vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL); hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL); } if (hscroll != 0 || vscroll != 0) { boolean isForwardScroll = isLayoutRtl() ? (hscroll < 0 || vscroll < 0) : (hscroll > 0 || vscroll > 0); if (isForwardScroll) { scrollRight(); } else { scrollLeft(); } return true; } } } } return super.onGenericMotionEvent(event); } private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) { if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(ev); } private void releaseVelocityTracker() { if (mVelocityTracker != null) { mVelocityTracker.clear(); mVelocityTracker.recycle(); mVelocityTracker = null; } } private void onSecondaryPointerUp(MotionEvent ev) { final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; final int pointerId = ev.getPointerId(pointerIndex); if (pointerId == mActivePointerId) { // This was our active pointer going up. Choose a new // active pointer and adjust accordingly. // TODO: Make this decision more intelligent. final int newPointerIndex = pointerIndex == 0 ? 1 : 0; mLastMotionX = mDownMotionX = ev.getX(newPointerIndex); mLastMotionY = ev.getY(newPointerIndex); mLastMotionXRemainder = 0; mActivePointerId = ev.getPointerId(newPointerIndex); if (mVelocityTracker != null) { mVelocityTracker.clear(); } } } @Override public void requestChildFocus(View child, View focused) { super.requestChildFocus(child, focused); int page = indexToPage(indexOfChild(child)); if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) { snapToPage(page); } } protected int getChildWidth(int index) { return getPageAt(index).getMeasuredWidth(); } int getPageNearestToPoint(float x) { int index = 0; for (int i = 0; i < getChildCount(); ++i) { if (x < getChildAt(i).getRight() - getScrollX()) { return index; } else { index++; } } return Math.min(index, getChildCount() - 1); } int getPageNearestToCenterOfScreen() { int minDistanceFromScreenCenter = Integer.MAX_VALUE; int minDistanceFromScreenCenterIndex = -1; int screenCenter = getViewportOffsetX() + getScrollX() + (getViewportWidth() / 2); final int childCount = getChildCount(); for (int i = 0; i < childCount; ++i) { View layout = (View) getPageAt(i); int childWidth = layout.getMeasuredWidth(); int halfChildWidth = (childWidth / 2); int childCenter = getViewportOffsetX() + getChildOffset(i) + halfChildWidth; int distanceFromScreenCenter = Math.abs(childCenter - screenCenter); if (distanceFromScreenCenter < minDistanceFromScreenCenter) { minDistanceFromScreenCenter = distanceFromScreenCenter; minDistanceFromScreenCenterIndex = i; } } return minDistanceFromScreenCenterIndex; } protected void snapToDestination() { snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION); } private static class ScrollInterpolator implements Interpolator { public ScrollInterpolator() { } public float getInterpolation(float t) { t -= 1.0f; return t*t*t*t*t + 1; } } // We want the duration of the page snap animation to be influenced by the distance that // the screen has to travel, however, we don't want this duration to be effected in a // purely linear fashion. Instead, we use this method to moderate the effect that the distance // of travel has on the overall snap duration. float distanceInfluenceForSnapDuration(float f) { f -= 0.5f; // center the values about 0. f *= 0.3f * Math.PI / 2.0f; return (float) Math.sin(f); } protected void snapToPageWithVelocity(int whichPage, int velocity) { whichPage = Math.max(0, Math.min(whichPage, getChildCount() - 1)); int halfScreenSize = getViewportWidth() / 2; final int newX = getScrollForPage(whichPage); int delta = newX - mUnboundedScrollX; int duration = 0; if (Math.abs(velocity) < mMinFlingVelocity) { // If the velocity is low enough, then treat this more as an automatic page advance // as opposed to an apparent physical response to flinging snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION); return; } // Here we compute a "distance" that will be used in the computation of the overall // snap duration. This is a function of the actual distance that needs to be traveled; // we keep this value close to half screen size in order to reduce the variance in snap // duration as a function of the distance the page needs to travel. float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize)); float distance = halfScreenSize + halfScreenSize * distanceInfluenceForSnapDuration(distanceRatio); velocity = Math.abs(velocity); velocity = Math.max(mMinSnapVelocity, velocity); // we want the page's snap velocity to approximately match the velocity at which the // user flings, so we scale the duration by a value near to the derivative of the scroll // interpolator at zero, ie. 5. We use 4 to make it a little slower. duration = 4 * Math.round(1000 * Math.abs(distance / velocity)); snapToPage(whichPage, delta, duration); } protected void snapToPage(int whichPage) { snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION); } protected void snapToPageImmediately(int whichPage) { snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION, true); } protected void snapToPage(int whichPage, int duration) { snapToPage(whichPage, duration, false); } protected void snapToPage(int whichPage, int duration, boolean immediate) { whichPage = Math.max(0, Math.min(whichPage, getPageCount() - 1)); int newX = getScrollForPage(whichPage); final int sX = mUnboundedScrollX; final int delta = newX - sX; snapToPage(whichPage, delta, duration, immediate); } protected void snapToPage(int whichPage, int delta, int duration) { snapToPage(whichPage, delta, duration, false); } protected void snapToPage(int whichPage, int delta, int duration, boolean immediate) { mNextPage = whichPage; View focusedChild = getFocusedChild(); if (focusedChild != null && whichPage != mCurrentPage && focusedChild == getPageAt(mCurrentPage)) { focusedChild.clearFocus(); } sendScrollAccessibilityEvent(); pageBeginMoving(); awakenScrollBars(duration); if (immediate) { duration = 0; } else if (duration == 0) { duration = Math.abs(delta); } if (!mScroller.isFinished()) { mScroller.abortAnimation(); } mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration); notifyPageSwitchListener(); // Trigger a compute() to finish switching pages if necessary if (immediate) { computeScroll(); } // Defer loading associated pages until the scroll settles mDeferLoadAssociatedPagesUntilScrollCompletes = true; mForceScreenScrolled = true; invalidate(); } public void scrollLeft() { if (getNextPage() > 0) snapToPage(getNextPage() - 1); } public void scrollRight() { if (getNextPage() < getChildCount() -1) snapToPage(getNextPage() + 1); } public int getPageForView(View v) { int result = -1; if (v != null) { ViewParent vp = v.getParent(); int count = getChildCount(); for (int i = 0; i < count; i++) { if (vp == getPageAt(i)) { return i; } } } return result; } /** * @return True is long presses are still allowed for the current touch */ public boolean allowLongPress() { return mAllowLongPress; } @Override public boolean performLongClick() { mCancelTap = true; return super.performLongClick(); } /** * Set true to allow long-press events to be triggered, usually checked by * {@link Launcher} to accept or block dpad-initiated long-presses. */ public void setAllowLongPress(boolean allowLongPress) { mAllowLongPress = allowLongPress; } public static class SavedState extends BaseSavedState { int currentPage = -1; SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); currentPage = in.readInt(); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(currentPage); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } protected void loadAssociatedPages(int page) { loadAssociatedPages(page, false); } protected void loadAssociatedPages(int page, boolean immediateAndOnly) { if (mContentIsRefreshable) { final int count = getChildCount(); if (page < count) { int lowerPageBound = getAssociatedLowerPageBound(page); int upperPageBound = getAssociatedUpperPageBound(page); if (DEBUG) Log.d(TAG, "loadAssociatedPages: " + lowerPageBound + "/" + upperPageBound); // First, clear any pages that should no longer be loaded for (int i = 0; i < count; ++i) { Page layout = (Page) getPageAt(i); if ((i < lowerPageBound) || (i > upperPageBound)) { if (layout.getPageChildCount() > 0) { layout.removeAllViewsOnPage(); } mDirtyPageContent.set(i, true); } } // Next, load any new pages for (int i = 0; i < count; ++i) { if ((i != page) && immediateAndOnly) { continue; } if (lowerPageBound <= i && i <= upperPageBound) { if (mDirtyPageContent.get(i)) { syncPageItems(i, (i == page) && immediateAndOnly); mDirtyPageContent.set(i, false); } } } } } } protected int getAssociatedLowerPageBound(int page) { return Math.max(0, page - 1); } protected int getAssociatedUpperPageBound(int page) { final int count = getChildCount(); return Math.min(page + 1, count - 1); } /** * This method is called ONLY to synchronize the number of pages that the paged view has. * To actually fill the pages with information, implement syncPageItems() below. It is * guaranteed that syncPageItems() will be called for a particular page before it is shown, * and therefore, individual page items do not need to be updated in this method. */ public abstract void syncPages(); /** * This method is called to synchronize the items that are on a particular page. If views on * the page can be reused, then they should be updated within this method. */ public abstract void syncPageItems(int page, boolean immediate); protected void invalidatePageData() { invalidatePageData(-1, false); } protected void invalidatePageData(int currentPage) { invalidatePageData(currentPage, false); } protected void invalidatePageData(int currentPage, boolean immediateAndOnly) { if (!mIsDataReady) { return; } if (mContentIsRefreshable) { // Force all scrolling-related behavior to end mScroller.forceFinished(true); mNextPage = INVALID_PAGE; // Update all the pages syncPages(); // We must force a measure after we've loaded the pages to update the content width and // to determine the full scroll width measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY)); // Set a new page as the current page if necessary if (currentPage > -1) { setCurrentPage(Math.min(getPageCount() - 1, currentPage)); } // Mark each of the pages as dirty final int count = getChildCount(); mDirtyPageContent.clear(); for (int i = 0; i < count; ++i) { mDirtyPageContent.add(true); } // Load any pages that are necessary for the current window of views loadAssociatedPages(mCurrentPage, immediateAndOnly); requestLayout(); } if (isPageMoving()) { // If the page is moving, then snap it to the final position to ensure we don't get // stuck between pages snapToDestination(); } } // Animate the drag view back to the original position void animateDragViewToOriginalPosition() { if (mDragView != null) { AnimatorSet anim = new AnimatorSet(); anim.setDuration(REORDERING_DROP_REPOSITION_DURATION); anim.playTogether( ObjectAnimator.ofFloat(mDragView, "translationX", 0f), ObjectAnimator.ofFloat(mDragView, "translationY", 0f), ObjectAnimator.ofFloat(mDragView, "scaleX", 1f), ObjectAnimator.ofFloat(mDragView, "scaleY", 1f)); anim.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { onPostReorderingAnimationCompleted(); } }); anim.start(); } } protected void onStartReordering() { // Set the touch state to reordering (allows snapping to pages, dragging a child, etc.) mTouchState = TOUCH_STATE_REORDERING; mIsReordering = true; // We must invalidate to trigger a redraw to update the layers such that the drag view // is always drawn on top invalidate(); } private void onPostReorderingAnimationCompleted() { // Trigger the callback when reordering has settled --mPostReorderingPreZoomInRemainingAnimationCount; if (mPostReorderingPreZoomInRunnable != null && mPostReorderingPreZoomInRemainingAnimationCount == 0) { mPostReorderingPreZoomInRunnable.run(); mPostReorderingPreZoomInRunnable = null; } } protected void onEndReordering() { mIsReordering = false; } public boolean startReordering(View v) { int dragViewIndex = indexOfChild(v); if (mTouchState != TOUCH_STATE_REST) return false; mTempVisiblePagesRange[0] = 0; mTempVisiblePagesRange[1] = getPageCount() - 1; getOverviewModePages(mTempVisiblePagesRange); mReorderingStarted = true; // Check if we are within the reordering range if (mTempVisiblePagesRange[0] <= dragViewIndex && dragViewIndex <= mTempVisiblePagesRange[1]) { // Find the drag view under the pointer mDragView = getChildAt(dragViewIndex); mDragView.animate().scaleX(1.15f).scaleY(1.15f).setDuration(100).start(); mDragViewBaselineLeft = mDragView.getLeft(); disableFreeScroll(-1); onStartReordering(); return true; } return false; } boolean isReordering(boolean testTouchState) { boolean state = mIsReordering; if (testTouchState) { state &= (mTouchState == TOUCH_STATE_REORDERING); } return state; } void endReordering() { // For simplicity, we call endReordering sometimes even if reordering was never started. // In that case, we don't want to do anything. if (!mReorderingStarted) return; mReorderingStarted = false; // If we haven't flung-to-delete the current child, then we just animate the drag view // back into position final Runnable onCompleteRunnable = new Runnable() { @Override public void run() { onEndReordering(); } }; if (!mDeferringForDelete) { mPostReorderingPreZoomInRunnable = new Runnable() { public void run() { onCompleteRunnable.run(); enableFreeScroll(); }; }; mPostReorderingPreZoomInRemainingAnimationCount = NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT; // Snap to the current page snapToPage(indexOfChild(mDragView), 0); // Animate the drag view back to the front position animateDragViewToOriginalPosition(); } else { // Handled in post-delete-animation-callbacks } } /* * Flinging to delete - IN PROGRESS */ private PointF isFlingingToDelete() { ViewConfiguration config = ViewConfiguration.get(getContext()); mVelocityTracker.computeCurrentVelocity(1000, config.getScaledMaximumFlingVelocity()); if (mVelocityTracker.getYVelocity() < mFlingToDeleteThresholdVelocity) { // Do a quick dot product test to ensure that we are flinging upwards PointF vel = new PointF(mVelocityTracker.getXVelocity(), mVelocityTracker.getYVelocity()); PointF upVec = new PointF(0f, -1f); float theta = (float) Math.acos(((vel.x * upVec.x) + (vel.y * upVec.y)) / (vel.length() * upVec.length())); if (theta <= Math.toRadians(FLING_TO_DELETE_MAX_FLING_DEGREES)) { return vel; } } return null; } /** * Creates an animation from the current drag view along its current velocity vector. * For this animation, the alpha runs for a fixed duration and we update the position * progressively. */ private static class FlingAlongVectorAnimatorUpdateListener implements AnimatorUpdateListener { private View mDragView; private PointF mVelocity; private Rect mFrom; private long mPrevTime; private float mFriction; private final TimeInterpolator mAlphaInterpolator = new DecelerateInterpolator(0.75f); public FlingAlongVectorAnimatorUpdateListener(View dragView, PointF vel, Rect from, long startTime, float friction) { mDragView = dragView; mVelocity = vel; mFrom = from; mPrevTime = startTime; mFriction = 1f - (mDragView.getResources().getDisplayMetrics().density * friction); } @Override public void onAnimationUpdate(ValueAnimator animation) { float t = ((Float) animation.getAnimatedValue()).floatValue(); long curTime = AnimationUtils.currentAnimationTimeMillis(); mFrom.left += (mVelocity.x * (curTime - mPrevTime) / 1000f); mFrom.top += (mVelocity.y * (curTime - mPrevTime) / 1000f); mDragView.setTranslationX(mFrom.left); mDragView.setTranslationY(mFrom.top); mDragView.setAlpha(1f - mAlphaInterpolator.getInterpolation(t)); mVelocity.x *= mFriction; mVelocity.y *= mFriction; mPrevTime = curTime; } }; private static final int ANIM_TAG_KEY = 100; private Runnable createPostDeleteAnimationRunnable(final View dragView) { return new Runnable() { @Override public void run() { int dragViewIndex = indexOfChild(dragView); // For each of the pages around the drag view, animate them from the previous // position to the new position in the layout (as a result of the drag view moving // in the layout) // NOTE: We can make an assumption here because we have side-bound pages that we // will always have pages to animate in from the left getOverviewModePages(mTempVisiblePagesRange); boolean isLastWidgetPage = (mTempVisiblePagesRange[0] == mTempVisiblePagesRange[1]); boolean slideFromLeft = (isLastWidgetPage || dragViewIndex > mTempVisiblePagesRange[0]); // Setup the scroll to the correct page before we swap the views if (slideFromLeft) { snapToPageImmediately(dragViewIndex - 1); } int firstIndex = (isLastWidgetPage ? 0 : mTempVisiblePagesRange[0]); int lastIndex = Math.min(mTempVisiblePagesRange[1], getPageCount() - 1); int lowerIndex = (slideFromLeft ? firstIndex : dragViewIndex + 1 ); int upperIndex = (slideFromLeft ? dragViewIndex - 1 : lastIndex); ArrayList<Animator> animations = new ArrayList<Animator>(); for (int i = lowerIndex; i <= upperIndex; ++i) { View v = getChildAt(i); // dragViewIndex < pageUnderPointIndex, so after we remove the // drag view all subsequent views to pageUnderPointIndex will // shift down. int oldX = 0; int newX = 0; if (slideFromLeft) { if (i == 0) { // Simulate the page being offscreen with the page spacing oldX = getViewportOffsetX() + getChildOffset(i) - getChildWidth(i) - mPageSpacing; } else { oldX = getViewportOffsetX() + getChildOffset(i - 1); } newX = getViewportOffsetX() + getChildOffset(i); } else { oldX = getChildOffset(i) - getChildOffset(i - 1); newX = 0; } // Animate the view translation from its old position to its new // position AnimatorSet anim = (AnimatorSet) v.getTag(); if (anim != null) { anim.cancel(); } // Note: Hacky, but we want to skip any optimizations to not draw completely // hidden views v.setAlpha(Math.max(v.getAlpha(), 0.01f)); v.setTranslationX(oldX - newX); anim = new AnimatorSet(); anim.playTogether( ObjectAnimator.ofFloat(v, "translationX", 0f), ObjectAnimator.ofFloat(v, "alpha", 1f)); animations.add(anim); v.setTag(ANIM_TAG_KEY, anim); } AnimatorSet slideAnimations = new AnimatorSet(); slideAnimations.playTogether(animations); slideAnimations.setDuration(DELETE_SLIDE_IN_SIDE_PAGE_DURATION); slideAnimations.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mDeferringForDelete = false; onEndReordering(); onRemoveViewAnimationCompleted(); } }); slideAnimations.start(); removeView(dragView); onRemoveView(dragView, true); } }; } public void onFlingToDelete(PointF vel) { final long startTime = AnimationUtils.currentAnimationTimeMillis(); // NOTE: Because it takes time for the first frame of animation to actually be // called and we expect the animation to be a continuation of the fling, we have // to account for the time that has elapsed since the fling finished. And since // we don't have a startDelay, we will always get call to update when we call // start() (which we want to ignore). final TimeInterpolator tInterpolator = new TimeInterpolator() { private int mCount = -1; private long mStartTime; private float mOffset; /* Anonymous inner class ctor */ { mStartTime = startTime; } @Override public float getInterpolation(float t) { if (mCount < 0) { mCount++; } else if (mCount == 0) { mOffset = Math.min(0.5f, (float) (AnimationUtils.currentAnimationTimeMillis() - mStartTime) / FLING_TO_DELETE_FADE_OUT_DURATION); mCount++; } return Math.min(1f, mOffset + t); } }; final Rect from = new Rect(); final View dragView = mDragView; from.left = (int) dragView.getTranslationX(); from.top = (int) dragView.getTranslationY(); AnimatorUpdateListener updateCb = new FlingAlongVectorAnimatorUpdateListener(dragView, vel, from, startTime, FLING_TO_DELETE_FRICTION); final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView); // Create and start the animation ValueAnimator mDropAnim = new ValueAnimator(); mDropAnim.setInterpolator(tInterpolator); mDropAnim.setDuration(FLING_TO_DELETE_FADE_OUT_DURATION); mDropAnim.setFloatValues(0f, 1f); mDropAnim.addUpdateListener(updateCb); mDropAnim.addListener(new AnimatorListenerAdapter() { public void onAnimationEnd(Animator animation) { onAnimationEndRunnable.run(); } }); mDropAnim.start(); mDeferringForDelete = true; } /* Drag to delete */ private boolean isHoveringOverDeleteDropTarget(int x, int y) { if (mDeleteDropTarget != null) { mAltTmpRect.set(0, 0, 0, 0); View parent = (View) mDeleteDropTarget.getParent(); if (parent != null) { parent.getGlobalVisibleRect(mAltTmpRect); } mDeleteDropTarget.getGlobalVisibleRect(mTmpRect); mTmpRect.offset(-mAltTmpRect.left, -mAltTmpRect.top); return mTmpRect.contains(x, y); } return false; } protected void setPageHoveringOverDeleteDropTarget(int viewIndex, boolean isHovering) {} private void onDropToDelete() { final View dragView = mDragView; final float toScale = 0f; final float toAlpha = 0f; // Create and start the complex animation ArrayList<Animator> animations = new ArrayList<Animator>(); AnimatorSet motionAnim = new AnimatorSet(); motionAnim.setInterpolator(new DecelerateInterpolator(2)); motionAnim.playTogether( ObjectAnimator.ofFloat(dragView, "scaleX", toScale), ObjectAnimator.ofFloat(dragView, "scaleY", toScale)); animations.add(motionAnim); AnimatorSet alphaAnim = new AnimatorSet(); alphaAnim.setInterpolator(new LinearInterpolator()); alphaAnim.playTogether( ObjectAnimator.ofFloat(dragView, "alpha", toAlpha)); animations.add(alphaAnim); final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView); AnimatorSet anim = new AnimatorSet(); anim.playTogether(animations); anim.setDuration(DRAG_TO_DELETE_FADE_OUT_DURATION); anim.addListener(new AnimatorListenerAdapter() { public void onAnimationEnd(Animator animation) { onAnimationEndRunnable.run(); } }); anim.start(); mDeferringForDelete = true; } /* Accessibility */ @Override public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); info.setScrollable(getPageCount() > 1); if (getCurrentPage() < getPageCount() - 1) { info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD); } if (getCurrentPage() > 0) { info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD); } } @Override public void sendAccessibilityEvent(int eventType) { // Don't let the view send real scroll events. if (eventType != AccessibilityEvent.TYPE_VIEW_SCROLLED) { super.sendAccessibilityEvent(eventType); } } @Override public void onInitializeAccessibilityEvent(AccessibilityEvent event) { super.onInitializeAccessibilityEvent(event); event.setScrollable(true); } @Override public boolean performAccessibilityAction(int action, Bundle arguments) { if (super.performAccessibilityAction(action, arguments)) { return true; } switch (action) { case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: { if (getCurrentPage() < getPageCount() - 1) { scrollRight(); return true; } } break; case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: { if (getCurrentPage() > 0) { scrollLeft(); return true; } } break; } return false; } protected String getCurrentPageDescription() { return String.format(getContext().getString(R.string.default_scroll_format), getNextPage() + 1, getChildCount()); } @Override public boolean onHoverEvent(android.view.MotionEvent event) { return true; } }
app/src/main/java/com/kogitune/launcher3/PagedView.java
/* * Copyright (C) 2012 The Android Open Source Project * * 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.kogitune.launcher3; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.animation.TimeInterpolator; import android.animation.ValueAnimator; import android.animation.ValueAnimator.AnimatorUpdateListener; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color;import android.graphics.Matrix; import android.graphics.PointF; import android.graphics.Rect; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.Log; import android.view.InputDevice; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.ViewParent; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityManager; import android.view.accessibility.AccessibilityNodeInfo; import android.view.animation.AnimationUtils; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import android.view.animation.LinearInterpolator; import android.widget.Scroller; import android.widget.Toast; import java.util.ArrayList; interface Page { public int getPageChildCount(); public View getChildOnPageAt(int i); public void removeAllViewsOnPage(); public void removeViewOnPageAt(int i); public int indexOfChildOnPage(View v); } /** * An abstraction of the original Workspace which supports browsing through a * sequential list of "pages" */ public abstract class PagedView extends ViewGroup implements ViewGroup.OnHierarchyChangeListener { private static final String TAG = "PagedView"; protected static final boolean DEBUG = true; protected static final int INVALID_PAGE = -1; // the min drag distance for a fling to register, to prevent random page shifts private static final int MIN_LENGTH_FOR_FLING = 25; protected static final int PAGE_SNAP_ANIMATION_DURATION = 750; protected static final int SLOW_PAGE_SNAP_ANIMATION_DURATION = 950; protected static final float NANOTIME_DIV = 1000000000.0f; private static final float OVERSCROLL_ACCELERATE_FACTOR = 2; private static final float OVERSCROLL_DAMP_FACTOR = 0.14f; private static final float RETURN_TO_ORIGINAL_PAGE_THRESHOLD = 0.33f; // The page is moved more than halfway, automatically move to the next page on touch up. private static final float SIGNIFICANT_MOVE_THRESHOLD = 0.4f; // The following constants need to be scaled based on density. The scaled versions will be // assigned to the corresponding member variables below. private static final int FLING_THRESHOLD_VELOCITY = 500; private static final int MIN_SNAP_VELOCITY = 1500; private static final int MIN_FLING_VELOCITY = 250; // We are disabling touch interaction of the widget region for factory ROM. private static final boolean DISABLE_TOUCH_INTERACTION = false; private static final boolean DISABLE_TOUCH_SIDE_PAGES = true; private static final boolean DISABLE_FLING_TO_DELETE = true; public static final int INVALID_RESTORE_PAGE = -1001; private boolean mFreeScroll = false; private int mFreeScrollMinScrollX = -1; private int mFreeScrollMaxScrollX = -1; static final int AUTOMATIC_PAGE_SPACING = -1; protected int mFlingThresholdVelocity; protected int mMinFlingVelocity; protected int mMinSnapVelocity; protected float mDensity; protected float mSmoothingTime; protected float mTouchX; protected boolean mFirstLayout = true; private int mNormalChildHeight; protected int mCurrentPage; protected int mRestorePage = INVALID_RESTORE_PAGE; protected int mChildCountOnLastLayout; protected int mNextPage = INVALID_PAGE; protected int mMaxScrollX; protected Scroller mScroller; private VelocityTracker mVelocityTracker; private float mParentDownMotionX; private float mParentDownMotionY; private float mDownMotionX; private float mDownMotionY; private float mDownScrollX; private float mDragViewBaselineLeft; protected float mLastMotionX; protected float mLastMotionXRemainder; protected float mLastMotionY; protected float mTotalMotionX; private int mLastScreenCenter = -1; private boolean mCancelTap; private int[] mPageScrolls; protected final static int TOUCH_STATE_REST = 0; protected final static int TOUCH_STATE_SCROLLING = 1; protected final static int TOUCH_STATE_PREV_PAGE = 2; protected final static int TOUCH_STATE_NEXT_PAGE = 3; protected final static int TOUCH_STATE_REORDERING = 4; protected final static float ALPHA_QUANTIZE_LEVEL = 0.0001f; protected int mTouchState = TOUCH_STATE_REST; protected boolean mForceScreenScrolled = false; protected OnLongClickListener mLongClickListener; protected int mTouchSlop; private int mPagingTouchSlop; private int mMaximumVelocity; protected int mPageSpacing; protected int mPageLayoutPaddingTop; protected int mPageLayoutPaddingBottom; protected int mPageLayoutPaddingLeft; protected int mPageLayoutPaddingRight; protected int mPageLayoutWidthGap; protected int mPageLayoutHeightGap; protected int mCellCountX = 0; protected int mCellCountY = 0; protected boolean mCenterPagesVertically; protected boolean mAllowOverScroll = true; protected int mUnboundedScrollX; protected int[] mTempVisiblePagesRange = new int[2]; protected boolean mForceDrawAllChildrenNextFrame; // mOverScrollX is equal to getScrollX() when we're within the normal scroll range. Otherwise // it is equal to the scaled overscroll position. We use a separate value so as to prevent // the screens from continuing to translate beyond the normal bounds. protected int mOverScrollX; protected static final int INVALID_POINTER = -1; protected int mActivePointerId = INVALID_POINTER; private PageSwitchListener mPageSwitchListener; protected ArrayList<Boolean> mDirtyPageContent; // If true, syncPages and syncPageItems will be called to refresh pages protected boolean mContentIsRefreshable = true; // If true, modify alpha of neighboring pages as user scrolls left/right protected boolean mFadeInAdjacentScreens = false; // It true, use a different slop parameter (pagingTouchSlop = 2 * touchSlop) for deciding // to switch to a new page protected boolean mUsePagingTouchSlop = true; // If true, the subclass should directly update scrollX itself in its computeScroll method // (SmoothPagedView does this) protected boolean mDeferScrollUpdate = false; protected boolean mDeferLoadAssociatedPagesUntilScrollCompletes = false; protected boolean mIsPageMoving = false; // All syncs and layout passes are deferred until data is ready. protected boolean mIsDataReady = false; protected boolean mAllowLongPress = true; // Page Indicator private int mPageIndicatorViewId; private PageIndicator mPageIndicator; private boolean mAllowPagedViewAnimations = true; // The viewport whether the pages are to be contained (the actual view may be larger than the // viewport) private Rect mViewport = new Rect(); // Reordering // We use the min scale to determine how much to expand the actually PagedView measured // dimensions such that when we are zoomed out, the view is not clipped private int REORDERING_DROP_REPOSITION_DURATION = 200; protected int REORDERING_REORDER_REPOSITION_DURATION = 300; protected int REORDERING_ZOOM_IN_OUT_DURATION = 250; private int REORDERING_SIDE_PAGE_HOVER_TIMEOUT = 80; private float mMinScale = 1f; private boolean mUseMinScale = false; protected View mDragView; protected AnimatorSet mZoomInOutAnim; private Runnable mSidePageHoverRunnable; private int mSidePageHoverIndex = -1; // This variable's scope is only for the duration of startReordering() and endReordering() private boolean mReorderingStarted = false; // This variable's scope is for the duration of startReordering() and after the zoomIn() // animation after endReordering() private boolean mIsReordering; // The runnable that settles the page after snapToPage and animateDragViewToOriginalPosition private int NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT = 2; private int mPostReorderingPreZoomInRemainingAnimationCount; private Runnable mPostReorderingPreZoomInRunnable; // Convenience/caching private Matrix mTmpInvMatrix = new Matrix(); private float[] mTmpPoint = new float[2]; private int[] mTmpIntPoint = new int[2]; private Rect mTmpRect = new Rect(); private Rect mAltTmpRect = new Rect(); // Fling to delete private int FLING_TO_DELETE_FADE_OUT_DURATION = 350; private float FLING_TO_DELETE_FRICTION = 0.035f; // The degrees specifies how much deviation from the up vector to still consider a fling "up" private float FLING_TO_DELETE_MAX_FLING_DEGREES = 65f; protected int mFlingToDeleteThresholdVelocity = -1400; // Drag to delete private boolean mDeferringForDelete = false; private int DELETE_SLIDE_IN_SIDE_PAGE_DURATION = 250; private int DRAG_TO_DELETE_FADE_OUT_DURATION = 350; // Drop to delete private View mDeleteDropTarget; private boolean mAutoComputePageSpacing = false; private boolean mRecomputePageSpacing = false; // Bouncer private boolean mTopAlignPageWhenShrinkingForBouncer = false; protected final Rect mInsets = new Rect(); protected int mFirstChildLeft; public interface PageSwitchListener { void onPageSwitch(View newPage, int newPageIndex); } public PagedView(Context context) { this(context, null); } public PagedView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public PagedView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PagedView, defStyle, 0); setPageSpacing(a.getDimensionPixelSize(R.styleable.PagedView_pageSpacing, 0)); if (mPageSpacing < 0) { mAutoComputePageSpacing = mRecomputePageSpacing = true; } mPageLayoutPaddingTop = a.getDimensionPixelSize( R.styleable.PagedView_pageLayoutPaddingTop, 0); mPageLayoutPaddingBottom = a.getDimensionPixelSize( R.styleable.PagedView_pageLayoutPaddingBottom, 0); mPageLayoutPaddingLeft = a.getDimensionPixelSize( R.styleable.PagedView_pageLayoutPaddingLeft, 0); mPageLayoutPaddingRight = a.getDimensionPixelSize( R.styleable.PagedView_pageLayoutPaddingRight, 0); mPageLayoutWidthGap = a.getDimensionPixelSize( R.styleable.PagedView_pageLayoutWidthGap, 0); mPageLayoutHeightGap = a.getDimensionPixelSize( R.styleable.PagedView_pageLayoutHeightGap, 0); mPageIndicatorViewId = a.getResourceId(R.styleable.PagedView_pageIndicator, -1); a.recycle(); setHapticFeedbackEnabled(false); init(); } /** * Initializes various states for this workspace. */ protected void init() { mDirtyPageContent = new ArrayList<Boolean>(); mDirtyPageContent.ensureCapacity(32); mScroller = new Scroller(getContext(), new ScrollInterpolator()); mCurrentPage = 0; mCenterPagesVertically = true; final ViewConfiguration configuration = ViewConfiguration.get(getContext()); mTouchSlop = configuration.getScaledPagingTouchSlop(); mPagingTouchSlop = configuration.getScaledPagingTouchSlop(); mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); mDensity = getResources().getDisplayMetrics().density; // Scale the fling-to-delete threshold by the density mFlingToDeleteThresholdVelocity = (int) (mFlingToDeleteThresholdVelocity * mDensity); mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * mDensity); mMinFlingVelocity = (int) (MIN_FLING_VELOCITY * mDensity); mMinSnapVelocity = (int) (MIN_SNAP_VELOCITY * mDensity); setOnHierarchyChangeListener(this); } protected void onAttachedToWindow() { super.onAttachedToWindow(); // Hook up the page indicator ViewGroup parent = (ViewGroup) getParent(); if (mPageIndicator == null && mPageIndicatorViewId > -1) { mPageIndicator = (PageIndicator) parent.findViewById(mPageIndicatorViewId); mPageIndicator.removeAllMarkers(mAllowPagedViewAnimations); ArrayList<PageIndicator.PageMarkerResources> markers = new ArrayList<PageIndicator.PageMarkerResources>(); for (int i = 0; i < getChildCount(); ++i) { markers.add(getPageIndicatorMarker(i)); } mPageIndicator.addMarkers(markers, mAllowPagedViewAnimations); OnClickListener listener = getPageIndicatorClickListener(); if (listener != null) { mPageIndicator.setOnClickListener(listener); } mPageIndicator.setContentDescription(getPageIndicatorDescription()); } } protected String getPageIndicatorDescription() { return getCurrentPageDescription(); } protected OnClickListener getPageIndicatorClickListener() { return null; } protected void onDetachedFromWindow() { // Unhook the page indicator mPageIndicator = null; } void setDeleteDropTarget(View v) { mDeleteDropTarget = v; } // Convenience methods to map points from self to parent and vice versa float[] mapPointFromViewToParent(View v, float x, float y) { mTmpPoint[0] = x; mTmpPoint[1] = y; v.getMatrix().mapPoints(mTmpPoint); mTmpPoint[0] += v.getLeft(); mTmpPoint[1] += v.getTop(); return mTmpPoint; } float[] mapPointFromParentToView(View v, float x, float y) { mTmpPoint[0] = x - v.getLeft(); mTmpPoint[1] = y - v.getTop(); v.getMatrix().invert(mTmpInvMatrix); mTmpInvMatrix.mapPoints(mTmpPoint); return mTmpPoint; } void updateDragViewTranslationDuringDrag() { if (mDragView != null) { float x = (mLastMotionX - mDownMotionX) + (getScrollX() - mDownScrollX) + (mDragViewBaselineLeft - mDragView.getLeft()); float y = mLastMotionY - mDownMotionY; mDragView.setTranslationX(x); mDragView.setTranslationY(y); if (DEBUG) Log.d(TAG, "PagedView.updateDragViewTranslationDuringDrag(): " + x + ", " + y); } } public void setMinScale(float f) { mMinScale = f; mUseMinScale = true; requestLayout(); } @Override public void setScaleX(float scaleX) { super.setScaleX(scaleX); if (isReordering(true)) { float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY); mLastMotionX = p[0]; mLastMotionY = p[1]; updateDragViewTranslationDuringDrag(); } } // Convenience methods to get the actual width/height of the PagedView (since it is measured // to be larger to account for the minimum possible scale) int getViewportWidth() { return mViewport.width(); } int getViewportHeight() { return mViewport.height(); } // Convenience methods to get the offset ASSUMING that we are centering the pages in the // PagedView both horizontally and vertically int getViewportOffsetX() { return (getMeasuredWidth() - getViewportWidth()) / 2; } int getViewportOffsetY() { return (getMeasuredHeight() - getViewportHeight()) / 2; } PageIndicator getPageIndicator() { return mPageIndicator; } protected PageIndicator.PageMarkerResources getPageIndicatorMarker(int pageIndex) { return new PageIndicator.PageMarkerResources(); } public void setPageSwitchListener(PageSwitchListener pageSwitchListener) { mPageSwitchListener = pageSwitchListener; if (mPageSwitchListener != null) { mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage); } } /** * Note: this is a reimplementation of View.isLayoutRtl() since that is currently hidden api. */ public boolean isLayoutRtl() { return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); } /** * Called by subclasses to mark that data is ready, and that we can begin loading and laying * out pages. */ protected void setDataIsReady() { mIsDataReady = true; } protected boolean isDataReady() { return mIsDataReady; } /** * Returns the index of the currently displayed page. * * @return The index of the currently displayed page. */ int getCurrentPage() { return mCurrentPage; } int getNextPage() { return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage; } int getPageCount() { return getChildCount(); } View getPageAt(int index) { return getChildAt(index); } protected int indexToPage(int index) { return index; } /** * Updates the scroll of the current page immediately to its final scroll position. We use this * in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of * the previous tab page. */ protected void updateCurrentPageScroll() { // If the current page is invalid, just reset the scroll position to zero int newX = 0; if (0 <= mCurrentPage && mCurrentPage < getPageCount()) { newX = getScrollForPage(mCurrentPage); } scrollTo(newX, 0); mScroller.setFinalX(newX); mScroller.forceFinished(true); } /** * Called during AllApps/Home transitions to avoid unnecessary work. When that other animation * ends, {@link #resumeScrolling()} should be called, along with * {@link #updateCurrentPageScroll()} to correctly set the final state and re-enable scrolling. */ void pauseScrolling() { mScroller.forceFinished(true); } /** * Enables scrolling again. * @see #pauseScrolling() */ void resumeScrolling() { } /** * Sets the current page. */ void setCurrentPage(int currentPage) { if (!mScroller.isFinished()) { mScroller.abortAnimation(); // We need to clean up the next page here to avoid computeScrollHelper from // updating current page on the pass. mNextPage = INVALID_PAGE; } // don't introduce any checks like mCurrentPage == currentPage here-- if we change the // the default if (getChildCount() == 0) { return; } mForceScreenScrolled = true; mCurrentPage = Math.max(0, Math.min(currentPage, getPageCount() - 1)); updateCurrentPageScroll(); notifyPageSwitchListener(); invalidate(); } /** * The restore page will be set in place of the current page at the next (likely first) * layout. */ void setRestorePage(int restorePage) { mRestorePage = restorePage; } protected void notifyPageSwitchListener() { if (mPageSwitchListener != null) { mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage); } // Update the page indicator (when we aren't reordering) if (mPageIndicator != null && !isReordering(false)) { mPageIndicator.setActiveMarker(getNextPage()); } } protected void pageBeginMoving() { if (!mIsPageMoving) { mIsPageMoving = true; onPageBeginMoving(); } } protected void pageEndMoving() { if (mIsPageMoving) { mIsPageMoving = false; onPageEndMoving(); } } protected boolean isPageMoving() { return mIsPageMoving; } // a method that subclasses can override to add behavior protected void onPageBeginMoving() { } // a method that subclasses can override to add behavior protected void onPageEndMoving() { } /** * Registers the specified listener on each page contained in this workspace. * * @param l The listener used to respond to long clicks. */ @Override public void setOnLongClickListener(OnLongClickListener l) { mLongClickListener = l; final int count = getPageCount(); for (int i = 0; i < count; i++) { getPageAt(i).setOnLongClickListener(l); } super.setOnLongClickListener(l); } @Override public void scrollBy(int x, int y) { scrollTo(mUnboundedScrollX + x, getScrollY() + y); } @Override public void scrollTo(int x, int y) { // In free scroll mode, we clamp the scrollX if (mFreeScroll) { x = Math.min(x, mFreeScrollMaxScrollX); x = Math.max(x, mFreeScrollMinScrollX); } final boolean isRtl = isLayoutRtl(); mUnboundedScrollX = x; boolean isXBeforeFirstPage = isRtl ? (x > mMaxScrollX) : (x < 0); boolean isXAfterLastPage = isRtl ? (x < 0) : (x > mMaxScrollX); if (isXBeforeFirstPage) { super.scrollTo(0, y); if (mAllowOverScroll) { if (isRtl) { overScroll(x - mMaxScrollX); } else { overScroll(x); } } } else if (isXAfterLastPage) { super.scrollTo(mMaxScrollX, y); if (mAllowOverScroll) { if (isRtl) { overScroll(x); } else { overScroll(x - mMaxScrollX); } } } else { mOverScrollX = x; super.scrollTo(x, y); } mTouchX = x; mSmoothingTime = System.nanoTime() / NANOTIME_DIV; // Update the last motion events when scrolling if (isReordering(true)) { float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY); mLastMotionX = p[0]; mLastMotionY = p[1]; updateDragViewTranslationDuringDrag(); } } private void sendScrollAccessibilityEvent() { AccessibilityManager am = (AccessibilityManager) getContext().getSystemService(Context.ACCESSIBILITY_SERVICE); if (am.isEnabled()) { AccessibilityEvent ev = AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED); ev.setItemCount(getChildCount()); ev.setFromIndex(mCurrentPage); final int action; if (getNextPage() >= mCurrentPage) { action = AccessibilityNodeInfo.ACTION_SCROLL_FORWARD; } else { action = AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD; } ev.setAction(action); sendAccessibilityEventUnchecked(ev); } } // we moved this functionality to a helper function so SmoothPagedView can reuse it protected boolean computeScrollHelper() { if (mScroller.computeScrollOffset()) { // Don't bother scrolling if the page does not need to be moved if (getScrollX() != mScroller.getCurrX() || getScrollY() != mScroller.getCurrY() || mOverScrollX != mScroller.getCurrX()) { float scaleX = mFreeScroll ? getScaleX() : 1f; int scrollX = (int) (mScroller.getCurrX() * (1 / scaleX)); scrollTo(scrollX, mScroller.getCurrY()); } invalidate(); return true; } else if (mNextPage != INVALID_PAGE) { sendScrollAccessibilityEvent(); mCurrentPage = Math.max(0, Math.min(mNextPage, getPageCount() - 1)); mNextPage = INVALID_PAGE; notifyPageSwitchListener(); // Load the associated pages if necessary if (mDeferLoadAssociatedPagesUntilScrollCompletes) { loadAssociatedPages(mCurrentPage); mDeferLoadAssociatedPagesUntilScrollCompletes = false; } // We don't want to trigger a page end moving unless the page has settled // and the user has stopped scrolling if (mTouchState == TOUCH_STATE_REST) { pageEndMoving(); } onPostReorderingAnimationCompleted(); AccessibilityManager am = (AccessibilityManager) getContext().getSystemService(Context.ACCESSIBILITY_SERVICE); if (am.isEnabled()) { // Notify the user when the page changes announceForAccessibility(getCurrentPageDescription()); } return true; } return false; } @Override public void computeScroll() { computeScrollHelper(); } protected boolean shouldSetTopAlignedPivotForWidget(int childIndex) { return mTopAlignPageWhenShrinkingForBouncer; } public static class LayoutParams extends ViewGroup.LayoutParams { public boolean isFullScreenPage = false; /** * {@inheritDoc} */ public LayoutParams(int width, int height) { super(width, height); } public LayoutParams(ViewGroup.LayoutParams source) { super(source); } } protected LayoutParams generateDefaultLayoutParams() { return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); } public void addFullScreenPage(View page) { LayoutParams lp = generateDefaultLayoutParams(); lp.isFullScreenPage = true; super.addView(page, 0, lp); } public int getNormalChildHeight() { return mNormalChildHeight; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (!mIsDataReady || getChildCount() == 0) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); return; } // We measure the dimensions of the PagedView to be larger than the pages so that when we // zoom out (and scale down), the view is still contained in the parent int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); // NOTE: We multiply by 1.5f to account for the fact that depending on the offset of the // viewport, we can be at most one and a half screens offset once we scale down DisplayMetrics dm = getResources().getDisplayMetrics(); int maxSize = Math.max(dm.widthPixels, dm.heightPixels + mInsets.top + mInsets.bottom); int parentWidthSize, parentHeightSize; int scaledWidthSize, scaledHeightSize; if (mUseMinScale) { parentWidthSize = (int) (1.5f * maxSize); parentHeightSize = maxSize; scaledWidthSize = (int) (parentWidthSize / mMinScale); scaledHeightSize = (int) (parentHeightSize / mMinScale); } else { scaledWidthSize = widthSize; scaledHeightSize = heightSize; } mViewport.set(0, 0, widthSize, heightSize); if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); return; } // Return early if we aren't given a proper dimension if (widthSize <= 0 || heightSize <= 0) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); return; } /* Allow the height to be set as WRAP_CONTENT. This allows the particular case * of the All apps view on XLarge displays to not take up more space then it needs. Width * is still not allowed to be set as WRAP_CONTENT since many parts of the code expect * each page to have the same width. */ final int verticalPadding = getPaddingTop() + getPaddingBottom(); final int horizontalPadding = getPaddingLeft() + getPaddingRight(); // The children are given the same width and height as the workspace // unless they were set to WRAP_CONTENT if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize); if (DEBUG) Log.d(TAG, "PagedView.scaledSize: " + scaledWidthSize + ", " + scaledHeightSize); //if (DEBUG) Log.d(TAG, "PagedView.parentSize: " + parentWidthSize + ", " + parentHeightSize); if (DEBUG) Log.d(TAG, "PagedView.horizontalPadding: " + horizontalPadding); if (DEBUG) Log.d(TAG, "PagedView.verticalPadding: " + verticalPadding); final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { // disallowing padding in paged view (just pass 0) final View child = getPageAt(i); if (child.getVisibility() != GONE) { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); int childWidthMode; int childHeightMode; int childWidth; int childHeight; if (!lp.isFullScreenPage) { if (lp.width == LayoutParams.WRAP_CONTENT) { childWidthMode = MeasureSpec.AT_MOST; } else { childWidthMode = MeasureSpec.EXACTLY; } if (lp.height == LayoutParams.WRAP_CONTENT) { childHeightMode = MeasureSpec.AT_MOST; } else { childHeightMode = MeasureSpec.EXACTLY; } childWidth = widthSize - horizontalPadding; childHeight = heightSize - verticalPadding - mInsets.top - mInsets.bottom; mNormalChildHeight = childHeight; } else { childWidthMode = MeasureSpec.EXACTLY; childHeightMode = MeasureSpec.EXACTLY; if (mUseMinScale) { childWidth = getViewportWidth(); childHeight = getViewportHeight(); } else { childWidth = widthSize - getPaddingLeft() - getPaddingRight(); childHeight = heightSize - getPaddingTop() - getPaddingBottom(); } } final int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidth, childWidthMode); final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeight, childHeightMode); child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } } setMeasuredDimension(scaledWidthSize, scaledHeightSize); if (childCount > 0) { // Calculate the variable page spacing if necessary if (mAutoComputePageSpacing && mRecomputePageSpacing) { // The gap between pages in the PagedView should be equal to the gap from the page // to the edge of the screen (so it is not visible in the current screen). To // account for unequal padding on each side of the paged view, we take the maximum // of the left/right gap and use that as the gap between each page. int offset = (getViewportWidth() - getChildWidth(0)) / 2; int spacing = Math.max(offset, widthSize - offset - getChildAt(0).getMeasuredWidth()); setPageSpacing(spacing); mRecomputePageSpacing = false; } } } public void setPageSpacing(int pageSpacing) { mPageSpacing = pageSpacing; requestLayout(); } protected int getFirstChildLeft() { return mFirstChildLeft; } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { if (!mIsDataReady || getChildCount() == 0) { return; } if (DEBUG) Log.d(TAG, "PagedView.onLayout()"); final int childCount = getChildCount(); int screenWidth = getViewportWidth(); int offsetX = getViewportOffsetX(); int offsetY = getViewportOffsetY(); // Update the viewport offsets mViewport.offset(offsetX, offsetY); final boolean isRtl = isLayoutRtl(); final int startIndex = isRtl ? childCount - 1 : 0; final int endIndex = isRtl ? -1 : childCount; final int delta = isRtl ? -1 : 1; int verticalPadding = getPaddingTop() + getPaddingBottom(); int childLeft = mFirstChildLeft = offsetX + (screenWidth - getChildWidth(startIndex)) / 2; if (mPageScrolls == null || getChildCount() != mChildCountOnLastLayout) { mPageScrolls = new int[getChildCount()]; } for (int i = startIndex; i != endIndex; i += delta) { final View child = getPageAt(i); if (child.getVisibility() != View.GONE) { LayoutParams lp = (LayoutParams) child.getLayoutParams(); int childTop; if (lp.isFullScreenPage) { childTop = offsetY; } else { childTop = offsetY + getPaddingTop() + mInsets.top; if (mCenterPagesVertically) { childTop += (getViewportHeight() - mInsets.top - mInsets.bottom - verticalPadding - child.getMeasuredHeight()) / 2; } } final int childWidth = child.getMeasuredWidth(); final int childHeight = child.getMeasuredHeight(); if (DEBUG) Log.d(TAG, "\tlayout-child" + i + ": " + childLeft + ", " + childTop); child.layout(childLeft, childTop, childLeft + child.getMeasuredWidth(), childTop + childHeight); // We assume the left and right padding are equal, and hence center the pages // horizontally int scrollOffset = (getViewportWidth() - childWidth) / 2; mPageScrolls[i] = childLeft - scrollOffset - offsetX; if (i != endIndex - delta) { childLeft += childWidth + scrollOffset; int nextScrollOffset = (getViewportWidth() - getChildWidth(i + delta)) / 2; childLeft += nextScrollOffset; } } } if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) { setHorizontalScrollBarEnabled(false); updateCurrentPageScroll(); setHorizontalScrollBarEnabled(true); mFirstLayout = false; } if (childCount > 0) { final int index = isLayoutRtl() ? 0 : childCount - 1; mMaxScrollX = getScrollForPage(index); } else { mMaxScrollX = 0; } if (mScroller.isFinished() && mChildCountOnLastLayout != getChildCount() && !mDeferringForDelete) { if (mRestorePage != INVALID_RESTORE_PAGE) { setCurrentPage(mRestorePage); mRestorePage = INVALID_RESTORE_PAGE; } else { setCurrentPage(getNextPage()); } } mChildCountOnLastLayout = getChildCount(); if (isReordering(true)) { updateDragViewTranslationDuringDrag(); } } protected void screenScrolled(int screenCenter) { boolean isInOverscroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX; if (mFadeInAdjacentScreens && !isInOverscroll) { for (int i = 0; i < getChildCount(); i++) { View child = getChildAt(i); if (child != null) { float scrollProgress = getScrollProgress(screenCenter, child, i); float alpha = 1 - Math.abs(scrollProgress); child.setAlpha(alpha); } } invalidate(); } } protected void enablePagedViewAnimations() { mAllowPagedViewAnimations = true; } protected void disablePagedViewAnimations() { mAllowPagedViewAnimations = false; } @Override public void onChildViewAdded(View parent, View child) { // Update the page indicator, we don't update the page indicator as we // add/remove pages if (mPageIndicator != null && !isReordering(false)) { int pageIndex = indexOfChild(child); mPageIndicator.addMarker(pageIndex, getPageIndicatorMarker(pageIndex), mAllowPagedViewAnimations); } // This ensures that when children are added, they get the correct transforms / alphas // in accordance with any scroll effects. mForceScreenScrolled = true; mRecomputePageSpacing = true; updateFreescrollBounds(); invalidate(); } @Override public void onChildViewRemoved(View parent, View child) { mForceScreenScrolled = true; updateFreescrollBounds(); invalidate(); } private void removeMarkerForView(int index) { // Update the page indicator, we don't update the page indicator as we // add/remove pages if (mPageIndicator != null && !isReordering(false)) { mPageIndicator.removeMarker(index, mAllowPagedViewAnimations); } } @Override public void removeView(View v) { // XXX: We should find a better way to hook into this before the view // gets removed form its parent... removeMarkerForView(indexOfChild(v)); super.removeView(v); } @Override public void removeViewInLayout(View v) { // XXX: We should find a better way to hook into this before the view // gets removed form its parent... removeMarkerForView(indexOfChild(v)); super.removeViewInLayout(v); } @Override public void removeViewAt(int index) { // XXX: We should find a better way to hook into this before the view // gets removed form its parent... removeViewAt(index); super.removeViewAt(index); } @Override public void removeAllViewsInLayout() { // Update the page indicator, we don't update the page indicator as we // add/remove pages if (mPageIndicator != null) { mPageIndicator.removeAllMarkers(mAllowPagedViewAnimations); } super.removeAllViewsInLayout(); } protected int getChildOffset(int index) { if (index < 0 || index > getChildCount() - 1) return 0; int offset = getPageAt(index).getLeft() - getViewportOffsetX(); return offset; } protected void getOverviewModePages(int[] range) { range[0] = 0; range[1] = Math.max(0, getChildCount() - 1); } protected void getVisiblePages(int[] range) { final int pageCount = getChildCount(); mTmpIntPoint[0] = mTmpIntPoint[1] = 0; range[0] = -1; range[1] = -1; if (pageCount > 0) { int viewportWidth = getViewportWidth(); int curScreen = 0; int count = getChildCount(); for (int i = 0; i < count; i++) { View currPage = getPageAt(i); mTmpIntPoint[0] = 0; Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false); if (mTmpIntPoint[0] > viewportWidth) { if (range[0] == -1) { continue; } else { break; } } mTmpIntPoint[0] = currPage.getMeasuredWidth(); Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false); if (mTmpIntPoint[0] < 0) { if (range[0] == -1) { continue; } else { break; } } curScreen = i; if (range[0] < 0) { range[0] = curScreen; } } range[1] = curScreen; } else { range[0] = -1; range[1] = -1; } } protected boolean shouldDrawChild(View child) { return child.getAlpha() > 0 && child.getVisibility() == VISIBLE; } @Override protected void dispatchDraw(Canvas canvas) { int halfScreenSize = getViewportWidth() / 2; // mOverScrollX is equal to getScrollX() when we're within the normal scroll range. // Otherwise it is equal to the scaled overscroll position. int screenCenter = mOverScrollX + halfScreenSize; if (screenCenter != mLastScreenCenter || mForceScreenScrolled) { // set mForceScreenScrolled before calling screenScrolled so that screenScrolled can // set it for the next frame mForceScreenScrolled = false; screenScrolled(screenCenter); mLastScreenCenter = screenCenter; } // Find out which screens are visible; as an optimization we only call draw on them final int pageCount = getChildCount(); if (pageCount > 0) { getVisiblePages(mTempVisiblePagesRange); final int leftScreen = mTempVisiblePagesRange[0]; final int rightScreen = mTempVisiblePagesRange[1]; if (leftScreen != -1 && rightScreen != -1) { final long drawingTime = getDrawingTime(); // Clip to the bounds canvas.save(); canvas.clipRect(getScrollX(), getScrollY(), getScrollX() + getRight() - getLeft(), getScrollY() + getBottom() - getTop()); // Draw all the children, leaving the drag view for last for (int i = pageCount - 1; i >= 0; i--) { final View v = getPageAt(i); if (v == mDragView) continue; if (mForceDrawAllChildrenNextFrame || (leftScreen <= i && i <= rightScreen && shouldDrawChild(v))) { v.setBackgroundColor(Color.argb(55,255,0,0)); drawChild(canvas, v, drawingTime); } } // Draw the drag view on top (if there is one) if (mDragView != null) { drawChild(canvas, mDragView, drawingTime); } mForceDrawAllChildrenNextFrame = false; canvas.restore(); } } } @Override public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) { int page = indexToPage(indexOfChild(child)); if (page != mCurrentPage || !mScroller.isFinished()) { snapToPage(page); return true; } return false; } @Override protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) { int focusablePage; if (mNextPage != INVALID_PAGE) { focusablePage = mNextPage; } else { focusablePage = mCurrentPage; } View v = getPageAt(focusablePage); if (v != null) { return v.requestFocus(direction, previouslyFocusedRect); } return false; } @Override public boolean dispatchUnhandledMove(View focused, int direction) { // XXX-RTL: This will be fixed in a future CL if (direction == View.FOCUS_LEFT) { if (getCurrentPage() > 0) { snapToPage(getCurrentPage() - 1); return true; } } else if (direction == View.FOCUS_RIGHT) { if (getCurrentPage() < getPageCount() - 1) { snapToPage(getCurrentPage() + 1); return true; } } return super.dispatchUnhandledMove(focused, direction); } @Override public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { // XXX-RTL: This will be fixed in a future CL if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) { getPageAt(mCurrentPage).addFocusables(views, direction, focusableMode); } if (direction == View.FOCUS_LEFT) { if (mCurrentPage > 0) { getPageAt(mCurrentPage - 1).addFocusables(views, direction, focusableMode); } } else if (direction == View.FOCUS_RIGHT){ if (mCurrentPage < getPageCount() - 1) { getPageAt(mCurrentPage + 1).addFocusables(views, direction, focusableMode); } } } /** * If one of our descendant views decides that it could be focused now, only * pass that along if it's on the current page. * * This happens when live folders requery, and if they're off page, they * end up calling requestFocus, which pulls it on page. */ @Override public void focusableViewAvailable(View focused) { View current = getPageAt(mCurrentPage); View v = focused; while (true) { if (v == current) { super.focusableViewAvailable(focused); return; } if (v == this) { return; } ViewParent parent = v.getParent(); if (parent instanceof View) { v = (View)v.getParent(); } else { return; } } } /** * {@inheritDoc} */ @Override public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { if (disallowIntercept) { // We need to make sure to cancel our long press if // a scrollable widget takes over touch events final View currentPage = getPageAt(mCurrentPage); currentPage.cancelLongPress(); } super.requestDisallowInterceptTouchEvent(disallowIntercept); } /** * Return true if a tap at (x, y) should trigger a flip to the previous page. */ protected boolean hitsPreviousPage(float x, float y) { int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2; if (isLayoutRtl()) { return (x > (getViewportOffsetX() + getViewportWidth() - offset + mPageSpacing)); } return (x < getViewportOffsetX() + offset - mPageSpacing); } /** * Return true if a tap at (x, y) should trigger a flip to the next page. */ protected boolean hitsNextPage(float x, float y) { int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2; if (isLayoutRtl()) { return (x < getViewportOffsetX() + offset - mPageSpacing); } return (x > (getViewportOffsetX() + getViewportWidth() - offset + mPageSpacing)); } /** Returns whether x and y originated within the buffered viewport */ private boolean isTouchPointInViewportWithBuffer(int x, int y) { mTmpRect.set(mViewport.left - mViewport.width() / 2, mViewport.top, mViewport.right + mViewport.width() / 2, mViewport.bottom); return mTmpRect.contains(x, y); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { if (DISABLE_TOUCH_INTERACTION) { return false; } /* * This method JUST determines whether we want to intercept the motion. * If we return true, onTouchEvent will be called and we do the actual * scrolling there. */ acquireVelocityTrackerAndAddMovement(ev); // Skip touch handling if there are no pages to swipe if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev); /* * Shortcut the most recurring case: the user is in the dragging * state and he is moving his finger. We want to intercept this * motion. */ final int action = ev.getAction(); if ((action == MotionEvent.ACTION_MOVE) && (mTouchState == TOUCH_STATE_SCROLLING)) { return true; } switch (action & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_MOVE: { /* * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check * whether the user has moved far enough from his original down touch. */ if (mActivePointerId != INVALID_POINTER) { determineScrollingStart(ev); } // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN // event. in that case, treat the first occurence of a move event as a ACTION_DOWN // i.e. fall through to the next case (don't break) // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events // while it's small- this was causing a crash before we checked for INVALID_POINTER) break; } case MotionEvent.ACTION_DOWN: { final float x = ev.getX(); final float y = ev.getY(); // Remember location of down touch mDownMotionX = x; mDownMotionY = y; mDownScrollX = getScrollX(); mLastMotionX = x; mLastMotionY = y; float[] p = mapPointFromViewToParent(this, x, y); mParentDownMotionX = p[0]; mParentDownMotionY = p[1]; mLastMotionXRemainder = 0; mTotalMotionX = 0; mActivePointerId = ev.getPointerId(0); /* * If being flinged and user touches the screen, initiate drag; * otherwise don't. mScroller.isFinished should be false when * being flinged. */ final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX()); final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop); if (finishedScrolling) { mTouchState = TOUCH_STATE_REST; mScroller.abortAnimation(); } else { if (isTouchPointInViewportWithBuffer((int) mDownMotionX, (int) mDownMotionY)) { mTouchState = TOUCH_STATE_SCROLLING; } else { mTouchState = TOUCH_STATE_REST; } } // check if this can be the beginning of a tap on the side of the pages // to scroll the current page if (!DISABLE_TOUCH_SIDE_PAGES) { if (mTouchState != TOUCH_STATE_PREV_PAGE && mTouchState != TOUCH_STATE_NEXT_PAGE) { if (getChildCount() > 0) { if (hitsPreviousPage(x, y)) { mTouchState = TOUCH_STATE_PREV_PAGE; } else if (hitsNextPage(x, y)) { mTouchState = TOUCH_STATE_NEXT_PAGE; } } } } break; } case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: resetTouchState(); break; case MotionEvent.ACTION_POINTER_UP: onSecondaryPointerUp(ev); releaseVelocityTracker(); break; } /* * The only time we want to intercept motion events is if we are in the * drag mode. */ return mTouchState != TOUCH_STATE_REST; } protected void determineScrollingStart(MotionEvent ev) { determineScrollingStart(ev, 1.0f); } /* * Determines if we should change the touch state to start scrolling after the * user moves their touch point too far. */ protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) { // Disallow scrolling if we don't have a valid pointer index final int pointerIndex = ev.findPointerIndex(mActivePointerId); if (pointerIndex == -1) return; // Disallow scrolling if we started the gesture from outside the viewport final float x = ev.getX(pointerIndex); final float y = ev.getY(pointerIndex); if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) return; final int xDiff = (int) Math.abs(x - mLastMotionX); final int yDiff = (int) Math.abs(y - mLastMotionY); final int touchSlop = Math.round(touchSlopScale * mTouchSlop); boolean xPaged = xDiff > mPagingTouchSlop; boolean xMoved = xDiff > touchSlop; boolean yMoved = yDiff > touchSlop; if (xMoved || xPaged || yMoved) { if (mUsePagingTouchSlop ? xPaged : xMoved) { // Scroll if the user moved far enough along the X axis mTouchState = TOUCH_STATE_SCROLLING; mTotalMotionX += Math.abs(mLastMotionX - x); mLastMotionX = x; mLastMotionXRemainder = 0; mTouchX = getViewportOffsetX() + getScrollX(); mSmoothingTime = System.nanoTime() / NANOTIME_DIV; pageBeginMoving(); } } } protected float getMaxScrollProgress() { return 1.0f; } protected void cancelCurrentPageLongPress() { if (mAllowLongPress) { //mAllowLongPress = false; // Try canceling the long press. It could also have been scheduled // by a distant descendant, so use the mAllowLongPress flag to block // everything final View currentPage = getPageAt(mCurrentPage); if (currentPage != null) { currentPage.cancelLongPress(); } } } protected float getBoundedScrollProgress(int screenCenter, View v, int page) { final int halfScreenSize = getViewportWidth() / 2; screenCenter = Math.min(getScrollX() + halfScreenSize, screenCenter); screenCenter = Math.max(halfScreenSize, screenCenter); return getScrollProgress(screenCenter, v, page); } protected float getScrollProgress(int screenCenter, View v, int page) { final int halfScreenSize = getViewportWidth() / 2; int totalDistance = v.getMeasuredWidth() + mPageSpacing; int delta = screenCenter - (getScrollForPage(page) + halfScreenSize); float scrollProgress = delta / (totalDistance * 1.0f); scrollProgress = Math.min(scrollProgress, getMaxScrollProgress()); scrollProgress = Math.max(scrollProgress, - getMaxScrollProgress()); return scrollProgress; } public int getScrollForPage(int index) { if (mPageScrolls == null || index >= mPageScrolls.length || index < 0) { return 0; } else { return mPageScrolls[index]; } } // While layout transitions are occurring, a child's position may stray from its baseline // position. This method returns the magnitude of this stray at any given time. public int getLayoutTransitionOffsetForPage(int index) { if (mPageScrolls == null || index >= mPageScrolls.length || index < 0) { return 0; } else { View child = getChildAt(index); int scrollOffset = (getViewportWidth() - child.getMeasuredWidth()) / 2; int baselineX = mPageScrolls[index] + scrollOffset + getViewportOffsetX(); return (int) (child.getX() - baselineX); } } // This curve determines how the effect of scrolling over the limits of the page dimishes // as the user pulls further and further from the bounds private float overScrollInfluenceCurve(float f) { f -= 1.0f; return f * f * f + 1.0f; } protected void acceleratedOverScroll(float amount) { int screenSize = getViewportWidth(); // We want to reach the max over scroll effect when the user has // over scrolled half the size of the screen float f = OVERSCROLL_ACCELERATE_FACTOR * (amount / screenSize); if (f == 0) return; // Clamp this factor, f, to -1 < f < 1 if (Math.abs(f) >= 1) { f /= Math.abs(f); } int overScrollAmount = (int) Math.round(f * screenSize); if (amount < 0) { mOverScrollX = overScrollAmount; super.scrollTo(0, getScrollY()); } else { mOverScrollX = mMaxScrollX + overScrollAmount; super.scrollTo(mMaxScrollX, getScrollY()); } invalidate(); } protected void dampedOverScroll(float amount) { int screenSize = getViewportWidth(); float f = (amount / screenSize); if (f == 0) return; f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f))); // Clamp this factor, f, to -1 < f < 1 if (Math.abs(f) >= 1) { f /= Math.abs(f); } int overScrollAmount = (int) Math.round(OVERSCROLL_DAMP_FACTOR * f * screenSize); if (amount < 0) { mOverScrollX = overScrollAmount; super.scrollTo(0, getScrollY()); } else { mOverScrollX = mMaxScrollX + overScrollAmount; super.scrollTo(mMaxScrollX, getScrollY()); } invalidate(); } protected void overScroll(float amount) { dampedOverScroll(amount); } protected float maxOverScroll() { // Using the formula in overScroll, assuming that f = 1.0 (which it should generally not // exceed). Used to find out how much extra wallpaper we need for the over scroll effect float f = 1.0f; f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f))); return OVERSCROLL_DAMP_FACTOR * f; } protected void enableFreeScroll() { setEnableFreeScroll(true, -1); } protected void disableFreeScroll(int snapPage) { setEnableFreeScroll(false, snapPage); } void updateFreescrollBounds() { getOverviewModePages(mTempVisiblePagesRange); if (isLayoutRtl()) { mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[1]); mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[0]); } else { mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[0]); mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[1]); } } private void setEnableFreeScroll(boolean freeScroll, int snapPage) { mFreeScroll = freeScroll; if (snapPage == -1) { snapPage = getPageNearestToCenterOfScreen(); } if (!mFreeScroll) { snapToPage(snapPage); } else { updateFreescrollBounds(); getOverviewModePages(mTempVisiblePagesRange); if (getCurrentPage() < mTempVisiblePagesRange[0]) { setCurrentPage(mTempVisiblePagesRange[0]); } else if (getCurrentPage() > mTempVisiblePagesRange[1]) { setCurrentPage(mTempVisiblePagesRange[1]); } } setEnableOverscroll(!freeScroll); } private void setEnableOverscroll(boolean enable) { mAllowOverScroll = enable; } int getNearestHoverOverPageIndex() { if (mDragView != null) { int dragX = (int) (mDragView.getLeft() + (mDragView.getMeasuredWidth() / 2) + mDragView.getTranslationX()); getOverviewModePages(mTempVisiblePagesRange); int minDistance = Integer.MAX_VALUE; int minIndex = indexOfChild(mDragView); for (int i = mTempVisiblePagesRange[0]; i <= mTempVisiblePagesRange[1]; i++) { View page = getPageAt(i); int pageX = (int) (page.getLeft() + page.getMeasuredWidth() / 2); int d = Math.abs(dragX - pageX); if (d < minDistance) { minIndex = i; minDistance = d; } } return minIndex; } return -1; } @Override public boolean onTouchEvent(MotionEvent ev) { if (DISABLE_TOUCH_INTERACTION) { return false; } super.onTouchEvent(ev); // Skip touch handling if there are no pages to swipe if (getChildCount() <= 0) return super.onTouchEvent(ev); acquireVelocityTrackerAndAddMovement(ev); final int action = ev.getAction(); switch (action & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: /* * If being flinged and user touches, stop the fling. isFinished * will be false if being flinged. */ if (!mScroller.isFinished()) { mScroller.abortAnimation(); } // Remember where the motion event started mDownMotionX = mLastMotionX = ev.getX(); mDownMotionY = mLastMotionY = ev.getY(); mDownScrollX = getScrollX(); float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY); mParentDownMotionX = p[0]; mParentDownMotionY = p[1]; mLastMotionXRemainder = 0; mTotalMotionX = 0; mActivePointerId = ev.getPointerId(0); if (mTouchState == TOUCH_STATE_SCROLLING) { pageBeginMoving(); } break; case MotionEvent.ACTION_MOVE: if (mTouchState == TOUCH_STATE_SCROLLING) { // Scroll to follow the motion event final int pointerIndex = ev.findPointerIndex(mActivePointerId); if (pointerIndex == -1) return true; final float x = ev.getX(pointerIndex); final float deltaX = mLastMotionX + mLastMotionXRemainder - x; mTotalMotionX += Math.abs(deltaX); // Only scroll and update mLastMotionX if we have moved some discrete amount. We // keep the remainder because we are actually testing if we've moved from the last // scrolled position (which is discrete). if (Math.abs(deltaX) >= 1.0f) { mTouchX += deltaX; mSmoothingTime = System.nanoTime() / NANOTIME_DIV; if (!mDeferScrollUpdate) { scrollBy((int) deltaX * 2, 0); if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX); } else { invalidate(); } mLastMotionX = x; mLastMotionXRemainder = deltaX - (int) deltaX; } else { awakenScrollBars(); } } else if (mTouchState == TOUCH_STATE_REORDERING) { // Update the last motion position mLastMotionX = ev.getX(); mLastMotionY = ev.getY(); // Update the parent down so that our zoom animations take this new movement into // account float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY); mParentDownMotionX = pt[0]; mParentDownMotionY = pt[1]; updateDragViewTranslationDuringDrag(); // Find the closest page to the touch point final int dragViewIndex = indexOfChild(mDragView); // Change the drag view if we are hovering over the drop target boolean isHoveringOverDelete = isHoveringOverDeleteDropTarget( (int) mParentDownMotionX, (int) mParentDownMotionY); setPageHoveringOverDeleteDropTarget(dragViewIndex, isHoveringOverDelete); if (DEBUG) Log.d(TAG, "mLastMotionX: " + mLastMotionX); if (DEBUG) Log.d(TAG, "mLastMotionY: " + mLastMotionY); if (DEBUG) Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX); if (DEBUG) Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY); final int pageUnderPointIndex = getNearestHoverOverPageIndex(); if (pageUnderPointIndex > -1 && pageUnderPointIndex != indexOfChild(mDragView) && !isHoveringOverDelete) { mTempVisiblePagesRange[0] = 0; mTempVisiblePagesRange[1] = getPageCount() - 1; getOverviewModePages(mTempVisiblePagesRange); if (mTempVisiblePagesRange[0] <= pageUnderPointIndex && pageUnderPointIndex <= mTempVisiblePagesRange[1] && pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) { mSidePageHoverIndex = pageUnderPointIndex; mSidePageHoverRunnable = new Runnable() { @Override public void run() { // Setup the scroll to the correct page before we swap the views snapToPage(pageUnderPointIndex); // For each of the pages between the paged view and the drag view, // animate them from the previous position to the new position in // the layout (as a result of the drag view moving in the layout) int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1; int lowerIndex = (dragViewIndex < pageUnderPointIndex) ? dragViewIndex + 1 : pageUnderPointIndex; int upperIndex = (dragViewIndex > pageUnderPointIndex) ? dragViewIndex - 1 : pageUnderPointIndex; for (int i = lowerIndex; i <= upperIndex; ++i) { View v = getChildAt(i); // dragViewIndex < pageUnderPointIndex, so after we remove the // drag view all subsequent views to pageUnderPointIndex will // shift down. int oldX = getViewportOffsetX() + getChildOffset(i); int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta); // Animate the view translation from its old position to its new // position AnimatorSet anim = (AnimatorSet) v.getTag(ANIM_TAG_KEY); if (anim != null) { anim.cancel(); } v.setTranslationX(oldX - newX); anim = new AnimatorSet(); anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION); anim.playTogether( ObjectAnimator.ofFloat(v, "translationX", 0f)); anim.start(); v.setTag(anim); } removeView(mDragView); onRemoveView(mDragView, false); addView(mDragView, pageUnderPointIndex); onAddView(mDragView, pageUnderPointIndex); mSidePageHoverIndex = -1; mPageIndicator.setActiveMarker(getNextPage()); } }; postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT); } } else { removeCallbacks(mSidePageHoverRunnable); mSidePageHoverIndex = -1; } } else { determineScrollingStart(ev); } break; case MotionEvent.ACTION_UP: if (mTouchState == TOUCH_STATE_SCROLLING) { final int activePointerId = mActivePointerId; final int pointerIndex = ev.findPointerIndex(activePointerId); final float x = ev.getX(pointerIndex); final VelocityTracker velocityTracker = mVelocityTracker; velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); int velocityX = (int) velocityTracker.getXVelocity(activePointerId); final int deltaX = (int) (x - mDownMotionX); final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth(); boolean isSignificantMove = Math.abs(deltaX) > pageWidth * SIGNIFICANT_MOVE_THRESHOLD; mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x); boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING && Math.abs(velocityX) > mFlingThresholdVelocity; if (!mFreeScroll) { // In the case that the page is moved far to one direction and then is flung // in the opposite direction, we use a threshold to determine whether we should // just return to the starting page, or if we should skip one further. boolean returnToOriginalPage = false; if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD && Math.signum(velocityX) != Math.signum(deltaX) && isFling) { returnToOriginalPage = true; } int finalPage; // We give flings precedence over large moves, which is why we short-circuit our // test for a large move if a fling has been registered. That is, a large // move to the left and fling to the right will register as a fling to the right. final boolean isRtl = isLayoutRtl(); boolean isDeltaXLeft = isRtl ? deltaX > 0 : deltaX < 0; boolean isVelocityXLeft = isRtl ? velocityX > 0 : velocityX < 0; if (((isSignificantMove && !isDeltaXLeft && !isFling) || (isFling && !isVelocityXLeft)) && mCurrentPage > 0) { finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1; snapToPageWithVelocity(finalPage, velocityX); } else if (((isSignificantMove && isDeltaXLeft && !isFling) || (isFling && isVelocityXLeft)) && mCurrentPage < getChildCount() - 1) { finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1; snapToPageWithVelocity(finalPage, velocityX); } else { snapToDestination(); } } else if (mTouchState == TOUCH_STATE_PREV_PAGE) { // at this point we have not moved beyond the touch slop // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so // we can just page int nextPage = Math.max(0, mCurrentPage - 1); if (nextPage != mCurrentPage) { snapToPage(nextPage); } else { snapToDestination(); } } else { if (!mScroller.isFinished()) { mScroller.abortAnimation(); } float scaleX = getScaleX(); int vX = (int) (-velocityX * scaleX); int initialScrollX = (int) (getScrollX() * scaleX); mScroller.fling(initialScrollX, getScrollY(), vX, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0); invalidate(); } } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) { // at this point we have not moved beyond the touch slop // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so // we can just page int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1); if (nextPage != mCurrentPage) { snapToPage(nextPage); } else { snapToDestination(); } } else if (mTouchState == TOUCH_STATE_REORDERING) { // Update the last motion position mLastMotionX = ev.getX(); mLastMotionY = ev.getY(); // Update the parent down so that our zoom animations take this new movement into // account float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY); mParentDownMotionX = pt[0]; mParentDownMotionY = pt[1]; updateDragViewTranslationDuringDrag(); boolean handledFling = false; if (!DISABLE_FLING_TO_DELETE) { // Check the velocity and see if we are flinging-to-delete PointF flingToDeleteVector = isFlingingToDelete(); if (flingToDeleteVector != null) { onFlingToDelete(flingToDeleteVector); handledFling = true; } } if (!handledFling && isHoveringOverDeleteDropTarget((int) mParentDownMotionX, (int) mParentDownMotionY)) { onDropToDelete(); } } else { if (!mCancelTap) { onUnhandledTap(ev); } } // Remove the callback to wait for the side page hover timeout removeCallbacks(mSidePageHoverRunnable); // End any intermediate reordering states resetTouchState(); break; case MotionEvent.ACTION_CANCEL: if (mTouchState == TOUCH_STATE_SCROLLING) { snapToDestination(); } resetTouchState(); break; case MotionEvent.ACTION_POINTER_UP: onSecondaryPointerUp(ev); releaseVelocityTracker(); break; } return true; } public void onFlingToDelete(View v) {} public void onRemoveView(View v, boolean deletePermanently) {} public void onRemoveViewAnimationCompleted() {} public void onAddView(View v, int index) {} private void resetTouchState() { releaseVelocityTracker(); endReordering(); mCancelTap = false; mTouchState = TOUCH_STATE_REST; mActivePointerId = INVALID_POINTER; } protected void onUnhandledTap(MotionEvent ev) { ((Launcher) getContext()).onClick(this); } @Override public boolean onGenericMotionEvent(MotionEvent event) { if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { switch (event.getAction()) { case MotionEvent.ACTION_SCROLL: { // Handle mouse (or ext. device) by shifting the page depending on the scroll final float vscroll; final float hscroll; if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) { vscroll = 0; hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL); } else { vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL); hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL); } if (hscroll != 0 || vscroll != 0) { boolean isForwardScroll = isLayoutRtl() ? (hscroll < 0 || vscroll < 0) : (hscroll > 0 || vscroll > 0); if (isForwardScroll) { scrollRight(); } else { scrollLeft(); } return true; } } } } return super.onGenericMotionEvent(event); } private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) { if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(ev); } private void releaseVelocityTracker() { if (mVelocityTracker != null) { mVelocityTracker.clear(); mVelocityTracker.recycle(); mVelocityTracker = null; } } private void onSecondaryPointerUp(MotionEvent ev) { final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; final int pointerId = ev.getPointerId(pointerIndex); if (pointerId == mActivePointerId) { // This was our active pointer going up. Choose a new // active pointer and adjust accordingly. // TODO: Make this decision more intelligent. final int newPointerIndex = pointerIndex == 0 ? 1 : 0; mLastMotionX = mDownMotionX = ev.getX(newPointerIndex); mLastMotionY = ev.getY(newPointerIndex); mLastMotionXRemainder = 0; mActivePointerId = ev.getPointerId(newPointerIndex); if (mVelocityTracker != null) { mVelocityTracker.clear(); } } } @Override public void requestChildFocus(View child, View focused) { super.requestChildFocus(child, focused); int page = indexToPage(indexOfChild(child)); if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) { snapToPage(page); } } protected int getChildWidth(int index) { return getPageAt(index).getMeasuredWidth(); } int getPageNearestToPoint(float x) { int index = 0; for (int i = 0; i < getChildCount(); ++i) { if (x < getChildAt(i).getRight() - getScrollX()) { return index; } else { index++; } } return Math.min(index, getChildCount() - 1); } int getPageNearestToCenterOfScreen() { int minDistanceFromScreenCenter = Integer.MAX_VALUE; int minDistanceFromScreenCenterIndex = -1; int screenCenter = getViewportOffsetX() + getScrollX() + (getViewportWidth() / 2); final int childCount = getChildCount(); for (int i = 0; i < childCount; ++i) { View layout = (View) getPageAt(i); int childWidth = layout.getMeasuredWidth(); int halfChildWidth = (childWidth / 2); int childCenter = getViewportOffsetX() + getChildOffset(i) + halfChildWidth; int distanceFromScreenCenter = Math.abs(childCenter - screenCenter); if (distanceFromScreenCenter < minDistanceFromScreenCenter) { minDistanceFromScreenCenter = distanceFromScreenCenter; minDistanceFromScreenCenterIndex = i; } } return minDistanceFromScreenCenterIndex; } protected void snapToDestination() { snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION); } private static class ScrollInterpolator implements Interpolator { public ScrollInterpolator() { } public float getInterpolation(float t) { t -= 1.0f; return t*t*t*t*t + 1; } } // We want the duration of the page snap animation to be influenced by the distance that // the screen has to travel, however, we don't want this duration to be effected in a // purely linear fashion. Instead, we use this method to moderate the effect that the distance // of travel has on the overall snap duration. float distanceInfluenceForSnapDuration(float f) { f -= 0.5f; // center the values about 0. f *= 0.3f * Math.PI / 2.0f; return (float) Math.sin(f); } protected void snapToPageWithVelocity(int whichPage, int velocity) { whichPage = Math.max(0, Math.min(whichPage, getChildCount() - 1)); int halfScreenSize = getViewportWidth() / 2; final int newX = getScrollForPage(whichPage); int delta = newX - mUnboundedScrollX; int duration = 0; if (Math.abs(velocity) < mMinFlingVelocity) { // If the velocity is low enough, then treat this more as an automatic page advance // as opposed to an apparent physical response to flinging snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION); return; } // Here we compute a "distance" that will be used in the computation of the overall // snap duration. This is a function of the actual distance that needs to be traveled; // we keep this value close to half screen size in order to reduce the variance in snap // duration as a function of the distance the page needs to travel. float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize)); float distance = halfScreenSize + halfScreenSize * distanceInfluenceForSnapDuration(distanceRatio); velocity = Math.abs(velocity); velocity = Math.max(mMinSnapVelocity, velocity); // we want the page's snap velocity to approximately match the velocity at which the // user flings, so we scale the duration by a value near to the derivative of the scroll // interpolator at zero, ie. 5. We use 4 to make it a little slower. duration = 4 * Math.round(1000 * Math.abs(distance / velocity)); snapToPage(whichPage, delta, duration); } protected void snapToPage(int whichPage) { snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION); } protected void snapToPageImmediately(int whichPage) { snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION, true); } protected void snapToPage(int whichPage, int duration) { snapToPage(whichPage, duration, false); } protected void snapToPage(int whichPage, int duration, boolean immediate) { whichPage = Math.max(0, Math.min(whichPage, getPageCount() - 1)); int newX = getScrollForPage(whichPage); final int sX = mUnboundedScrollX; final int delta = newX - sX; snapToPage(whichPage, delta, duration, immediate); } protected void snapToPage(int whichPage, int delta, int duration) { snapToPage(whichPage, delta, duration, false); } protected void snapToPage(int whichPage, int delta, int duration, boolean immediate) { mNextPage = whichPage; View focusedChild = getFocusedChild(); if (focusedChild != null && whichPage != mCurrentPage && focusedChild == getPageAt(mCurrentPage)) { focusedChild.clearFocus(); } sendScrollAccessibilityEvent(); pageBeginMoving(); awakenScrollBars(duration); if (immediate) { duration = 0; } else if (duration == 0) { duration = Math.abs(delta); } if (!mScroller.isFinished()) { mScroller.abortAnimation(); } mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration); notifyPageSwitchListener(); // Trigger a compute() to finish switching pages if necessary if (immediate) { computeScroll(); } // Defer loading associated pages until the scroll settles mDeferLoadAssociatedPagesUntilScrollCompletes = true; mForceScreenScrolled = true; invalidate(); } public void scrollLeft() { if (getNextPage() > 0) snapToPage(getNextPage() - 1); } public void scrollRight() { if (getNextPage() < getChildCount() -1) snapToPage(getNextPage() + 1); } public int getPageForView(View v) { int result = -1; if (v != null) { ViewParent vp = v.getParent(); int count = getChildCount(); for (int i = 0; i < count; i++) { if (vp == getPageAt(i)) { return i; } } } return result; } /** * @return True is long presses are still allowed for the current touch */ public boolean allowLongPress() { return mAllowLongPress; } @Override public boolean performLongClick() { mCancelTap = true; return super.performLongClick(); } /** * Set true to allow long-press events to be triggered, usually checked by * {@link Launcher} to accept or block dpad-initiated long-presses. */ public void setAllowLongPress(boolean allowLongPress) { mAllowLongPress = allowLongPress; } public static class SavedState extends BaseSavedState { int currentPage = -1; SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); currentPage = in.readInt(); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(currentPage); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } protected void loadAssociatedPages(int page) { loadAssociatedPages(page, false); } protected void loadAssociatedPages(int page, boolean immediateAndOnly) { if (mContentIsRefreshable) { final int count = getChildCount(); if (page < count) { int lowerPageBound = getAssociatedLowerPageBound(page); int upperPageBound = getAssociatedUpperPageBound(page); if (DEBUG) Log.d(TAG, "loadAssociatedPages: " + lowerPageBound + "/" + upperPageBound); // First, clear any pages that should no longer be loaded for (int i = 0; i < count; ++i) { Page layout = (Page) getPageAt(i); if ((i < lowerPageBound) || (i > upperPageBound)) { if (layout.getPageChildCount() > 0) { layout.removeAllViewsOnPage(); } mDirtyPageContent.set(i, true); } } // Next, load any new pages for (int i = 0; i < count; ++i) { if ((i != page) && immediateAndOnly) { continue; } if (lowerPageBound <= i && i <= upperPageBound) { if (mDirtyPageContent.get(i)) { syncPageItems(i, (i == page) && immediateAndOnly); mDirtyPageContent.set(i, false); } } } } } } protected int getAssociatedLowerPageBound(int page) { return Math.max(0, page - 1); } protected int getAssociatedUpperPageBound(int page) { final int count = getChildCount(); return Math.min(page + 1, count - 1); } /** * This method is called ONLY to synchronize the number of pages that the paged view has. * To actually fill the pages with information, implement syncPageItems() below. It is * guaranteed that syncPageItems() will be called for a particular page before it is shown, * and therefore, individual page items do not need to be updated in this method. */ public abstract void syncPages(); /** * This method is called to synchronize the items that are on a particular page. If views on * the page can be reused, then they should be updated within this method. */ public abstract void syncPageItems(int page, boolean immediate); protected void invalidatePageData() { invalidatePageData(-1, false); } protected void invalidatePageData(int currentPage) { invalidatePageData(currentPage, false); } protected void invalidatePageData(int currentPage, boolean immediateAndOnly) { if (!mIsDataReady) { return; } if (mContentIsRefreshable) { // Force all scrolling-related behavior to end mScroller.forceFinished(true); mNextPage = INVALID_PAGE; // Update all the pages syncPages(); // We must force a measure after we've loaded the pages to update the content width and // to determine the full scroll width measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY)); // Set a new page as the current page if necessary if (currentPage > -1) { setCurrentPage(Math.min(getPageCount() - 1, currentPage)); } // Mark each of the pages as dirty final int count = getChildCount(); mDirtyPageContent.clear(); for (int i = 0; i < count; ++i) { mDirtyPageContent.add(true); } // Load any pages that are necessary for the current window of views loadAssociatedPages(mCurrentPage, immediateAndOnly); requestLayout(); } if (isPageMoving()) { // If the page is moving, then snap it to the final position to ensure we don't get // stuck between pages snapToDestination(); } } // Animate the drag view back to the original position void animateDragViewToOriginalPosition() { if (mDragView != null) { AnimatorSet anim = new AnimatorSet(); anim.setDuration(REORDERING_DROP_REPOSITION_DURATION); anim.playTogether( ObjectAnimator.ofFloat(mDragView, "translationX", 0f), ObjectAnimator.ofFloat(mDragView, "translationY", 0f), ObjectAnimator.ofFloat(mDragView, "scaleX", 1f), ObjectAnimator.ofFloat(mDragView, "scaleY", 1f)); anim.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { onPostReorderingAnimationCompleted(); } }); anim.start(); } } protected void onStartReordering() { // Set the touch state to reordering (allows snapping to pages, dragging a child, etc.) mTouchState = TOUCH_STATE_REORDERING; mIsReordering = true; // We must invalidate to trigger a redraw to update the layers such that the drag view // is always drawn on top invalidate(); } private void onPostReorderingAnimationCompleted() { // Trigger the callback when reordering has settled --mPostReorderingPreZoomInRemainingAnimationCount; if (mPostReorderingPreZoomInRunnable != null && mPostReorderingPreZoomInRemainingAnimationCount == 0) { mPostReorderingPreZoomInRunnable.run(); mPostReorderingPreZoomInRunnable = null; } } protected void onEndReordering() { mIsReordering = false; } public boolean startReordering(View v) { int dragViewIndex = indexOfChild(v); if (mTouchState != TOUCH_STATE_REST) return false; mTempVisiblePagesRange[0] = 0; mTempVisiblePagesRange[1] = getPageCount() - 1; getOverviewModePages(mTempVisiblePagesRange); mReorderingStarted = true; // Check if we are within the reordering range if (mTempVisiblePagesRange[0] <= dragViewIndex && dragViewIndex <= mTempVisiblePagesRange[1]) { // Find the drag view under the pointer mDragView = getChildAt(dragViewIndex); mDragView.animate().scaleX(1.15f).scaleY(1.15f).setDuration(100).start(); mDragViewBaselineLeft = mDragView.getLeft(); disableFreeScroll(-1); onStartReordering(); return true; } return false; } boolean isReordering(boolean testTouchState) { boolean state = mIsReordering; if (testTouchState) { state &= (mTouchState == TOUCH_STATE_REORDERING); } return state; } void endReordering() { // For simplicity, we call endReordering sometimes even if reordering was never started. // In that case, we don't want to do anything. if (!mReorderingStarted) return; mReorderingStarted = false; // If we haven't flung-to-delete the current child, then we just animate the drag view // back into position final Runnable onCompleteRunnable = new Runnable() { @Override public void run() { onEndReordering(); } }; if (!mDeferringForDelete) { mPostReorderingPreZoomInRunnable = new Runnable() { public void run() { onCompleteRunnable.run(); enableFreeScroll(); }; }; mPostReorderingPreZoomInRemainingAnimationCount = NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT; // Snap to the current page snapToPage(indexOfChild(mDragView), 0); // Animate the drag view back to the front position animateDragViewToOriginalPosition(); } else { // Handled in post-delete-animation-callbacks } } /* * Flinging to delete - IN PROGRESS */ private PointF isFlingingToDelete() { ViewConfiguration config = ViewConfiguration.get(getContext()); mVelocityTracker.computeCurrentVelocity(1000, config.getScaledMaximumFlingVelocity()); if (mVelocityTracker.getYVelocity() < mFlingToDeleteThresholdVelocity) { // Do a quick dot product test to ensure that we are flinging upwards PointF vel = new PointF(mVelocityTracker.getXVelocity(), mVelocityTracker.getYVelocity()); PointF upVec = new PointF(0f, -1f); float theta = (float) Math.acos(((vel.x * upVec.x) + (vel.y * upVec.y)) / (vel.length() * upVec.length())); if (theta <= Math.toRadians(FLING_TO_DELETE_MAX_FLING_DEGREES)) { return vel; } } return null; } /** * Creates an animation from the current drag view along its current velocity vector. * For this animation, the alpha runs for a fixed duration and we update the position * progressively. */ private static class FlingAlongVectorAnimatorUpdateListener implements AnimatorUpdateListener { private View mDragView; private PointF mVelocity; private Rect mFrom; private long mPrevTime; private float mFriction; private final TimeInterpolator mAlphaInterpolator = new DecelerateInterpolator(0.75f); public FlingAlongVectorAnimatorUpdateListener(View dragView, PointF vel, Rect from, long startTime, float friction) { mDragView = dragView; mVelocity = vel; mFrom = from; mPrevTime = startTime; mFriction = 1f - (mDragView.getResources().getDisplayMetrics().density * friction); } @Override public void onAnimationUpdate(ValueAnimator animation) { float t = ((Float) animation.getAnimatedValue()).floatValue(); long curTime = AnimationUtils.currentAnimationTimeMillis(); mFrom.left += (mVelocity.x * (curTime - mPrevTime) / 1000f); mFrom.top += (mVelocity.y * (curTime - mPrevTime) / 1000f); mDragView.setTranslationX(mFrom.left); mDragView.setTranslationY(mFrom.top); mDragView.setAlpha(1f - mAlphaInterpolator.getInterpolation(t)); mVelocity.x *= mFriction; mVelocity.y *= mFriction; mPrevTime = curTime; } }; private static final int ANIM_TAG_KEY = 100; private Runnable createPostDeleteAnimationRunnable(final View dragView) { return new Runnable() { @Override public void run() { int dragViewIndex = indexOfChild(dragView); // For each of the pages around the drag view, animate them from the previous // position to the new position in the layout (as a result of the drag view moving // in the layout) // NOTE: We can make an assumption here because we have side-bound pages that we // will always have pages to animate in from the left getOverviewModePages(mTempVisiblePagesRange); boolean isLastWidgetPage = (mTempVisiblePagesRange[0] == mTempVisiblePagesRange[1]); boolean slideFromLeft = (isLastWidgetPage || dragViewIndex > mTempVisiblePagesRange[0]); // Setup the scroll to the correct page before we swap the views if (slideFromLeft) { snapToPageImmediately(dragViewIndex - 1); } int firstIndex = (isLastWidgetPage ? 0 : mTempVisiblePagesRange[0]); int lastIndex = Math.min(mTempVisiblePagesRange[1], getPageCount() - 1); int lowerIndex = (slideFromLeft ? firstIndex : dragViewIndex + 1 ); int upperIndex = (slideFromLeft ? dragViewIndex - 1 : lastIndex); ArrayList<Animator> animations = new ArrayList<Animator>(); for (int i = lowerIndex; i <= upperIndex; ++i) { View v = getChildAt(i); // dragViewIndex < pageUnderPointIndex, so after we remove the // drag view all subsequent views to pageUnderPointIndex will // shift down. int oldX = 0; int newX = 0; if (slideFromLeft) { if (i == 0) { // Simulate the page being offscreen with the page spacing oldX = getViewportOffsetX() + getChildOffset(i) - getChildWidth(i) - mPageSpacing; } else { oldX = getViewportOffsetX() + getChildOffset(i - 1); } newX = getViewportOffsetX() + getChildOffset(i); } else { oldX = getChildOffset(i) - getChildOffset(i - 1); newX = 0; } // Animate the view translation from its old position to its new // position AnimatorSet anim = (AnimatorSet) v.getTag(); if (anim != null) { anim.cancel(); } // Note: Hacky, but we want to skip any optimizations to not draw completely // hidden views v.setAlpha(Math.max(v.getAlpha(), 0.01f)); v.setTranslationX(oldX - newX); anim = new AnimatorSet(); anim.playTogether( ObjectAnimator.ofFloat(v, "translationX", 0f), ObjectAnimator.ofFloat(v, "alpha", 1f)); animations.add(anim); v.setTag(ANIM_TAG_KEY, anim); } AnimatorSet slideAnimations = new AnimatorSet(); slideAnimations.playTogether(animations); slideAnimations.setDuration(DELETE_SLIDE_IN_SIDE_PAGE_DURATION); slideAnimations.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mDeferringForDelete = false; onEndReordering(); onRemoveViewAnimationCompleted(); } }); slideAnimations.start(); removeView(dragView); onRemoveView(dragView, true); } }; } public void onFlingToDelete(PointF vel) { final long startTime = AnimationUtils.currentAnimationTimeMillis(); // NOTE: Because it takes time for the first frame of animation to actually be // called and we expect the animation to be a continuation of the fling, we have // to account for the time that has elapsed since the fling finished. And since // we don't have a startDelay, we will always get call to update when we call // start() (which we want to ignore). final TimeInterpolator tInterpolator = new TimeInterpolator() { private int mCount = -1; private long mStartTime; private float mOffset; /* Anonymous inner class ctor */ { mStartTime = startTime; } @Override public float getInterpolation(float t) { if (mCount < 0) { mCount++; } else if (mCount == 0) { mOffset = Math.min(0.5f, (float) (AnimationUtils.currentAnimationTimeMillis() - mStartTime) / FLING_TO_DELETE_FADE_OUT_DURATION); mCount++; } return Math.min(1f, mOffset + t); } }; final Rect from = new Rect(); final View dragView = mDragView; from.left = (int) dragView.getTranslationX(); from.top = (int) dragView.getTranslationY(); AnimatorUpdateListener updateCb = new FlingAlongVectorAnimatorUpdateListener(dragView, vel, from, startTime, FLING_TO_DELETE_FRICTION); final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView); // Create and start the animation ValueAnimator mDropAnim = new ValueAnimator(); mDropAnim.setInterpolator(tInterpolator); mDropAnim.setDuration(FLING_TO_DELETE_FADE_OUT_DURATION); mDropAnim.setFloatValues(0f, 1f); mDropAnim.addUpdateListener(updateCb); mDropAnim.addListener(new AnimatorListenerAdapter() { public void onAnimationEnd(Animator animation) { onAnimationEndRunnable.run(); } }); mDropAnim.start(); mDeferringForDelete = true; } /* Drag to delete */ private boolean isHoveringOverDeleteDropTarget(int x, int y) { if (mDeleteDropTarget != null) { mAltTmpRect.set(0, 0, 0, 0); View parent = (View) mDeleteDropTarget.getParent(); if (parent != null) { parent.getGlobalVisibleRect(mAltTmpRect); } mDeleteDropTarget.getGlobalVisibleRect(mTmpRect); mTmpRect.offset(-mAltTmpRect.left, -mAltTmpRect.top); return mTmpRect.contains(x, y); } return false; } protected void setPageHoveringOverDeleteDropTarget(int viewIndex, boolean isHovering) {} private void onDropToDelete() { final View dragView = mDragView; final float toScale = 0f; final float toAlpha = 0f; // Create and start the complex animation ArrayList<Animator> animations = new ArrayList<Animator>(); AnimatorSet motionAnim = new AnimatorSet(); motionAnim.setInterpolator(new DecelerateInterpolator(2)); motionAnim.playTogether( ObjectAnimator.ofFloat(dragView, "scaleX", toScale), ObjectAnimator.ofFloat(dragView, "scaleY", toScale)); animations.add(motionAnim); AnimatorSet alphaAnim = new AnimatorSet(); alphaAnim.setInterpolator(new LinearInterpolator()); alphaAnim.playTogether( ObjectAnimator.ofFloat(dragView, "alpha", toAlpha)); animations.add(alphaAnim); final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView); AnimatorSet anim = new AnimatorSet(); anim.playTogether(animations); anim.setDuration(DRAG_TO_DELETE_FADE_OUT_DURATION); anim.addListener(new AnimatorListenerAdapter() { public void onAnimationEnd(Animator animation) { onAnimationEndRunnable.run(); } }); anim.start(); mDeferringForDelete = true; } /* Accessibility */ @Override public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); info.setScrollable(getPageCount() > 1); if (getCurrentPage() < getPageCount() - 1) { info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD); } if (getCurrentPage() > 0) { info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD); } } @Override public void sendAccessibilityEvent(int eventType) { // Don't let the view send real scroll events. if (eventType != AccessibilityEvent.TYPE_VIEW_SCROLLED) { super.sendAccessibilityEvent(eventType); } } @Override public void onInitializeAccessibilityEvent(AccessibilityEvent event) { super.onInitializeAccessibilityEvent(event); event.setScrollable(true); } @Override public boolean performAccessibilityAction(int action, Bundle arguments) { if (super.performAccessibilityAction(action, arguments)) { return true; } switch (action) { case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: { if (getCurrentPage() < getPageCount() - 1) { scrollRight(); return true; } } break; case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: { if (getCurrentPage() > 0) { scrollLeft(); return true; } } break; } return false; } protected String getCurrentPageDescription() { return String.format(getContext().getString(R.string.default_scroll_format), getNextPage() + 1, getChildCount()); } @Override public boolean onHoverEvent(android.view.MotionEvent event) { return true; } }
delete debug red background
app/src/main/java/com/kogitune/launcher3/PagedView.java
delete debug red background
<ide><path>pp/src/main/java/com/kogitune/launcher3/PagedView.java <ide> if (v == mDragView) continue; <ide> if (mForceDrawAllChildrenNextFrame || <ide> (leftScreen <= i && i <= rightScreen && shouldDrawChild(v))) { <del> v.setBackgroundColor(Color.argb(55,255,0,0)); <add> //v.setBackgroundColor(Color.argb(55,255,0,0)); <ide> drawChild(canvas, v, drawingTime); <ide> } <ide> }
Java
apache-2.0
d9788f5430caa5596cf85910d98d26566dffb6cb
0
cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x
/* * Copyright 2002-2004 the original author or authors. * * 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.springframework.beans.propertyeditors; import java.beans.PropertyEditorSupport; import java.io.IOException; import java.net.URL; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceEditor; /** * Editor for java.net.URL, to directly feed a URL property * instead of using a String property. * @author Juergen Hoeller * @since 15.12.2003 * @see java.net.URL */ public class URLEditor extends PropertyEditorSupport { private final ResourceEditor resourceEditor; /** * Create a new URLEditor, * using the default ResourceEditor underneath. */ public URLEditor() { this.resourceEditor = new ResourceEditor(); } /** * Create a new URLEditor, * using the given ResourceEditor underneath. * @param resourceEditor the ResourceEditor to use */ public URLEditor(ResourceEditor resourceEditor) { this.resourceEditor = resourceEditor; } public void setAsText(String text) throws IllegalArgumentException { this.resourceEditor.setAsText(text); Resource resource = (Resource) this.resourceEditor.getValue(); try { setValue(resource != null ? resource.getURL() : null); } catch (IOException ex) { throw new IllegalArgumentException( "Could not retrieve URL for " + resource + ": " + ex.getMessage()); } } public String getAsText() { if (getValue() != null) { return ((URL) getValue()).toExternalForm(); } else { return ""; } } }
src/org/springframework/beans/propertyeditors/URLEditor.java
/* * Copyright 2002-2004 the original author or authors. * * 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.springframework.beans.propertyeditors; import java.beans.PropertyEditorSupport; import java.net.MalformedURLException; import java.net.URL; /** * Editor for java.net.URL, to directly feed a URL property * instead of using a String property. * @author Juergen Hoeller * @since 15.12.2003 * @see java.net.URL */ public class URLEditor extends PropertyEditorSupport { public void setAsText(String text) throws IllegalArgumentException { try { setValue(new URL(text)); } catch (MalformedURLException ex) { throw new IllegalArgumentException("Malformed URL: " + ex.getMessage()); } } public String getAsText() { return ((URL) getValue()).toExternalForm(); } }
delegate to ResourceEditor git-svn-id: b619a0c99665f88f1afe72824344cefe9a1c8c90@4025 fd5a2b45-1f63-4059-99e9-3c7cb7fd75c8
src/org/springframework/beans/propertyeditors/URLEditor.java
delegate to ResourceEditor
<ide><path>rc/org/springframework/beans/propertyeditors/URLEditor.java <ide> package org.springframework.beans.propertyeditors; <ide> <ide> import java.beans.PropertyEditorSupport; <del>import java.net.MalformedURLException; <add>import java.io.IOException; <ide> import java.net.URL; <add> <add>import org.springframework.core.io.Resource; <add>import org.springframework.core.io.ResourceEditor; <ide> <ide> /** <ide> * Editor for java.net.URL, to directly feed a URL property <ide> */ <ide> public class URLEditor extends PropertyEditorSupport { <ide> <add> private final ResourceEditor resourceEditor; <add> <add> /** <add> * Create a new URLEditor, <add> * using the default ResourceEditor underneath. <add> */ <add> public URLEditor() { <add> this.resourceEditor = new ResourceEditor(); <add> } <add> <add> /** <add> * Create a new URLEditor, <add> * using the given ResourceEditor underneath. <add> * @param resourceEditor the ResourceEditor to use <add> */ <add> public URLEditor(ResourceEditor resourceEditor) { <add> this.resourceEditor = resourceEditor; <add> } <add> <ide> public void setAsText(String text) throws IllegalArgumentException { <add> this.resourceEditor.setAsText(text); <add> Resource resource = (Resource) this.resourceEditor.getValue(); <ide> try { <del> setValue(new URL(text)); <add> setValue(resource != null ? resource.getURL() : null); <ide> } <del> catch (MalformedURLException ex) { <del> throw new IllegalArgumentException("Malformed URL: " + ex.getMessage()); <add> catch (IOException ex) { <add> throw new IllegalArgumentException( <add> "Could not retrieve URL for " + resource + ": " + ex.getMessage()); <ide> } <ide> } <ide> <ide> public String getAsText() { <del> return ((URL) getValue()).toExternalForm(); <add> if (getValue() != null) { <add> return ((URL) getValue()).toExternalForm(); <add> } <add> else { <add> return ""; <add> } <ide> } <ide> <ide> }
Java
lgpl-2.1
ba98ef45c97ec0be2ab06953292d8c1b917db0cc
0
csrg-utfsm/acscb,csrg-utfsm/acscb,ACS-Community/ACS,csrg-utfsm/acscb,ACS-Community/ACS,ACS-Community/ACS,csrg-utfsm/acscb,csrg-utfsm/acscb,ACS-Community/ACS,ACS-Community/ACS,ACS-Community/ACS,csrg-utfsm/acscb,csrg-utfsm/acscb,ACS-Community/ACS,ACS-Community/ACS,csrg-utfsm/acscb
package alma.acs.container.corba; import java.util.logging.Level; import alma.acs.component.ComponentQueryDescriptor; import alma.acs.component.client.ComponentClientTestCase; import alma.jconttest.DummyComponent; import alma.jconttest.DummyComponentHelper; /** * Tests {@link alma.acs.container.corba.AcsCorba} and related usage of ORB and POAs. * Requires ACS runtime with a remote container. * * @author hsommer * @see alma.acs.container.corba.AcsCorbaTest */ public class AcsCorbaTestWithContainer extends ComponentClientTestCase { private static final String DUMMYCOMP_TYPENAME = "IDL:alma/jconttest/DummyComponent:1.0"; private DummyComponent dummyComponent; // simple otherthread-to-mainthread exception passing private volatile Throwable exceptionInThread; public AcsCorbaTestWithContainer() throws Exception { super("AcsCorbaTestWithContainer"); } protected void setUp() throws Exception { Thread.sleep(2000); // to make sure that logging client is up and captures all logs super.setUp(); } protected void tearDown() throws Exception { m_logger.info("done, tearDown"); super.tearDown(); } public void testParallelCalls() throws Exception { org.omg.CORBA.Object compObj = getContainerServices().getDynamicComponent(new ComponentQueryDescriptor(null, DUMMYCOMP_TYPENAME), false); assertNotNull(compObj); dummyComponent = DummyComponentHelper.narrow(compObj); String compName = dummyComponent.name(); assertNotNull(compName); exceptionInThread = null; // run a call to 'callThatTakesSomeTime' from a client thread Runnable compMethodCallRunnable = new Runnable() { public void run() { try { dummyComponent.callThatTakesSomeTime(2000); } catch (Exception ex) { m_logger.log(Level.SEVERE, "Async client call 'dummyComponent#callThatTakesSomeTime' failed with exception.", ex); exceptionInThread = ex; } } }; (new Thread(compMethodCallRunnable)).start(); // now run another call from the main thread Thread.sleep(500); // just to make sure the first call is out compMethodCallRunnable.run(); // some other parallel call that uses ContainerServices getContainerServices().getDynamicComponent(new ComponentQueryDescriptor(null, DUMMYCOMP_TYPENAME), false); assertNull("got an exception in the first of two calls", exceptionInThread); } /** * Activates / deactivates a component 10 times, each time calling a method that still runs while * its POA is getting deactivated. The purpose is to check the container's ability to wait for currently * processing requests to terminate, before <code>cleanUp</code> is called on the component. * <p> * TODO: extend this scenario so that another collocated component issues the long lasting call. * This may not work due to a JacORB bug, which we should find out about. */ public void testComponentPOALifecycleAsync() throws Exception { _testComponentPOALifecycle(true, 10); } /** * @param destroyWhileBusy * @param iterations * @throws Exception */ private void _testComponentPOALifecycle(boolean destroyWhileBusy, int iterations) throws Exception { // times in milliseconds final int remoteCallDurationMin = (destroyWhileBusy ? 2000 : 0); final int callOverheadMax = 600; for (int i=0; i < iterations; i++) { m_logger.info("Will create, use and destroy component instance #" + i); org.omg.CORBA.Object compObj = getContainerServices().getDynamicComponent( new ComponentQueryDescriptor(null, DUMMYCOMP_TYPENAME), false); assertNotNull(compObj); dummyComponent = DummyComponentHelper.narrow(compObj); String compName = dummyComponent.name(); assertNotNull(compName); exceptionInThread = null; // make CORBA calls to the component, and have it destroyed dummyComponent.dummyComponentsCanDoCloseToNothing(); if (destroyWhileBusy) { Runnable compMethodCallRunnable = new Runnable() { public void run() { try { dummyComponent.callThatTakesSomeTime(remoteCallDurationMin); } catch (Exception ex) { m_logger.log(Level.SEVERE, "Async client call 'dummyComponent#callThatTakesSomeTime' failed with exception.", ex); exceptionInThread = ex; } } }; m_logger.info("Will release component while active request is still running."); (new Thread(compMethodCallRunnable)).start(); // Sleep a bit so that we are sure the component method 'callThatTakesSomeTime' is executing (=sleeping). // TODO: use proper synchronization to wait until dymmyComponent has received the call to 'callThatTakesSomeTime' // this could be done using ACS callbacks. Thread.sleep(callOverheadMax); } else { dummyComponent.callThatTakesSomeTime(remoteCallDurationMin); } // we expect the releaseComponent call to take some time, because the container must wait for the // currently active call to finish before the component can be unloaded. // Without any call and container overhead, the component is busy already for as long as we slept (=callOverheadMax). // In that case we should measure timeReleaseCompCall == remoteCallDurationMin-callOverheadMax. // Any overhead in the 'callThatTakesSomeTime' and the return of 'releaseComponent' only increases the measured timeReleaseCompCall. // When running the test, we still see occasional failures of returning a few milliseconds too early. // 2012-06-13: Assuming that these errors come from granularity issues with the timer and that measuring nanoseconds // will improve this situation, we change from System.currentTimeMillis diffs to using System.nanoTime(). long timeBeforeRelease = System.nanoTime(); getContainerServices().releaseComponent(compName); int timeReleaseCompCallMillis = (int) ((System.nanoTime() - timeBeforeRelease) / 1000000); int timeReleaseCompCallMillisExpectedMin = remoteCallDurationMin - callOverheadMax; int timeReleaseCompCallMillisExpectedMax = timeReleaseCompCallMillisExpectedMin + 2 * callOverheadMax; if (destroyWhileBusy) { assertTrue("Releasing component '" + compName + "' took " + timeReleaseCompCallMillis + " ms, when between " + timeReleaseCompCallMillisExpectedMin + " ms and " + timeReleaseCompCallMillisExpectedMax + " were expected.", timeReleaseCompCallMillis >= remoteCallDurationMin-callOverheadMax && timeReleaseCompCallMillis <= timeReleaseCompCallMillisExpectedMax); } if (exceptionInThread != null) { fail("asynchronous component call number " + i + " (callThatTakesSomeTime) failed: " + exceptionInThread.toString()); } } } }
LGPL/CommonSoftware/jcont/test/alma/acs/container/corba/AcsCorbaTestWithContainer.java
package alma.acs.container.corba; import java.util.logging.Level; import alma.acs.component.ComponentQueryDescriptor; import alma.acs.component.client.ComponentClientTestCase; import alma.jconttest.DummyComponentImpl.DummyComponentHelper; /** * Tests {@link alma.acs.container.corba.AcsCorba} and related usage of ORB and POAs. * Requires ACS runtime with a remote container. * * @author hsommer * @see alma.acs.container.corba.AcsCorbaTest */ public class AcsCorbaTestWithContainer extends ComponentClientTestCase { private static final String DUMMYCOMP_TYPENAME = "IDL:alma/jconttest/DummyComponent:1.0"; private DummyComponent dummyComponent; // simple otherthread-to-mainthread exception passing private volatile Throwable exceptionInThread; public AcsCorbaTestWithContainer() throws Exception { super("AcsCorbaTestWithContainer"); } protected void setUp() throws Exception { Thread.sleep(2000); // to make sure that logging client is up and captures all logs super.setUp(); } protected void tearDown() throws Exception { m_logger.info("done, tearDown"); super.tearDown(); } public void testParallelCalls() throws Exception { org.omg.CORBA.Object compObj = getContainerServices().getDynamicComponent(new ComponentQueryDescriptor(null, DUMMYCOMP_TYPENAME), false); assertNotNull(compObj); dummyComponent = DummyComponentHelper.narrow(compObj); String compName = dummyComponent.name(); assertNotNull(compName); exceptionInThread = null; // run a call to 'callThatTakesSomeTime' from a client thread Runnable compMethodCallRunnable = new Runnable() { public void run() { try { dummyComponent.callThatTakesSomeTime(2000); } catch (Exception ex) { m_logger.log(Level.SEVERE, "Async client call 'dummyComponent#callThatTakesSomeTime' failed with exception.", ex); exceptionInThread = ex; } } }; (new Thread(compMethodCallRunnable)).start(); // now run another call from the main thread Thread.sleep(500); // just to make sure the first call is out compMethodCallRunnable.run(); // some other parallel call that uses ContainerServices getContainerServices().getDynamicComponent(new ComponentQueryDescriptor(null, DUMMYCOMP_TYPENAME), false); assertNull("got an exception in the first of two calls", exceptionInThread); } /** * Activates / deactivates a component 10 times, each time calling a method that still runs while * its POA is getting deactivated. The purpose is to check the container's ability to wait for currently * processing requests to terminate, before <code>cleanUp</code> is called on the component. * <p> * TODO: extend this scenario so that another collocated component issues the long lasting call. * This may not work due to a JacORB bug, which we should find out about. */ public void testComponentPOALifecycleAsync() throws Exception { _testComponentPOALifecycle(true, 10); } /** * @param destroyWhileBusy * @param iterations * @throws Exception */ private void _testComponentPOALifecycle(boolean destroyWhileBusy, int iterations) throws Exception { // times in milliseconds final int remoteCallDurationMin = (destroyWhileBusy ? 2000 : 0); final int callOverheadMax = 600; for (int i=0; i < iterations; i++) { m_logger.info("Will create, use and destroy component instance #" + i); org.omg.CORBA.Object compObj = getContainerServices().getDynamicComponent( new ComponentQueryDescriptor(null, DUMMYCOMP_TYPENAME), false); assertNotNull(compObj); dummyComponent = DummyComponentHelper.narrow(compObj); String compName = dummyComponent.name(); assertNotNull(compName); exceptionInThread = null; // make CORBA calls to the component, and have it destroyed dummyComponent.dummyComponentsCanDoCloseToNothing(); if (destroyWhileBusy) { Runnable compMethodCallRunnable = new Runnable() { public void run() { try { dummyComponent.callThatTakesSomeTime(remoteCallDurationMin); } catch (Exception ex) { m_logger.log(Level.SEVERE, "Async client call 'dummyComponent#callThatTakesSomeTime' failed with exception.", ex); exceptionInThread = ex; } } }; m_logger.info("Will release component while active request is still running."); (new Thread(compMethodCallRunnable)).start(); // Sleep a bit so that we are sure the component method 'callThatTakesSomeTime' is executing (=sleeping). // TODO: use proper synchronization to wait until dymmyComponent has received the call to 'callThatTakesSomeTime' // this could be done using ACS callbacks. Thread.sleep(callOverheadMax); } else { dummyComponent.callThatTakesSomeTime(remoteCallDurationMin); } // we expect the releaseComponent call to take some time, because the container must wait for the // currently active call to finish before the component can be unloaded. // Without any call and container overhead, the component is busy already for as long as we slept (=callOverheadMax). // In that case we should measure timeReleaseCompCall == remoteCallDurationMin-callOverheadMax. // Any overhead in the 'callThatTakesSomeTime' and the return of 'releaseComponent' only increases the measured timeReleaseCompCall. // When running the test, we still see occasional failures of returning a few milliseconds too early. // 2012-06-13: Assuming that these errors come from granularity issues with the timer and that measuring nanoseconds // will improve this situation, we change from System.currentTimeMillis diffs to using System.nanoTime(). long timeBeforeRelease = System.nanoTime(); getContainerServices().releaseComponent(compName); int timeReleaseCompCallMillis = (int) ((System.nanoTime() - timeBeforeRelease) / 1000000); int timeReleaseCompCallMillisExpectedMin = remoteCallDurationMin - callOverheadMax; int timeReleaseCompCallMillisExpectedMax = timeReleaseCompCallMillisExpectedMin + 2 * callOverheadMax; if (destroyWhileBusy) { assertTrue("Releasing component '" + compName + "' took " + timeReleaseCompCallMillis + " ms, when between " + timeReleaseCompCallMillisExpectedMin + " ms and " + timeReleaseCompCallMillisExpectedMax + " were expected.", timeReleaseCompCallMillis >= remoteCallDurationMin-callOverheadMax && timeReleaseCompCallMillis <= timeReleaseCompCallMillisExpectedMax); } if (exceptionInThread != null) { fail("asynchronous component call number " + i + " (callThatTakesSomeTime) failed: " + exceptionInThread.toString()); } } } }
Imports fixed git-svn-id: 4f15cd35116e72df6ba252f213c0d8a6c7d4ad11@223515 523d945c-050c-4681-91ec-863ad3bb968a
LGPL/CommonSoftware/jcont/test/alma/acs/container/corba/AcsCorbaTestWithContainer.java
Imports fixed
<ide><path>GPL/CommonSoftware/jcont/test/alma/acs/container/corba/AcsCorbaTestWithContainer.java <ide> <ide> import alma.acs.component.ComponentQueryDescriptor; <ide> import alma.acs.component.client.ComponentClientTestCase; <del>import alma.jconttest.DummyComponentImpl.DummyComponentHelper; <add>import alma.jconttest.DummyComponent; <add>import alma.jconttest.DummyComponentHelper; <ide> <ide> /** <ide> * Tests {@link alma.acs.container.corba.AcsCorba} and related usage of ORB and POAs.
Java
mit
fd20c42d9dd12cf4b492cd8b065354ccf3c335ce
0
gcauchis/ta4j,mdeverdelhan/ta4j
/** * The MIT License (MIT) * * Copyright (c) 2014-2017 Marc de Verdelhan & respective authors (see AUTHORS) * * 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. */ package eu.verdelhan.ta4j.indicators; import eu.verdelhan.ta4j.Indicator; import eu.verdelhan.ta4j.TimeSeries; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Cached {@link Indicator indicator}. * <p> * Caches the constructor of the indicator. Avoid to calculate the same index of the indicator twice. */ public abstract class CachedIndicator<T> extends AbstractIndicator<T> { /** List of cached results */ private final List<T> results = new ArrayList<T>(); /** * Should always be the index of the last result in the results list. * I.E. the last calculated result. */ protected int highestResultIndex = -1; /** * Constructor. * @param series the related time series */ public CachedIndicator(TimeSeries series) { super(series); } /** * Constructor. * @param indicator a related indicator (with a time series) */ public CachedIndicator(Indicator indicator) { this(indicator.getTimeSeries()); } @Override public T getValue(int index) { TimeSeries series = getTimeSeries(); if (series == null) { // Series is null; the indicator doesn't need cache. // (e.g. simple computation of the value) // --> Calculating the value return calculate(index); } // Series is not null final int removedTicksCount = series.getRemovedTicksCount(); final int maximumResultCount = series.getMaximumTickCount(); T result; if (index < removedTicksCount) { // Result already removed from cache log.trace("{}: result from tick {} already removed from cache, use {}-th instead", getClass().getSimpleName(), index, removedTicksCount); increaseLengthTo(removedTicksCount, maximumResultCount); highestResultIndex = removedTicksCount; result = results.get(0); if (result == null) { result = calculate(removedTicksCount); results.set(0, result); } } else { increaseLengthTo(index, maximumResultCount); if (index > highestResultIndex) { // Result not calculated yet highestResultIndex = index; result = calculate(index); results.set(results.size()-1, result); } else { // Result covered by current cache int resultInnerIndex = results.size() - 1 - (highestResultIndex - index); result = results.get(resultInnerIndex); if (result == null) { result = calculate(index); } results.set(resultInnerIndex, result); } } return result; } /** * @param index the tick index * @return the value of the indicator */ protected abstract T calculate(int index); /** * Increases the size of cached results buffer. * @param index the index to increase length to * @param maxLength the maximum length of the results buffer */ private void increaseLengthTo(int index, int maxLength) { if (highestResultIndex > -1) { int newResultsCount = Math.min(index-highestResultIndex, maxLength); if (newResultsCount == maxLength) { results.clear(); results.addAll(Collections.<T> nCopies(maxLength, null)); } else if (newResultsCount > 0) { results.addAll(Collections.<T> nCopies(newResultsCount, null)); removeExceedingResults(maxLength); } } else { // First use of cache assert results.isEmpty() : "Cache results list should be empty"; results.addAll(Collections.<T> nCopies(Math.min(index+1, maxLength), null)); } } /** * Removes the N first results which exceed the maximum tick count. * (i.e. keeps only the last maximumResultCount results) * @param maximumResultCount the number of results to keep */ private void removeExceedingResults(int maximumResultCount) { int resultCount = results.size(); if (resultCount > maximumResultCount) { // Removing old results final int nbResultsToRemove = resultCount - maximumResultCount; for (int i = 0; i < nbResultsToRemove; i++) { results.remove(0); } } } }
ta4j/src/main/java/eu/verdelhan/ta4j/indicators/CachedIndicator.java
/** * The MIT License (MIT) * * Copyright (c) 2014-2017 Marc de Verdelhan & respective authors (see AUTHORS) * * 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. */ package eu.verdelhan.ta4j.indicators; import eu.verdelhan.ta4j.Indicator; import eu.verdelhan.ta4j.TimeSeries; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Cached {@link Indicator indicator}. * <p> * Caches the constructor of the indicator. Avoid to calculate the same index of the indicator twice. */ public abstract class CachedIndicator<T> extends AbstractIndicator<T> { /** List of cached results */ private final List<T> results = new ArrayList<T>(); /** * Should always be the index of the last result in the results list. * I.E. the last calculated result. */ protected int highestResultIndex = -1; /** * Constructor. * @param series the related time series */ public CachedIndicator(TimeSeries series) { super(series); } /** * Constructor. * @param indicator a related indicator (with a time series) */ public CachedIndicator(Indicator indicator) { this(indicator.getTimeSeries()); } @Override public T getValue(int index) { TimeSeries series = getTimeSeries(); if (series == null) { // Series is null; the indicator doesn't need cache. // (e.g. simple computation of the value) // --> Calculating the value return calculate(index); } // Series is not null final int removedTicksCount = series.getRemovedTicksCount(); final int maximumResultCount = getTimeSeries().getMaximumTickCount(); T result; if (index < removedTicksCount) { // Result already removed from cache log.trace("{}: result from tick {} already removed from cache, use {}-th instead", getClass().getSimpleName(), index, removedTicksCount); increaseLengthTo(removedTicksCount, maximumResultCount); highestResultIndex = removedTicksCount; result = results.get(0); if (result == null) { result = calculate(removedTicksCount); results.set(0, result); } } else { increaseLengthTo(index, maximumResultCount); if (index > highestResultIndex) { // Result not calculated yet highestResultIndex = index; result = calculate(index); results.set(results.size()-1, result); } else { // Result covered by current cache int resultInnerIndex = results.size() - 1 - (highestResultIndex - index); result = results.get(resultInnerIndex); if (result == null) { result = calculate(index); } results.set(resultInnerIndex, result); } } return result; } /** * @param index the tick index * @return the value of the indicator */ protected abstract T calculate(int index); /** * Increases the size of cached results buffer. * @param index the index to increase length to * @param maxLength the maximum length of the results buffer */ private void increaseLengthTo(int index, int maxLength) { if (highestResultIndex > -1) { int newResultsCount = Math.min(index-highestResultIndex, maxLength); if (newResultsCount == maxLength) { results.clear(); results.addAll(Collections.<T> nCopies(maxLength, null)); } else if (newResultsCount > 0) { results.addAll(Collections.<T> nCopies(newResultsCount, null)); removeExceedingResults(maxLength); } } else { // First use of cache assert results.isEmpty() : "Cache results list should be empty"; results.addAll(Collections.<T> nCopies(Math.min(index+1, maxLength), null)); } } /** * Removes the N first results which exceed the maximum tick count. * (i.e. keeps only the last maximumResultCount results) * @param maximumResultCount the number of results to keep */ private void removeExceedingResults(int maximumResultCount) { int resultCount = results.size(); if (resultCount > maximumResultCount) { // Removing old results final int nbResultsToRemove = resultCount - maximumResultCount; for (int i = 0; i < nbResultsToRemove; i++) { results.remove(0); } } } }
Small fix
ta4j/src/main/java/eu/verdelhan/ta4j/indicators/CachedIndicator.java
Small fix
<ide><path>a4j/src/main/java/eu/verdelhan/ta4j/indicators/CachedIndicator.java <ide> // Series is not null <ide> <ide> final int removedTicksCount = series.getRemovedTicksCount(); <del> final int maximumResultCount = getTimeSeries().getMaximumTickCount(); <add> final int maximumResultCount = series.getMaximumTickCount(); <ide> <ide> T result; <ide> if (index < removedTicksCount) {
Java
apache-2.0
56155a9771b7feccf205344cea6b8f3c46bcb119
0
Shrralis/chnu_java_labs
package com.shrralis.lab4; import com.shrralis.lab4.base.WorkerAbstract; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; @SuppressWarnings("unchecked") public class Test { public static void main(String[] args) throws IOException { ArrayList<WorkerAbstract> workers = new ArrayList<>(); workers.add(new Rater(3000, 32)); workers.add(new Hourler(30, 100)); File file = new File("workers.txt"); if (!file.exists()) { if (!file.createNewFile()) { System.err.println("Error with creating file!"); System.err.println("Exiting..."); return; } } FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); JSONArray array = new JSONArray(); for (WorkerAbstract w : workers) { JSONObject o = w.getJson(); o.put("id", workers.indexOf(w)); array.add(o); } System.out.println(array.toJSONString()); bw.write(array.toJSONString()); bw.close(); fw.close(); } }
Lab4/src/com/shrralis/lab4/Test.java
package com.shrralis.lab4; import com.shrralis.lab4.base.WorkerAbstract; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; @SuppressWarnings("unchecked") public class Test { public static void main(String[] args) throws IOException { ArrayList<WorkerAbstract> workers = new ArrayList<>(); workers.add(new Rater(3000, 32)); workers.add(new Hourler(30, 100)); File file = new File("workers.txt"); if (!file.exists()) { if (!file.createNewFile()) { System.err.println("Error with creating file!"); System.err.println("Exiting..."); return; } } FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); JSONArray array = new JSONArray(); for (WorkerAbstract w : workers) { JSONObject o = w.getJson(); o.put("id", workers.indexOf(w)); array.add(o); } System.out.println(array.toJSONString()); bw.write(array.toJSONString()); bw.close(); fw.close(); } }
Removed unnecessary empty line.
Lab4/src/com/shrralis/lab4/Test.java
Removed unnecessary empty line.
<ide><path>ab4/src/com/shrralis/lab4/Test.java <ide> array.add(o); <ide> } <ide> System.out.println(array.toJSONString()); <del> <ide> bw.write(array.toJSONString()); <ide> bw.close(); <ide> fw.close();
Java
bsd-3-clause
9e444543d1fc789bde6b9047328be77b23ca3e92
0
NCIP/caaers,CBIIT/caaers,NCIP/caaers,CBIIT/caaers,NCIP/caaers,CBIIT/caaers,CBIIT/caaers,CBIIT/caaers,NCIP/caaers
package gov.nih.nci.cabig.caaers.web.ae; import gov.nih.nci.cabig.caaers.dao.AdverseEventReportingPeriodDao; import gov.nih.nci.cabig.caaers.dao.StudyDao; import gov.nih.nci.cabig.caaers.dao.StudyParticipantAssignmentDao; import gov.nih.nci.cabig.caaers.dao.report.ReportDefinitionDao; import gov.nih.nci.cabig.caaers.domain.AdverseEvent; import gov.nih.nci.cabig.caaers.domain.AdverseEventReportingPeriod; import gov.nih.nci.cabig.caaers.domain.Ctc; import gov.nih.nci.cabig.caaers.domain.CtcCategory; import gov.nih.nci.cabig.caaers.domain.ExpeditedAdverseEventReport; import gov.nih.nci.cabig.caaers.domain.Grade; import gov.nih.nci.cabig.caaers.domain.Hospitalization; import gov.nih.nci.cabig.caaers.domain.LabLoad; import gov.nih.nci.cabig.caaers.domain.Outcome; import gov.nih.nci.cabig.caaers.domain.OutcomeType; import gov.nih.nci.cabig.caaers.domain.Participant; import gov.nih.nci.cabig.caaers.domain.Study; import gov.nih.nci.cabig.caaers.domain.StudyParticipantAssignment; import gov.nih.nci.cabig.caaers.domain.Term; import gov.nih.nci.cabig.caaers.domain.report.Report; import gov.nih.nci.cabig.caaers.domain.report.ReportDefinition; import gov.nih.nci.cabig.caaers.domain.workflow.ReportingPeriodReviewComment; import gov.nih.nci.cabig.caaers.service.EvaluationService; import gov.nih.nci.cabig.caaers.tools.configuration.Configuration; import gov.nih.nci.cabig.caaers.utils.IndexFixedList; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import javax.persistence.Transient; public class CaptureAdverseEventInputCommand implements AdverseEventInputCommand { private StudyParticipantAssignment assignment; private StudyParticipantAssignmentDao assignmentDao; private ReportDefinitionDao reportDefinitionDao; private Participant participant; private Study study; private EvaluationService evaluationService; protected AdverseEventReportingPeriod adverseEventReportingPeriod; protected AdverseEventReportingPeriodDao adverseEventReportingPeriodDao; private StudyDao studyDao; private List<CtcCategory> ctcCategories; private Integer primaryAdverseEventId; private IndexFixedList<AdverseEvent> adverseEvents; // Added for Post processing in Confirmation page private List<ReportDefinition> allReportDefinitions; private Map<ReportDefinition, List<AdverseEvent>> requiredReportDefinitionsMap; private Map<Integer, String> reportStatusMap; private Map<Integer, Boolean> requiredReportDefinitionIndicatorMap; private Map<Integer, Boolean> reportDefinitionMap;//will store user selection //this map is used for internal purpouses private Map<Integer, ReportDefinition> reportDefinitionIndexMap; private Map<Integer, Boolean> selectedAesMap; private Ctc ctcVersion; private Set<AdverseEvent> seriousAdverseEvents; private boolean workflowEnabled = false; public CaptureAdverseEventInputCommand(){ } public CaptureAdverseEventInputCommand(AdverseEventReportingPeriodDao adverseEventReportingPeriodDao, StudyParticipantAssignmentDao assignmentDao, EvaluationService evaluationService, ReportDefinitionDao reportDefinitionDao, StudyDao studyDao){ this.adverseEventReportingPeriodDao = adverseEventReportingPeriodDao; this.assignmentDao = assignmentDao; this.evaluationService = evaluationService; this.reportDefinitionDao = reportDefinitionDao; this.studyDao = studyDao; this.selectedAesMap = new HashMap<Integer, Boolean>(); this.allReportDefinitions = new ArrayList<ReportDefinition>(); this.requiredReportDefinitionsMap = new HashMap<ReportDefinition, List<AdverseEvent>>(); this.reportStatusMap = new HashMap<Integer, String>(); this.requiredReportDefinitionIndicatorMap = new HashMap<Integer, Boolean>(); this.reportDefinitionMap = new HashMap<Integer, Boolean>(); this.reportDefinitionIndexMap = new HashMap<Integer, ReportDefinition>(); this.seriousAdverseEvents = new TreeSet<AdverseEvent>(new Comparator<AdverseEvent>(){ public int compare(AdverseEvent o1, AdverseEvent o2) { if(o1 == null && o2 == null) return 0; if(o1 == null || o1.getGrade() == null) return 1; if(o2 == null || o2.getGrade() == null) return -1; if(o1.getGrade().getCode() > o2.getGrade().getCode()) return -1; if(o1.getGrade().getCode() < o2.getGrade().getCode()) return 1; return 0; } }); } /** * This method will check if the study selected is a DCP sponsored study and is AdEERS submittable. * @return */ public boolean isDCPNonAdeersStudy(){ if(study == null) return false; return (!study.getAdeersReporting()) && study.getPrimaryFundingSponsorOrganization().getNciInstituteCode().equals("DCP"); } public void save() { // AdverseEventReportingPeriod mergedReportingPeriod; // // if(this.getAdverseEventReportingPeriod() != null){ // mergedReportingPeriod = adverseEventReportingPeriodDao.merge(this.getAdverseEventReportingPeriod()); // this.setAdverseEventReportingPeriod(mergedReportingPeriod); // } if(this.getAdverseEventReportingPeriod() != null) adverseEventReportingPeriodDao.save(this.getAdverseEventReportingPeriod()); } public void reassociate(){ //reassociate all report definitions if(allReportDefinitions != null) for(ReportDefinition repDef : allReportDefinitions){ reportDefinitionDao.reassociate(repDef); } studyDao.lock(study); if(this.adverseEventReportingPeriod != null && this.adverseEventReportingPeriod.getId() != null){ adverseEventReportingPeriodDao.reassociate(this.adverseEventReportingPeriod); } } /** * This method will refresh the StudyParticipantAssignment and updates the {@link AdverseEventReportingPeriod}. */ public void refreshAssignment(Integer reportingPeriodId){ //reload assignmet assignmentDao.refresh(getAssignment()); refreshReportingPeriod(reportingPeriodId); } public void refreshReportingPeriod(Integer reportingPeriodId){ studyDao.lock(study); assignmentDao.reassociate(getAssignment()); //reset the adverse event report in the command setAdverseEventReportingPeriod(null); for(AdverseEventReportingPeriod reportingPeriod : assignment.getReportingPeriods()){ if(reportingPeriod.getId().equals(reportingPeriodId)){ setAdverseEventReportingPeriod(reportingPeriod); break; } } } public void clearSession(){ assignmentDao.clearSession(); } public void evictUnwantedObjects(){ assignmentDao.evict(getAssignment()); } /** * This method will take care of initializing the lazy associations * This method will take care of * - Updating the index fixed list for AdverseEvents, associated to the reporting period * - initializing the lazy associations */ public void initialize(){ //set the assignment into the command. if(this.adverseEventReportingPeriod != null) this.assignment = this.adverseEventReportingPeriod.getAssignment(); adverseEvents = new IndexFixedList<AdverseEvent>(new ArrayList<AdverseEvent>()); if(adverseEventReportingPeriod != null){ adverseEvents = new IndexFixedList<AdverseEvent>(adverseEventReportingPeriod.getAdverseEvents()); Study study = adverseEventReportingPeriod.getStudy(); if(study.getStudyOrganizations() != null) study.getStudyOrganizations().size(); if(study.getExpectedAECtcTerms() != null) study.getExpectedAECtcTerms().size(); boolean isCTCStudy = study.getAeTerminology().getTerm() == Term.CTC; if(isCTCStudy){ for(AdverseEvent ae : getAdverseEvents()){ ae.getAdverseEventTerm().isOtherRequired(); ae.getAdverseEventCtcTerm().getCtcTerm().isOtherRequired(); ae.getAdverseEventCtcTerm().getCtcTerm().getContextualGrades(); } } this.adverseEventReportingPeriod.getAdverseEvents().size(); this.adverseEventReportingPeriod.getAeReports(); for(ExpeditedAdverseEventReport aeReport : this.adverseEventReportingPeriod.getAeReports()){ aeReport.getAllSponsorReportsCompleted(); aeReport.getHasAmendableReport(); aeReport.getHasSubmittedReport(); aeReport.getNumberOfAes(); for(Report report : aeReport.getReports()){ report.getLastVersion().getVersion(); } } List<ReportingPeriodReviewComment> reviewCommentList = this.adverseEventReportingPeriod.getReviewComments(); if(reviewCommentList != null) this.adverseEventReportingPeriod.getReviewComments().size(); if(this.assignment != null) this.assignment.getParticipant().getIdentifiers(); } } // public void initializeObjectsInCommand(){ // if(study == null) return; // if(study.getExpectedAECtcTerms() != null) study.getExpectedAECtcTerms().size(); // boolean isCTCStudy = study.getAeTerminology().getTerm() == Term.CTC; // if (isCTCStudy){ // List<AdverseEvent> aes = getAdverseEvents(); // if(aes != null){ // for (AdverseEvent ae: aes) { // // } // } // } // // } /** * This method will find all avaliable report definitions for all the StudyOrganizations. */ public List<ReportDefinition> findAllReportDefintionNames(){ // evalutate available report definitions per session. if(this.allReportDefinitions.isEmpty()){ this.allReportDefinitions.addAll(evaluationService.applicableReportDefinitions(this.assignment)); //upate the index map for(ReportDefinition repDef : allReportDefinitions){ reportDefinitionIndexMap.put(repDef.getId(), repDef); } } return this.allReportDefinitions; } public List<ReportDefinition> findRequiredReportDefinitions(){ //if already available return that, as we will take care of clearing it when we quit this tab. if(requiredReportDefinitionsMap.isEmpty() && !adverseEventReportingPeriod.isBaselineReportingType()){ this.requiredReportDefinitionsMap = evaluationService.findRequiredReportDefinitions(this.adverseEventReportingPeriod); //refresh the serious AE list here refreshSeriousAdverseEvents(); } return new ArrayList<ReportDefinition>(requiredReportDefinitionsMap.keySet()); } /** * This method will return the ReportDefinition which are selected by user * page. */ public List<ReportDefinition> getSelectedReportDefinitions() { List<ReportDefinition> reportDefs = new ArrayList<ReportDefinition>(); for (Map.Entry<Integer, Boolean> entry : reportDefinitionMap.entrySet()) { if (entry.getValue() != null && entry.getValue()) reportDefs.add(reportDefinitionIndexMap.get(entry.getKey())); } return reportDefs; } /** * Will clear first the report definitions, then * add all report definitions, with value false, and updates the the value to true for selected ones. */ public void refreshReportDefinitionMap(){ reportDefinitionMap.clear(); for(ReportDefinition rpDef : allReportDefinitions){ reportDefinitionMap.put(rpDef.getId(), false); } //rules engine said reports should be selected for(ReportDefinition rpDef : requiredReportDefinitionsMap.keySet()){ reportDefinitionMap.put(rpDef.getId(), true); } } /** * This method will return the adverse events that are selected (checked) * @return */ public List<AdverseEvent> findSelectedAdverseEvents(){ List<AdverseEvent> adverseEvents = new ArrayList<AdverseEvent>(); for(AdverseEvent ae : adverseEventReportingPeriod.getAdverseEvents()){ Boolean value = selectedAesMap.get(ae.getId()); if(value != null && value){ adverseEvents.add(ae); } } return adverseEvents; } public void refreshReportStatusMap(){ reportStatusMap.clear(); //initialize every thing with empty for(ReportDefinition rpDef : allReportDefinitions){ reportStatusMap.put(rpDef.getId(), rpDef.getExpectedDisplayDueDate()); } } public void refreshReportDefinitionRequiredIndicatorMap(){ this.requiredReportDefinitionIndicatorMap.clear(); for(ReportDefinition rpDef : allReportDefinitions){ requiredReportDefinitionIndicatorMap.put(rpDef.getId(), false); } for(ReportDefinition rpDef : this.requiredReportDefinitionsMap.keySet()){ requiredReportDefinitionIndicatorMap.put(rpDef.getId(), true); } } /** * All AEs associated with <b>selectedReportDefinitions</b> must be selected. * * This method populates the SelectedAesMap member of the command object. The adverse events that were serious on triggering of the rules are set to true in this * Map. All the adverse events in the reporting period are keys in this map. */ public void refreshSelectedAesMap(){ selectedAesMap.clear(); //initialize all selected aes to false for(AdverseEvent ae: adverseEventReportingPeriod.getAdverseEvents()){ Integer id = ae.getId(); selectedAesMap.put(id, Boolean.FALSE); } for(AdverseEvent ae: adverseEventReportingPeriod.getReportableAdverseEvents()){ ae.setRequiresReporting(false); } //reset the ones that are available below with true for(Map.Entry<ReportDefinition, List<AdverseEvent>> entry : requiredReportDefinitionsMap.entrySet()){ for(AdverseEvent ae : entry.getValue()){ selectedAesMap.put(ae.getId(), true); ae.setRequiresReporting(Boolean.TRUE); } } } /** * The list of serious adverse events is refreshed here. */ public void refreshSeriousAdverseEvents(){ seriousAdverseEvents.clear(); for(List<AdverseEvent> aes : requiredReportDefinitionsMap.values()){ for(AdverseEvent ae : aes){ seriousAdverseEvents.add(ae); } } } /** * Find primary adverse event. */ //public void findPrimaryAdverseEvent(){ // if(adverseEventReportingPeriod.getAeReports().size() == 0) // if(!seriousAdverseEvents.isEmpty()) this.primaryAdverseEventId = new ArrayList<AdverseEvent>(seriousAdverseEvents).get(0).getId(); //} /** * Updates the requires reporting indicator of this AE. * @param ae */ public void updateRequiresReportingFlag(AdverseEvent ae){ if(seriousAdverseEvents == null || seriousAdverseEvents.isEmpty())return; ae.setRequiresReporting(seriousAdverseEvents.contains(ae)); } /** * This method will set the seriousness (outcome) on every adverse event, by reading the non-hospitalization and non-death outcome indicators, * preference is given to the first satisfied one. (Note:- In Expedited flow, the user may select multiple outcome(s). */ public void initializeOutcome(){ if(this.adverseEvents == null) return; for(AdverseEvent ae : adverseEvents.getInternalList()){ ae.setSerious(null); for(Outcome o: ae.getOutcomes()){ if(o.getOutcomeType().equals(OutcomeType.HOSPITALIZATION) || o.getOutcomeType().equals(OutcomeType.DEATH)) continue; ae.setSerious(o.getOutcomeType()); break; } } } /** * This method will synchronize the outcomes list associated with the adverse event. * If grade is 5, the outcome of type death is added, else removed(if present) * If hospitalization is 'yes', the outcome of type hospitalization is added, else removed (if present) * If the serious(outcome) not available in the outcomes list, it will be added. * Remove all the other outcomes present in the list (means user deselected a previously selected one) */ public void synchronizeOutcome(){ for(AdverseEvent ae : adverseEvents.getInternalList()){ //if grade is 5 make sure we have OutcomeType.DEATH if(ae.getGrade() != null && ae.getGrade().equals(Grade.DEATH)){ if(!isOutcomePresent(OutcomeType.DEATH, ae.getOutcomes())){ Outcome newOutcome = new Outcome(); newOutcome.setOutcomeType(OutcomeType.DEATH); ae.addOutcome(newOutcome); } }else{ removeOutcomeIfPresent(OutcomeType.DEATH, ae.getOutcomes()); } //if hospitalized, make sure we have OutcomeType.HOSPITALIZATION if(ae.getHospitalization() != null && ae.getHospitalization().equals(Hospitalization.YES)){ if(!isOutcomePresent(OutcomeType.HOSPITALIZATION, ae.getOutcomes())){ Outcome newOutcome = new Outcome(); newOutcome.setOutcomeType(OutcomeType.HOSPITALIZATION); ae.addOutcome(newOutcome); } }else { removeOutcomeIfPresent(OutcomeType.HOSPITALIZATION, ae.getOutcomes()); } //update the selected seriousness outcome if(ae.getSerious() != null){ if(!isOutcomePresent(ae.getSerious(), ae.getOutcomes())){ Outcome newOutcome = new Outcome(); newOutcome.setOutcomeType(ae.getSerious()); ae.addOutcome(newOutcome); } } //remove the rest of the outcomes for(OutcomeType outcomeType : OutcomeType.values()){ if(outcomeType.equals(OutcomeType.HOSPITALIZATION) || outcomeType.equals(OutcomeType.DEATH)) continue; if(ae.getSerious() != null && outcomeType.equals(ae.getSerious()) ) continue; removeOutcomeIfPresent(outcomeType, ae.getOutcomes()); } } } /** * Returns true, if an Outcome of a specific type is present in the list of outcomes */ private boolean isOutcomePresent(OutcomeType type, List<Outcome> outcomes){ if(outcomes == null || outcomes.isEmpty()) return false; for(Outcome o : outcomes){ if(o.getOutcomeType() == type) return true; } return false; } /** * Removes an outcome type, if it is present. */ private boolean removeOutcomeIfPresent(OutcomeType type, List<Outcome> outcomes){ if(outcomes == null || outcomes.isEmpty()) return false; Outcome obj = null; for(Outcome o : outcomes){ if(o.getOutcomeType() == type){ obj = o; break; } } if(obj == null) return false; return outcomes.remove(obj); } public void setSelectedAesMap(Map<Integer, Boolean> selectedAesMap) { this.selectedAesMap = selectedAesMap; } public Map<Integer, Boolean> getSelectedAesMap(){ return selectedAesMap; } public IndexFixedList<AdverseEvent> getAdverseEvents() { return adverseEvents; } public void setAdverseEvents(IndexFixedList<AdverseEvent> adverseEvents) { this.adverseEvents = adverseEvents; } /** * Returns all the {@link ReportDefinition} available to this AE */ public List<ReportDefinition> getAllReportDefinitions() { return allReportDefinitions; } public void setAllReportDefinitions(List<ReportDefinition> allReportDefinitions) { this.allReportDefinitions = allReportDefinitions; } public void setAdverseEventReportingPeriodDao( AdverseEventReportingPeriodDao adverseEventReportingPeriodDao) { this.adverseEventReportingPeriodDao = adverseEventReportingPeriodDao; } public Ctc getCtcVersion() { return ctcVersion; } public void setCtcVersion(Ctc ctcVersion) { this.ctcVersion = ctcVersion; } @Transient public Integer getTermCode(){ return null; } //this method is added to satisfy the UI requirements, so to be moved to the command class public void setTermCode(Integer ignore){} public StudyParticipantAssignment getAssignment() { if(assignment != null) return assignment; //fetch the assignment from DB. if (getParticipant() != null && getStudy() != null) { this.assignment = assignmentDao.getAssignment(getParticipant(), getStudy()); } return this.assignment; } public void setAssignment(StudyParticipantAssignment assignment) { this.assignment = assignment; } public boolean getIgnoreCompletedStudy() { // TODO Auto-generated method stub return false; } public Participant getParticipant() { return participant; } public Study getStudy() { return study; } public Participant getParticipantID() { return participant; } public Study getStudyID() { return study; } public String getTreatmentDescriptionType() { // TODO Auto-generated method stub return null; } public void setTreatmentDescriptionType(String type) { // TODO Auto-generated method stub } public void setParticipant(Participant participant) { this.participant = participant; } public void setStudy(Study study) { this.study = study; } public void setParticipantID(Participant participant) { this.participant = participant; } public void setStudyID(Study study) { this.study = study; } public AdverseEventReportingPeriod getAdverseEventReportingPeriod() { return adverseEventReportingPeriod; } public void setAdverseEventReportingPeriod(AdverseEventReportingPeriod adverseEventReportingPeriod) { this.adverseEventReportingPeriod = adverseEventReportingPeriod; initialize(); } public void setCtcCategories(List<CtcCategory> ctcCategories) { this.ctcCategories = ctcCategories; } public List<CtcCategory> getCtcCategories() { if(ctcCategories == null){ if(adverseEventReportingPeriod != null) setCtcCategories(adverseEventReportingPeriod.getStudy().getAeTerminology().getCtcVersion().getCategories()); } return ctcCategories; } public EvaluationService getEvaluationService() { return evaluationService; } public void setEvaluationService(EvaluationService evaluationService) { this.evaluationService = evaluationService; } public Map<ReportDefinition, List<AdverseEvent>> getRequiredReportDefinitionsMap() { return requiredReportDefinitionsMap; } public Map<Integer, String> getReportStatusMap() { return reportStatusMap; } public Map<Integer, Boolean> getRequiredReportDefinitionIndicatorMap() { return requiredReportDefinitionIndicatorMap; } public Map<Integer, Boolean> getReportDefinitionMap() { return reportDefinitionMap; } public void setReportDefinitionMap(Map<Integer, Boolean> reportDefinitionMap) { this.reportDefinitionMap = reportDefinitionMap; } public Integer getPrimaryAdverseEventId() { return primaryAdverseEventId; } public void setPrimaryAdverseEventId(Integer primaryAdverseEventId) { this.primaryAdverseEventId = primaryAdverseEventId; } public List<AdverseEvent> getSelectedAesList() { List selectedAesList = new ArrayList<AdverseEvent>(); Map<Integer, AdverseEvent> aeObjectMap = new HashMap<Integer, AdverseEvent>(); for(AdverseEvent ae: adverseEvents){ if(!aeObjectMap.containsKey(ae.getId())) aeObjectMap.put(ae.getId(), ae); } for(Integer id: getSelectedAesMap().keySet()){ if(getSelectedAesMap().get(id).equals(Boolean.TRUE)) selectedAesList.add(aeObjectMap.get(id)); } return selectedAesList; } public boolean getWorkflowEnabled() { return workflowEnabled; } public void setWorkflowEnabled(boolean workflowEnabled) { this.workflowEnabled = workflowEnabled; } //hasLabs public boolean isAssociatedToLabAlerts(){ return false; } public boolean isAssociatedToWorkflow(){ if(getAdverseEventReportingPeriod() == null) return false; return getAdverseEventReportingPeriod().getWorkflowId() != null; } public boolean isHavingSolicitedAEs(){ if(adverseEventReportingPeriod == null) return false; if(adverseEventReportingPeriod.getAdverseEvents() == null) return false; for(AdverseEvent ae : adverseEventReportingPeriod.getAdverseEvents()) if(ae.getSolicited()) return true; return false; } }
projects/web/src/main/java/gov/nih/nci/cabig/caaers/web/ae/CaptureAdverseEventInputCommand.java
package gov.nih.nci.cabig.caaers.web.ae; import gov.nih.nci.cabig.caaers.dao.AdverseEventReportingPeriodDao; import gov.nih.nci.cabig.caaers.dao.StudyDao; import gov.nih.nci.cabig.caaers.dao.StudyParticipantAssignmentDao; import gov.nih.nci.cabig.caaers.dao.report.ReportDefinitionDao; import gov.nih.nci.cabig.caaers.domain.AdverseEvent; import gov.nih.nci.cabig.caaers.domain.AdverseEventReportingPeriod; import gov.nih.nci.cabig.caaers.domain.Ctc; import gov.nih.nci.cabig.caaers.domain.CtcCategory; import gov.nih.nci.cabig.caaers.domain.ExpeditedAdverseEventReport; import gov.nih.nci.cabig.caaers.domain.Grade; import gov.nih.nci.cabig.caaers.domain.Hospitalization; import gov.nih.nci.cabig.caaers.domain.LabLoad; import gov.nih.nci.cabig.caaers.domain.Outcome; import gov.nih.nci.cabig.caaers.domain.OutcomeType; import gov.nih.nci.cabig.caaers.domain.Participant; import gov.nih.nci.cabig.caaers.domain.Study; import gov.nih.nci.cabig.caaers.domain.StudyParticipantAssignment; import gov.nih.nci.cabig.caaers.domain.Term; import gov.nih.nci.cabig.caaers.domain.report.Report; import gov.nih.nci.cabig.caaers.domain.report.ReportDefinition; import gov.nih.nci.cabig.caaers.domain.workflow.ReportingPeriodReviewComment; import gov.nih.nci.cabig.caaers.service.EvaluationService; import gov.nih.nci.cabig.caaers.tools.configuration.Configuration; import gov.nih.nci.cabig.caaers.utils.IndexFixedList; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import javax.persistence.Transient; public class CaptureAdverseEventInputCommand implements AdverseEventInputCommand { private StudyParticipantAssignment assignment; private StudyParticipantAssignmentDao assignmentDao; private ReportDefinitionDao reportDefinitionDao; private Participant participant; private Study study; private EvaluationService evaluationService; protected AdverseEventReportingPeriod adverseEventReportingPeriod; protected AdverseEventReportingPeriodDao adverseEventReportingPeriodDao; private StudyDao studyDao; private List<CtcCategory> ctcCategories; private Integer primaryAdverseEventId; private IndexFixedList<AdverseEvent> adverseEvents; // Added for Post processing in Confirmation page private List<ReportDefinition> allReportDefinitions; private Map<ReportDefinition, List<AdverseEvent>> requiredReportDefinitionsMap; private Map<Integer, String> reportStatusMap; private Map<Integer, Boolean> requiredReportDefinitionIndicatorMap; private Map<Integer, Boolean> reportDefinitionMap;//will store user selection //this map is used for internal purpouses private Map<Integer, ReportDefinition> reportDefinitionIndexMap; private Map<Integer, Boolean> selectedAesMap; private Ctc ctcVersion; private Set<AdverseEvent> seriousAdverseEvents; private boolean workflowEnabled = false; public CaptureAdverseEventInputCommand(){ } public CaptureAdverseEventInputCommand(AdverseEventReportingPeriodDao adverseEventReportingPeriodDao, StudyParticipantAssignmentDao assignmentDao, EvaluationService evaluationService, ReportDefinitionDao reportDefinitionDao, StudyDao studyDao){ this.adverseEventReportingPeriodDao = adverseEventReportingPeriodDao; this.assignmentDao = assignmentDao; this.evaluationService = evaluationService; this.reportDefinitionDao = reportDefinitionDao; this.studyDao = studyDao; this.selectedAesMap = new HashMap<Integer, Boolean>(); this.allReportDefinitions = new ArrayList<ReportDefinition>(); this.requiredReportDefinitionsMap = new HashMap<ReportDefinition, List<AdverseEvent>>(); this.reportStatusMap = new HashMap<Integer, String>(); this.requiredReportDefinitionIndicatorMap = new HashMap<Integer, Boolean>(); this.reportDefinitionMap = new HashMap<Integer, Boolean>(); this.reportDefinitionIndexMap = new HashMap<Integer, ReportDefinition>(); this.seriousAdverseEvents = new TreeSet<AdverseEvent>(new Comparator<AdverseEvent>(){ public int compare(AdverseEvent o1, AdverseEvent o2) { if(o1 == null && o2 == null) return 0; if(o1 == null || o1.getGrade() == null) return 1; if(o2 == null || o2.getGrade() == null) return -1; if(o1.getGrade().getCode() > o2.getGrade().getCode()) return -1; if(o1.getGrade().getCode() < o2.getGrade().getCode()) return 1; return 0; } }); } /** * This method will check if the study selected is a DCP sponsored study and is AdEERS submittable. * @return */ public boolean isDCPNonAdeersStudy(){ if(study == null) return false; return (!study.getAdeersReporting()) && study.getPrimaryFundingSponsorOrganization().getNciInstituteCode().equals("DCP"); } public void save() { // AdverseEventReportingPeriod mergedReportingPeriod; // // if(this.getAdverseEventReportingPeriod() != null){ // mergedReportingPeriod = adverseEventReportingPeriodDao.merge(this.getAdverseEventReportingPeriod()); // this.setAdverseEventReportingPeriod(mergedReportingPeriod); // } if(this.getAdverseEventReportingPeriod() != null) adverseEventReportingPeriodDao.save(this.getAdverseEventReportingPeriod()); } public void reassociate(){ //reassociate all report definitions if(allReportDefinitions != null) for(ReportDefinition repDef : allReportDefinitions){ reportDefinitionDao.reassociate(repDef); } studyDao.lock(study); if(this.adverseEventReportingPeriod != null && this.adverseEventReportingPeriod.getId() != null){ adverseEventReportingPeriodDao.reassociate(this.adverseEventReportingPeriod); } } /** * This method will refresh the StudyParticipantAssignment and updates the {@link AdverseEventReportingPeriod}. */ public void refreshAssignment(Integer reportingPeriodId){ //reload assignmet assignmentDao.refresh(getAssignment()); refreshReportingPeriod(reportingPeriodId); } public void refreshReportingPeriod(Integer reportingPeriodId){ studyDao.lock(study); assignmentDao.reassociate(getAssignment()); //reset the adverse event report in the command setAdverseEventReportingPeriod(null); for(AdverseEventReportingPeriod reportingPeriod : assignment.getReportingPeriods()){ if(reportingPeriod.getId().equals(reportingPeriodId)){ setAdverseEventReportingPeriod(reportingPeriod); break; } } } public void clearSession(){ assignmentDao.clearSession(); } public void evictUnwantedObjects(){ assignmentDao.evict(getAssignment()); } /** * This method will take care of initializing the lazy associations * This method will take care of * - Updating the index fixed list for AdverseEvents, associated to the reporting period * - initializing the lazy associations */ public void initialize(){ //set the assignment into the command. this.assignment = this.adverseEventReportingPeriod.getAssignment(); adverseEvents = new IndexFixedList<AdverseEvent>(new ArrayList<AdverseEvent>()); if(adverseEventReportingPeriod != null){ adverseEvents = new IndexFixedList<AdverseEvent>(adverseEventReportingPeriod.getAdverseEvents()); Study study = adverseEventReportingPeriod.getStudy(); if(study.getStudyOrganizations() != null) study.getStudyOrganizations().size(); if(study.getExpectedAECtcTerms() != null) study.getExpectedAECtcTerms().size(); boolean isCTCStudy = study.getAeTerminology().getTerm() == Term.CTC; if(isCTCStudy){ for(AdverseEvent ae : getAdverseEvents()){ ae.getAdverseEventTerm().isOtherRequired(); ae.getAdverseEventCtcTerm().getCtcTerm().isOtherRequired(); ae.getAdverseEventCtcTerm().getCtcTerm().getContextualGrades(); } } this.adverseEventReportingPeriod.getAdverseEvents().size(); this.adverseEventReportingPeriod.getAeReports(); for(ExpeditedAdverseEventReport aeReport : this.adverseEventReportingPeriod.getAeReports()){ aeReport.getAllSponsorReportsCompleted(); aeReport.getHasAmendableReport(); aeReport.getHasSubmittedReport(); aeReport.getNumberOfAes(); for(Report report : aeReport.getReports()){ report.getLastVersion().getVersion(); } } List<ReportingPeriodReviewComment> reviewCommentList = this.adverseEventReportingPeriod.getReviewComments(); if(reviewCommentList != null) this.adverseEventReportingPeriod.getReviewComments().size(); if(this.assignment != null) this.assignment.getParticipant().getIdentifiers(); } } // public void initializeObjectsInCommand(){ // if(study == null) return; // if(study.getExpectedAECtcTerms() != null) study.getExpectedAECtcTerms().size(); // boolean isCTCStudy = study.getAeTerminology().getTerm() == Term.CTC; // if (isCTCStudy){ // List<AdverseEvent> aes = getAdverseEvents(); // if(aes != null){ // for (AdverseEvent ae: aes) { // // } // } // } // // } /** * This method will find all avaliable report definitions for all the StudyOrganizations. */ public List<ReportDefinition> findAllReportDefintionNames(){ // evalutate available report definitions per session. if(this.allReportDefinitions.isEmpty()){ this.allReportDefinitions.addAll(evaluationService.applicableReportDefinitions(this.assignment)); //upate the index map for(ReportDefinition repDef : allReportDefinitions){ reportDefinitionIndexMap.put(repDef.getId(), repDef); } } return this.allReportDefinitions; } public List<ReportDefinition> findRequiredReportDefinitions(){ //if already available return that, as we will take care of clearing it when we quit this tab. if(requiredReportDefinitionsMap.isEmpty() && !adverseEventReportingPeriod.isBaselineReportingType()){ this.requiredReportDefinitionsMap = evaluationService.findRequiredReportDefinitions(this.adverseEventReportingPeriod); //refresh the serious AE list here refreshSeriousAdverseEvents(); } return new ArrayList<ReportDefinition>(requiredReportDefinitionsMap.keySet()); } /** * This method will return the ReportDefinition which are selected by user * page. */ public List<ReportDefinition> getSelectedReportDefinitions() { List<ReportDefinition> reportDefs = new ArrayList<ReportDefinition>(); for (Map.Entry<Integer, Boolean> entry : reportDefinitionMap.entrySet()) { if (entry.getValue() != null && entry.getValue()) reportDefs.add(reportDefinitionIndexMap.get(entry.getKey())); } return reportDefs; } /** * Will clear first the report definitions, then * add all report definitions, with value false, and updates the the value to true for selected ones. */ public void refreshReportDefinitionMap(){ reportDefinitionMap.clear(); for(ReportDefinition rpDef : allReportDefinitions){ reportDefinitionMap.put(rpDef.getId(), false); } //rules engine said reports should be selected for(ReportDefinition rpDef : requiredReportDefinitionsMap.keySet()){ reportDefinitionMap.put(rpDef.getId(), true); } } /** * This method will return the adverse events that are selected (checked) * @return */ public List<AdverseEvent> findSelectedAdverseEvents(){ List<AdverseEvent> adverseEvents = new ArrayList<AdverseEvent>(); for(AdverseEvent ae : adverseEventReportingPeriod.getAdverseEvents()){ Boolean value = selectedAesMap.get(ae.getId()); if(value != null && value){ adverseEvents.add(ae); } } return adverseEvents; } public void refreshReportStatusMap(){ reportStatusMap.clear(); //initialize every thing with empty for(ReportDefinition rpDef : allReportDefinitions){ reportStatusMap.put(rpDef.getId(), rpDef.getExpectedDisplayDueDate()); } } public void refreshReportDefinitionRequiredIndicatorMap(){ this.requiredReportDefinitionIndicatorMap.clear(); for(ReportDefinition rpDef : allReportDefinitions){ requiredReportDefinitionIndicatorMap.put(rpDef.getId(), false); } for(ReportDefinition rpDef : this.requiredReportDefinitionsMap.keySet()){ requiredReportDefinitionIndicatorMap.put(rpDef.getId(), true); } } /** * All AEs associated with <b>selectedReportDefinitions</b> must be selected. * * This method populates the SelectedAesMap member of the command object. The adverse events that were serious on triggering of the rules are set to true in this * Map. All the adverse events in the reporting period are keys in this map. */ public void refreshSelectedAesMap(){ selectedAesMap.clear(); //initialize all selected aes to false for(AdverseEvent ae: adverseEventReportingPeriod.getAdverseEvents()){ Integer id = ae.getId(); selectedAesMap.put(id, Boolean.FALSE); } for(AdverseEvent ae: adverseEventReportingPeriod.getReportableAdverseEvents()){ ae.setRequiresReporting(false); } //reset the ones that are available below with true for(Map.Entry<ReportDefinition, List<AdverseEvent>> entry : requiredReportDefinitionsMap.entrySet()){ for(AdverseEvent ae : entry.getValue()){ selectedAesMap.put(ae.getId(), true); ae.setRequiresReporting(Boolean.TRUE); } } } /** * The list of serious adverse events is refreshed here. */ public void refreshSeriousAdverseEvents(){ seriousAdverseEvents.clear(); for(List<AdverseEvent> aes : requiredReportDefinitionsMap.values()){ for(AdverseEvent ae : aes){ seriousAdverseEvents.add(ae); } } } /** * Find primary adverse event. */ //public void findPrimaryAdverseEvent(){ // if(adverseEventReportingPeriod.getAeReports().size() == 0) // if(!seriousAdverseEvents.isEmpty()) this.primaryAdverseEventId = new ArrayList<AdverseEvent>(seriousAdverseEvents).get(0).getId(); //} /** * Updates the requires reporting indicator of this AE. * @param ae */ public void updateRequiresReportingFlag(AdverseEvent ae){ if(seriousAdverseEvents == null || seriousAdverseEvents.isEmpty())return; ae.setRequiresReporting(seriousAdverseEvents.contains(ae)); } /** * This method will set the seriousness (outcome) on every adverse event, by reading the non-hospitalization and non-death outcome indicators, * preference is given to the first satisfied one. (Note:- In Expedited flow, the user may select multiple outcome(s). */ public void initializeOutcome(){ if(this.adverseEvents == null) return; for(AdverseEvent ae : adverseEvents.getInternalList()){ ae.setSerious(null); for(Outcome o: ae.getOutcomes()){ if(o.getOutcomeType().equals(OutcomeType.HOSPITALIZATION) || o.getOutcomeType().equals(OutcomeType.DEATH)) continue; ae.setSerious(o.getOutcomeType()); break; } } } /** * This method will synchronize the outcomes list associated with the adverse event. * If grade is 5, the outcome of type death is added, else removed(if present) * If hospitalization is 'yes', the outcome of type hospitalization is added, else removed (if present) * If the serious(outcome) not available in the outcomes list, it will be added. * Remove all the other outcomes present in the list (means user deselected a previously selected one) */ public void synchronizeOutcome(){ for(AdverseEvent ae : adverseEvents.getInternalList()){ //if grade is 5 make sure we have OutcomeType.DEATH if(ae.getGrade() != null && ae.getGrade().equals(Grade.DEATH)){ if(!isOutcomePresent(OutcomeType.DEATH, ae.getOutcomes())){ Outcome newOutcome = new Outcome(); newOutcome.setOutcomeType(OutcomeType.DEATH); ae.addOutcome(newOutcome); } }else{ removeOutcomeIfPresent(OutcomeType.DEATH, ae.getOutcomes()); } //if hospitalized, make sure we have OutcomeType.HOSPITALIZATION if(ae.getHospitalization() != null && ae.getHospitalization().equals(Hospitalization.YES)){ if(!isOutcomePresent(OutcomeType.HOSPITALIZATION, ae.getOutcomes())){ Outcome newOutcome = new Outcome(); newOutcome.setOutcomeType(OutcomeType.HOSPITALIZATION); ae.addOutcome(newOutcome); } }else { removeOutcomeIfPresent(OutcomeType.HOSPITALIZATION, ae.getOutcomes()); } //update the selected seriousness outcome if(ae.getSerious() != null){ if(!isOutcomePresent(ae.getSerious(), ae.getOutcomes())){ Outcome newOutcome = new Outcome(); newOutcome.setOutcomeType(ae.getSerious()); ae.addOutcome(newOutcome); } } //remove the rest of the outcomes for(OutcomeType outcomeType : OutcomeType.values()){ if(outcomeType.equals(OutcomeType.HOSPITALIZATION) || outcomeType.equals(OutcomeType.DEATH)) continue; if(ae.getSerious() != null && outcomeType.equals(ae.getSerious()) ) continue; removeOutcomeIfPresent(outcomeType, ae.getOutcomes()); } } } /** * Returns true, if an Outcome of a specific type is present in the list of outcomes */ private boolean isOutcomePresent(OutcomeType type, List<Outcome> outcomes){ if(outcomes == null || outcomes.isEmpty()) return false; for(Outcome o : outcomes){ if(o.getOutcomeType() == type) return true; } return false; } /** * Removes an outcome type, if it is present. */ private boolean removeOutcomeIfPresent(OutcomeType type, List<Outcome> outcomes){ if(outcomes == null || outcomes.isEmpty()) return false; Outcome obj = null; for(Outcome o : outcomes){ if(o.getOutcomeType() == type){ obj = o; break; } } if(obj == null) return false; return outcomes.remove(obj); } public void setSelectedAesMap(Map<Integer, Boolean> selectedAesMap) { this.selectedAesMap = selectedAesMap; } public Map<Integer, Boolean> getSelectedAesMap(){ return selectedAesMap; } public IndexFixedList<AdverseEvent> getAdverseEvents() { return adverseEvents; } public void setAdverseEvents(IndexFixedList<AdverseEvent> adverseEvents) { this.adverseEvents = adverseEvents; } /** * Returns all the {@link ReportDefinition} available to this AE */ public List<ReportDefinition> getAllReportDefinitions() { return allReportDefinitions; } public void setAllReportDefinitions(List<ReportDefinition> allReportDefinitions) { this.allReportDefinitions = allReportDefinitions; } public void setAdverseEventReportingPeriodDao( AdverseEventReportingPeriodDao adverseEventReportingPeriodDao) { this.adverseEventReportingPeriodDao = adverseEventReportingPeriodDao; } public Ctc getCtcVersion() { return ctcVersion; } public void setCtcVersion(Ctc ctcVersion) { this.ctcVersion = ctcVersion; } @Transient public Integer getTermCode(){ return null; } //this method is added to satisfy the UI requirements, so to be moved to the command class public void setTermCode(Integer ignore){} public StudyParticipantAssignment getAssignment() { if(assignment != null) return assignment; //fetch the assignment from DB. if (getParticipant() != null && getStudy() != null) { this.assignment = assignmentDao.getAssignment(getParticipant(), getStudy()); } return this.assignment; } public void setAssignment(StudyParticipantAssignment assignment) { this.assignment = assignment; } public boolean getIgnoreCompletedStudy() { // TODO Auto-generated method stub return false; } public Participant getParticipant() { return participant; } public Study getStudy() { return study; } public Participant getParticipantID() { return participant; } public Study getStudyID() { return study; } public String getTreatmentDescriptionType() { // TODO Auto-generated method stub return null; } public void setTreatmentDescriptionType(String type) { // TODO Auto-generated method stub } public void setParticipant(Participant participant) { this.participant = participant; } public void setStudy(Study study) { this.study = study; } public void setParticipantID(Participant participant) { this.participant = participant; } public void setStudyID(Study study) { this.study = study; } public AdverseEventReportingPeriod getAdverseEventReportingPeriod() { return adverseEventReportingPeriod; } public void setAdverseEventReportingPeriod(AdverseEventReportingPeriod adverseEventReportingPeriod) { this.adverseEventReportingPeriod = adverseEventReportingPeriod; initialize(); } public void setCtcCategories(List<CtcCategory> ctcCategories) { this.ctcCategories = ctcCategories; } public List<CtcCategory> getCtcCategories() { if(ctcCategories == null){ if(adverseEventReportingPeriod != null) setCtcCategories(adverseEventReportingPeriod.getStudy().getAeTerminology().getCtcVersion().getCategories()); } return ctcCategories; } public EvaluationService getEvaluationService() { return evaluationService; } public void setEvaluationService(EvaluationService evaluationService) { this.evaluationService = evaluationService; } public Map<ReportDefinition, List<AdverseEvent>> getRequiredReportDefinitionsMap() { return requiredReportDefinitionsMap; } public Map<Integer, String> getReportStatusMap() { return reportStatusMap; } public Map<Integer, Boolean> getRequiredReportDefinitionIndicatorMap() { return requiredReportDefinitionIndicatorMap; } public Map<Integer, Boolean> getReportDefinitionMap() { return reportDefinitionMap; } public void setReportDefinitionMap(Map<Integer, Boolean> reportDefinitionMap) { this.reportDefinitionMap = reportDefinitionMap; } public Integer getPrimaryAdverseEventId() { return primaryAdverseEventId; } public void setPrimaryAdverseEventId(Integer primaryAdverseEventId) { this.primaryAdverseEventId = primaryAdverseEventId; } public List<AdverseEvent> getSelectedAesList() { List selectedAesList = new ArrayList<AdverseEvent>(); Map<Integer, AdverseEvent> aeObjectMap = new HashMap<Integer, AdverseEvent>(); for(AdverseEvent ae: adverseEvents){ if(!aeObjectMap.containsKey(ae.getId())) aeObjectMap.put(ae.getId(), ae); } for(Integer id: getSelectedAesMap().keySet()){ if(getSelectedAesMap().get(id).equals(Boolean.TRUE)) selectedAesList.add(aeObjectMap.get(id)); } return selectedAesList; } public boolean getWorkflowEnabled() { return workflowEnabled; } public void setWorkflowEnabled(boolean workflowEnabled) { this.workflowEnabled = workflowEnabled; } //hasLabs public boolean isAssociatedToLabAlerts(){ return false; } public boolean isAssociatedToWorkflow(){ if(getAdverseEventReportingPeriod() == null) return false; return getAdverseEventReportingPeriod().getWorkflowId() != null; } public boolean isHavingSolicitedAEs(){ if(adverseEventReportingPeriod == null) return false; if(adverseEventReportingPeriod.getAdverseEvents() == null) return false; for(AdverseEvent ae : adverseEventReportingPeriod.getAdverseEvents()) if(ae.getSolicited()) return true; return false; } }
fix for null pointer in capture page SVN-Revision: 8197
projects/web/src/main/java/gov/nih/nci/cabig/caaers/web/ae/CaptureAdverseEventInputCommand.java
fix for null pointer in capture page
<ide><path>rojects/web/src/main/java/gov/nih/nci/cabig/caaers/web/ae/CaptureAdverseEventInputCommand.java <ide> */ <ide> public void initialize(){ <ide> //set the assignment into the command. <del> this.assignment = this.adverseEventReportingPeriod.getAssignment(); <add> if(this.adverseEventReportingPeriod != null) <add> this.assignment = this.adverseEventReportingPeriod.getAssignment(); <ide> <ide> adverseEvents = new IndexFixedList<AdverseEvent>(new ArrayList<AdverseEvent>()); <ide> if(adverseEventReportingPeriod != null){
Java
bsd-3-clause
fd47ff00097ccf2d5f1805ae055e13922a54de22
0
krishagni/openspecimen,krishagni/openspecimen,krishagni/openspecimen
package com.krishagni.catissueplus.core.biospecimen.events; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.krishagni.catissueplus.core.administrative.domain.PermissibleValue; import com.krishagni.catissueplus.core.administrative.events.StorageLocationSummary; import com.krishagni.catissueplus.core.biospecimen.domain.Specimen; import com.krishagni.catissueplus.core.biospecimen.domain.SpecimenRequirement; import com.krishagni.catissueplus.core.biospecimen.domain.Visit; import com.krishagni.catissueplus.core.common.ListenAttributeChanges; import com.krishagni.catissueplus.core.common.util.Utility; import com.krishagni.catissueplus.core.de.events.ExtensionDetail; @ListenAttributeChanges public class SpecimenDetail extends SpecimenInfo { private static final long serialVersionUID = -752005520158376620L; private CollectionEventDetail collectionEvent; private ReceivedEventDetail receivedEvent; private String labelFmt; private String labelAutoPrintMode; private Set<String> biohazards; private String comments; private Boolean closeAfterChildrenCreation; private List<SpecimenDetail> children; private Long pooledSpecimenId; private String pooledSpecimenLabel; private List<SpecimenDetail> specimensPool; // // Properties required for auto-creation of containers // private StorageLocationSummary containerLocation; private Long containerTypeId; private String containerTypeName; // This is needed for creation of derivatives from BO for closing parent specimen. private Boolean closeParent; private Boolean poolSpecimen; private String reqCode; private ExtensionDetail extensionDetail; private boolean reserved; // // transient variables specifying action to be performed // private boolean forceDelete; private boolean printLabel; private Integer incrParentFreezeThaw; private Date transferTime; private String transferComments; private boolean autoCollectParents; private String uid; private String parentUid; private Long dpId; private StorageLocationSummary holdingLocation; public CollectionEventDetail getCollectionEvent() { return collectionEvent; } public void setCollectionEvent(CollectionEventDetail collectionEvent) { this.collectionEvent = collectionEvent; } public ReceivedEventDetail getReceivedEvent() { return receivedEvent; } public void setReceivedEvent(ReceivedEventDetail receivedEvent) { this.receivedEvent = receivedEvent; } public String getLabelFmt() { return labelFmt; } public void setLabelFmt(String labelFmt) { this.labelFmt = labelFmt; } public String getLabelAutoPrintMode() { return labelAutoPrintMode; } public void setLabelAutoPrintMode(String labelAutoPrintMode) { this.labelAutoPrintMode = labelAutoPrintMode; } public List<SpecimenDetail> getChildren() { return children; } public void setChildren(List<SpecimenDetail> children) { this.children = children; } public Long getPooledSpecimenId() { return pooledSpecimenId; } public void setPooledSpecimenId(Long pooledSpecimenId) { this.pooledSpecimenId = pooledSpecimenId; } public String getPooledSpecimenLabel() { return pooledSpecimenLabel; } public void setPooledSpecimenLabel(String pooledSpecimenLabel) { this.pooledSpecimenLabel = pooledSpecimenLabel; } public List<SpecimenDetail> getSpecimensPool() { return specimensPool; } public void setSpecimensPool(List<SpecimenDetail> specimensPool) { this.specimensPool = specimensPool; } @JsonIgnore public StorageLocationSummary getContainerLocation() { return containerLocation; } @JsonProperty public void setContainerLocation(StorageLocationSummary containerLocation) { this.containerLocation = containerLocation; } @JsonIgnore public Long getContainerTypeId() { return containerTypeId; } @JsonProperty public void setContainerTypeId(Long containerTypeId) { this.containerTypeId = containerTypeId; } @JsonIgnore public String getContainerTypeName() { return containerTypeName; } @JsonProperty public void setContainerTypeName(String containerTypeName) { this.containerTypeName = containerTypeName; } public Set<String> getBiohazards() { return biohazards; } public void setBiohazards(Set<String> biohazards) { this.biohazards = biohazards; } public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } @JsonIgnore public Boolean getCloseAfterChildrenCreation() { return closeAfterChildrenCreation; } @JsonProperty public void setCloseAfterChildrenCreation(Boolean closeAfterChildrenCreation) { this.closeAfterChildrenCreation = closeAfterChildrenCreation; } @JsonIgnore public Boolean getCloseParent() { return closeParent; } @JsonProperty public void setCloseParent(Boolean closeParent) { this.closeParent = closeParent; } public Boolean getPoolSpecimen() { return poolSpecimen; } public void setPoolSpecimen(Boolean poolSpecimen) { this.poolSpecimen = poolSpecimen; } public String getReqCode() { return reqCode; } public void setReqCode(String reqCode) { this.reqCode = reqCode; } @JsonIgnore public boolean closeParent() { return closeParent == null ? false : closeParent; } public ExtensionDetail getExtensionDetail() { return extensionDetail; } public void setExtensionDetail(ExtensionDetail extensionDetail) { this.extensionDetail = extensionDetail; } public boolean isReserved() { return reserved; } public void setReserved(boolean reserved) { this.reserved = reserved; } @JsonIgnore public boolean isForceDelete() { return forceDelete; } public void setForceDelete(boolean forceDelete) { this.forceDelete = forceDelete; } // // Do not serialise printLabel from interaction object to response JSON. Therefore @JsonIgnore // However, deserialise, if present, from input request JSON to interaction object. Hence @JsonProperty // @JsonIgnore public boolean isPrintLabel() { return printLabel; } @JsonProperty public void setPrintLabel(boolean printLabel) { this.printLabel = printLabel; } @JsonIgnore public Integer getIncrParentFreezeThaw() { return incrParentFreezeThaw; } @JsonProperty public void setIncrParentFreezeThaw(Integer incrParentFreezeThaw) { this.incrParentFreezeThaw = incrParentFreezeThaw; } @JsonIgnore public Date getTransferTime() { return transferTime; } @JsonProperty public void setTransferTime(Date transferTime) { this.transferTime = transferTime; } @JsonIgnore public String getTransferComments() { return transferComments; } @JsonProperty public void setTransferComments(String transferComments) { this.transferComments = transferComments; } @JsonIgnore public boolean isAutoCollectParents() { return autoCollectParents; } @JsonProperty public void setAutoCollectParents(boolean autoCollectParents) { this.autoCollectParents = autoCollectParents; } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getParentUid() { return parentUid; } public void setParentUid(String parentUid) { this.parentUid = parentUid; } public Long getDpId() { return dpId; } public void setDpId(Long dpId) { this.dpId = dpId; } @JsonIgnore public StorageLocationSummary getHoldingLocation() { return holdingLocation; } @JsonProperty public void setHoldingLocation(StorageLocationSummary holdingLocation) { this.holdingLocation = holdingLocation; } public static SpecimenDetail from(Specimen specimen) { return from(specimen, true, true); } public static SpecimenDetail from(Specimen specimen, boolean partial, boolean excludePhi) { return from(specimen, partial, excludePhi, false); } public static SpecimenDetail from(Specimen specimen, boolean partial, boolean excludePhi, boolean excludeChildren) { SpecimenDetail result = new SpecimenDetail(); SpecimenInfo.fromTo(specimen, result); SpecimenRequirement sr = specimen.getSpecimenRequirement(); if (!excludeChildren) { if (sr == null) { List<SpecimenDetail> children = Utility.nullSafeStream(specimen.getChildCollection()) .map(child -> from(child, partial, excludePhi, excludeChildren)) .collect(Collectors.toList()); sort(children); result.setChildren(children); } else { if (sr.isPooledSpecimenReq()) { result.setSpecimensPool(getSpecimens(specimen.getVisit(), sr.getSpecimenPoolReqs(), specimen.getSpecimensPool(), partial, excludePhi, excludeChildren)); } result.setPoolSpecimen(sr.isSpecimenPoolReq()); result.setChildren(getSpecimens(specimen.getVisit(), sr.getChildSpecimenRequirements(), specimen.getChildCollection(), partial, excludePhi, excludeChildren)); } if (specimen.getPooledSpecimen() != null) { result.setPooledSpecimenId(specimen.getPooledSpecimen().getId()); result.setPooledSpecimenLabel(specimen.getPooledSpecimen().getLabel()); } } // // false to ensure we don't end up in infinite recurssion // result.setLabelFmt(specimen.getLabelTmpl(false)); if (sr != null && sr.getLabelAutoPrintModeToUse() != null) { result.setLabelAutoPrintMode(sr.getLabelAutoPrintModeToUse().name()); } result.setReqCode(sr != null ? sr.getCode() : null); result.setBiohazards(PermissibleValue.toValueSet(specimen.getBiohazards())); result.setComments(specimen.getComment()); result.setReserved(specimen.isReserved()); if (!partial) { result.setExtensionDetail(ExtensionDetail.from(specimen.getExtension(), excludePhi)); if (specimen.isPrimary()) { result.setCollectionEvent(CollectionEventDetail.from(specimen.getCollectionEvent())); result.setReceivedEvent(ReceivedEventDetail.from(specimen.getReceivedEvent())); } else { result.setCollectionEvent(CollectionEventDetail.from(specimen.getCollRecvDetails())); result.setReceivedEvent(ReceivedEventDetail.from(specimen.getCollRecvDetails())); } } result.setUid(specimen.getUid()); result.setParentUid(specimen.getParentUid()); return result; } public static List<SpecimenDetail> from(Collection<Specimen> specimens) { return Utility.nullSafeStream(specimens).map(SpecimenDetail::from).collect(Collectors.toList()); } public static SpecimenDetail from(SpecimenRequirement anticipated) { return SpecimenDetail.from(anticipated, false); } public static SpecimenDetail from(SpecimenRequirement anticipated, boolean excludeChildren) { SpecimenDetail result = new SpecimenDetail(); SpecimenInfo.fromTo(anticipated, result); if (anticipated.isPooledSpecimenReq()) { result.setSpecimensPool(fromAnticipated(anticipated.getSpecimenPoolReqs(), excludeChildren)); } result.setPoolSpecimen(anticipated.isSpecimenPoolReq()); if (!excludeChildren) { result.setChildren(fromAnticipated(anticipated.getChildSpecimenRequirements(), excludeChildren)); } result.setLabelFmt(anticipated.getLabelTmpl()); if (anticipated.getLabelAutoPrintModeToUse() != null) { result.setLabelAutoPrintMode(anticipated.getLabelAutoPrintModeToUse().name()); } result.setReqCode(anticipated.getCode()); return result; } public static void sort(List<SpecimenDetail> specimens) { Collections.sort(specimens); for (SpecimenDetail specimen : specimens) { if (specimen.getChildren() != null) { sort(specimen.getChildren()); } } } public static List<SpecimenDetail> getSpecimens( Visit visit, Collection<SpecimenRequirement> anticipated, Collection<Specimen> specimens, boolean partial, boolean excludePhi, boolean excludeChildren) { List<SpecimenDetail> result = Utility.stream(specimens) .map(s -> SpecimenDetail.from(s, partial, excludePhi, excludeChildren)) .collect(Collectors.toList()); merge(visit, anticipated, result, null, getReqSpecimenMap(result), excludeChildren); SpecimenDetail.sort(result); return result; } private static Map<Long, SpecimenDetail> getReqSpecimenMap(List<SpecimenDetail> specimens) { Map<Long, SpecimenDetail> reqSpecimenMap = new HashMap<>(); List<SpecimenDetail> remaining = new ArrayList<>(); remaining.addAll(specimens); while (!remaining.isEmpty()) { SpecimenDetail specimen = remaining.remove(0); Long srId = (specimen.getReqId() == null) ? -1 : specimen.getReqId(); reqSpecimenMap.put(srId, specimen); if (specimen.getChildren() != null) { remaining.addAll(specimen.getChildren()); } } return reqSpecimenMap; } private static void merge( Visit visit, Collection<SpecimenRequirement> anticipatedSpecimens, List<SpecimenDetail> result, SpecimenDetail currentParent, Map<Long, SpecimenDetail> reqSpecimenMap, boolean excludeChildren) { for (SpecimenRequirement anticipated : anticipatedSpecimens) { SpecimenDetail specimen = reqSpecimenMap.get(anticipated.getId()); if (specimen != null && excludeChildren) { continue; } if (specimen != null) { merge(visit, anticipated.getChildSpecimenRequirements(), result, specimen, reqSpecimenMap, excludeChildren); } else if (!anticipated.isClosed()) { specimen = SpecimenDetail.from(anticipated, excludeChildren); setVisitDetails(visit, specimen); if (currentParent == null) { result.add(specimen); } else { specimen.setParentId(currentParent.getId()); currentParent.getChildren().add(specimen); } } } } private static void setVisitDetails(Visit visit, SpecimenDetail specimen) { if (visit == null) { return; } specimen.setVisitId(visit.getId()); specimen.setVisitName(visit.getName()); specimen.setVisitStatus(visit.getStatus()); specimen.setSprNo(visit.getSurgicalPathologyNumber()); specimen.setVisitDate(visit.getVisitDate()); Utility.nullSafeStream(specimen.getChildren()).forEach(child -> setVisitDetails(visit, child)); } private static List<SpecimenDetail> fromAnticipated(Collection<SpecimenRequirement> anticipatedSpecimens, boolean excludeChildren) { return Utility.nullSafeStream(anticipatedSpecimens) .filter(anticipated -> !anticipated.isClosed()) .map(s -> SpecimenDetail.from(s, excludeChildren)) .collect(Collectors.toList()); } }
WEB-INF/src/com/krishagni/catissueplus/core/biospecimen/events/SpecimenDetail.java
package com.krishagni.catissueplus.core.biospecimen.events; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.krishagni.catissueplus.core.administrative.domain.PermissibleValue; import com.krishagni.catissueplus.core.administrative.events.StorageLocationSummary; import com.krishagni.catissueplus.core.biospecimen.domain.Specimen; import com.krishagni.catissueplus.core.biospecimen.domain.SpecimenRequirement; import com.krishagni.catissueplus.core.biospecimen.domain.Visit; import com.krishagni.catissueplus.core.common.ListenAttributeChanges; import com.krishagni.catissueplus.core.common.util.Utility; import com.krishagni.catissueplus.core.de.events.ExtensionDetail; @ListenAttributeChanges public class SpecimenDetail extends SpecimenInfo { private static final long serialVersionUID = -752005520158376620L; private CollectionEventDetail collectionEvent; private ReceivedEventDetail receivedEvent; private String labelFmt; private String labelAutoPrintMode; private Set<String> biohazards; private String comments; private Boolean closeAfterChildrenCreation; private List<SpecimenDetail> children; private Long pooledSpecimenId; private String pooledSpecimenLabel; private List<SpecimenDetail> specimensPool; // // Properties required for auto-creation of containers // private StorageLocationSummary containerLocation; private Long containerTypeId; private String containerTypeName; // This is needed for creation of derivatives from BO for closing parent specimen. private Boolean closeParent; private Boolean poolSpecimen; private String reqCode; private ExtensionDetail extensionDetail; private boolean reserved; // // transient variables specifying action to be performed // private boolean forceDelete; private boolean printLabel; private Integer incrParentFreezeThaw; private Date transferTime; private String transferComments; private boolean autoCollectParents; private String uid; private String parentUid; private Long dpId; private StorageLocationSummary holdingLocation; public CollectionEventDetail getCollectionEvent() { return collectionEvent; } public void setCollectionEvent(CollectionEventDetail collectionEvent) { this.collectionEvent = collectionEvent; } public ReceivedEventDetail getReceivedEvent() { return receivedEvent; } public void setReceivedEvent(ReceivedEventDetail receivedEvent) { this.receivedEvent = receivedEvent; } public String getLabelFmt() { return labelFmt; } public void setLabelFmt(String labelFmt) { this.labelFmt = labelFmt; } public String getLabelAutoPrintMode() { return labelAutoPrintMode; } public void setLabelAutoPrintMode(String labelAutoPrintMode) { this.labelAutoPrintMode = labelAutoPrintMode; } public List<SpecimenDetail> getChildren() { return children; } public void setChildren(List<SpecimenDetail> children) { this.children = children; } public Long getPooledSpecimenId() { return pooledSpecimenId; } public void setPooledSpecimenId(Long pooledSpecimenId) { this.pooledSpecimenId = pooledSpecimenId; } public String getPooledSpecimenLabel() { return pooledSpecimenLabel; } public void setPooledSpecimenLabel(String pooledSpecimenLabel) { this.pooledSpecimenLabel = pooledSpecimenLabel; } public List<SpecimenDetail> getSpecimensPool() { return specimensPool; } public void setSpecimensPool(List<SpecimenDetail> specimensPool) { this.specimensPool = specimensPool; } @JsonIgnore public StorageLocationSummary getContainerLocation() { return containerLocation; } @JsonProperty public void setContainerLocation(StorageLocationSummary containerLocation) { this.containerLocation = containerLocation; } @JsonIgnore public Long getContainerTypeId() { return containerTypeId; } @JsonProperty public void setContainerTypeId(Long containerTypeId) { this.containerTypeId = containerTypeId; } @JsonIgnore public String getContainerTypeName() { return containerTypeName; } @JsonProperty public void setContainerTypeName(String containerTypeName) { this.containerTypeName = containerTypeName; } public Set<String> getBiohazards() { return biohazards; } public void setBiohazards(Set<String> biohazards) { this.biohazards = biohazards; } public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } @JsonIgnore public Boolean getCloseAfterChildrenCreation() { return closeAfterChildrenCreation; } @JsonProperty public void setCloseAfterChildrenCreation(Boolean closeAfterChildrenCreation) { this.closeAfterChildrenCreation = closeAfterChildrenCreation; } @JsonIgnore public Boolean getCloseParent() { return closeParent; } @JsonProperty public void setCloseParent(Boolean closeParent) { this.closeParent = closeParent; } public Boolean getPoolSpecimen() { return poolSpecimen; } public void setPoolSpecimen(Boolean poolSpecimen) { this.poolSpecimen = poolSpecimen; } public String getReqCode() { return reqCode; } public void setReqCode(String reqCode) { this.reqCode = reqCode; } @JsonIgnore public boolean closeParent() { return closeParent == null ? false : closeParent; } public ExtensionDetail getExtensionDetail() { return extensionDetail; } public void setExtensionDetail(ExtensionDetail extensionDetail) { this.extensionDetail = extensionDetail; } public boolean isReserved() { return reserved; } public void setReserved(boolean reserved) { this.reserved = reserved; } @JsonIgnore public boolean isForceDelete() { return forceDelete; } public void setForceDelete(boolean forceDelete) { this.forceDelete = forceDelete; } // // Do not serialise printLabel from interaction object to response JSON. Therefore @JsonIgnore // However, deserialise, if present, from input request JSON to interaction object. Hence @JsonProperty // @JsonIgnore public boolean isPrintLabel() { return printLabel; } @JsonProperty public void setPrintLabel(boolean printLabel) { this.printLabel = printLabel; } @JsonIgnore public Integer getIncrParentFreezeThaw() { return incrParentFreezeThaw; } @JsonProperty public void setIncrParentFreezeThaw(Integer incrParentFreezeThaw) { this.incrParentFreezeThaw = incrParentFreezeThaw; } @JsonIgnore public Date getTransferTime() { return transferTime; } @JsonProperty public void setTransferTime(Date transferTime) { this.transferTime = transferTime; } @JsonIgnore public String getTransferComments() { return transferComments; } @JsonProperty public void setTransferComments(String transferComments) { this.transferComments = transferComments; } @JsonIgnore public boolean isAutoCollectParents() { return autoCollectParents; } @JsonProperty public void setAutoCollectParents(boolean autoCollectParents) { this.autoCollectParents = autoCollectParents; } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getParentUid() { return parentUid; } public void setParentUid(String parentUid) { this.parentUid = parentUid; } public Long getDpId() { return dpId; } public void setDpId(Long dpId) { this.dpId = dpId; } @JsonIgnore public StorageLocationSummary getHoldingLocation() { return holdingLocation; } @JsonProperty public void setHoldingLocation(StorageLocationSummary holdingLocation) { this.holdingLocation = holdingLocation; } public static SpecimenDetail from(Specimen specimen) { return from(specimen, true, true); } public static SpecimenDetail from(Specimen specimen, boolean partial, boolean excludePhi) { return from(specimen, partial, excludePhi, false); } public static SpecimenDetail from(Specimen specimen, boolean partial, boolean excludePhi, boolean excludeChildren) { SpecimenDetail result = new SpecimenDetail(); SpecimenInfo.fromTo(specimen, result); SpecimenRequirement sr = specimen.getSpecimenRequirement(); if (!excludeChildren) { if (sr == null) { List<SpecimenDetail> children = Utility.nullSafeStream(specimen.getChildCollection()) .map(child -> from(child, partial, excludePhi, excludeChildren)) .collect(Collectors.toList()); sort(children); result.setChildren(children); } else { if (sr.isPooledSpecimenReq()) { result.setSpecimensPool(getSpecimens(specimen.getVisit(), sr.getSpecimenPoolReqs(), specimen.getSpecimensPool(), partial, excludePhi, excludeChildren)); } result.setPoolSpecimen(sr.isSpecimenPoolReq()); result.setChildren(getSpecimens(specimen.getVisit(), sr.getChildSpecimenRequirements(), specimen.getChildCollection(), partial, excludePhi, excludeChildren)); } if (specimen.getPooledSpecimen() != null) { result.setPooledSpecimenId(specimen.getPooledSpecimen().getId()); result.setPooledSpecimenLabel(specimen.getPooledSpecimen().getLabel()); } } // // false to ensure we don't end up in infinite recurssion // result.setLabelFmt(specimen.getLabelTmpl(false)); if (sr != null && sr.getLabelAutoPrintModeToUse() != null) { result.setLabelAutoPrintMode(sr.getLabelAutoPrintModeToUse().name()); } result.setReqCode(sr != null ? sr.getCode() : null); result.setBiohazards(PermissibleValue.toValueSet(specimen.getBiohazards())); result.setComments(specimen.getComment()); result.setReserved(specimen.isReserved()); if (!partial) { result.setExtensionDetail(ExtensionDetail.from(specimen.getExtension(), excludePhi)); result.setCollectionEvent(CollectionEventDetail.from(specimen.getCollRecvDetails())); result.setReceivedEvent(ReceivedEventDetail.from(specimen.getCollRecvDetails())); } result.setUid(specimen.getUid()); result.setParentUid(specimen.getParentUid()); return result; } public static List<SpecimenDetail> from(Collection<Specimen> specimens) { return Utility.nullSafeStream(specimens).map(SpecimenDetail::from).collect(Collectors.toList()); } public static SpecimenDetail from(SpecimenRequirement anticipated) { return SpecimenDetail.from(anticipated, false); } public static SpecimenDetail from(SpecimenRequirement anticipated, boolean excludeChildren) { SpecimenDetail result = new SpecimenDetail(); SpecimenInfo.fromTo(anticipated, result); if (anticipated.isPooledSpecimenReq()) { result.setSpecimensPool(fromAnticipated(anticipated.getSpecimenPoolReqs(), excludeChildren)); } result.setPoolSpecimen(anticipated.isSpecimenPoolReq()); if (!excludeChildren) { result.setChildren(fromAnticipated(anticipated.getChildSpecimenRequirements(), excludeChildren)); } result.setLabelFmt(anticipated.getLabelTmpl()); if (anticipated.getLabelAutoPrintModeToUse() != null) { result.setLabelAutoPrintMode(anticipated.getLabelAutoPrintModeToUse().name()); } result.setReqCode(anticipated.getCode()); return result; } public static void sort(List<SpecimenDetail> specimens) { Collections.sort(specimens); for (SpecimenDetail specimen : specimens) { if (specimen.getChildren() != null) { sort(specimen.getChildren()); } } } public static List<SpecimenDetail> getSpecimens( Visit visit, Collection<SpecimenRequirement> anticipated, Collection<Specimen> specimens, boolean partial, boolean excludePhi, boolean excludeChildren) { List<SpecimenDetail> result = Utility.stream(specimens) .map(s -> SpecimenDetail.from(s, partial, excludePhi, excludeChildren)) .collect(Collectors.toList()); merge(visit, anticipated, result, null, getReqSpecimenMap(result), excludeChildren); SpecimenDetail.sort(result); return result; } private static Map<Long, SpecimenDetail> getReqSpecimenMap(List<SpecimenDetail> specimens) { Map<Long, SpecimenDetail> reqSpecimenMap = new HashMap<>(); List<SpecimenDetail> remaining = new ArrayList<>(); remaining.addAll(specimens); while (!remaining.isEmpty()) { SpecimenDetail specimen = remaining.remove(0); Long srId = (specimen.getReqId() == null) ? -1 : specimen.getReqId(); reqSpecimenMap.put(srId, specimen); if (specimen.getChildren() != null) { remaining.addAll(specimen.getChildren()); } } return reqSpecimenMap; } private static void merge( Visit visit, Collection<SpecimenRequirement> anticipatedSpecimens, List<SpecimenDetail> result, SpecimenDetail currentParent, Map<Long, SpecimenDetail> reqSpecimenMap, boolean excludeChildren) { for (SpecimenRequirement anticipated : anticipatedSpecimens) { SpecimenDetail specimen = reqSpecimenMap.get(anticipated.getId()); if (specimen != null && excludeChildren) { continue; } if (specimen != null) { merge(visit, anticipated.getChildSpecimenRequirements(), result, specimen, reqSpecimenMap, excludeChildren); } else if (!anticipated.isClosed()) { specimen = SpecimenDetail.from(anticipated, excludeChildren); setVisitDetails(visit, specimen); if (currentParent == null) { result.add(specimen); } else { specimen.setParentId(currentParent.getId()); currentParent.getChildren().add(specimen); } } } } private static void setVisitDetails(Visit visit, SpecimenDetail specimen) { if (visit == null) { return; } specimen.setVisitId(visit.getId()); specimen.setVisitName(visit.getName()); specimen.setVisitStatus(visit.getStatus()); specimen.setSprNo(visit.getSurgicalPathologyNumber()); specimen.setVisitDate(visit.getVisitDate()); Utility.nullSafeStream(specimen.getChildren()).forEach(child -> setVisitDetails(visit, child)); } private static List<SpecimenDetail> fromAnticipated(Collection<SpecimenRequirement> anticipatedSpecimens, boolean excludeChildren) { return Utility.nullSafeStream(anticipatedSpecimens) .filter(anticipated -> !anticipated.isClosed()) .map(s -> SpecimenDetail.from(s, excludeChildren)) .collect(Collectors.toList()); } }
OPSMN-5572: The collection and received event details of the API response were populated using the "read-only" collection/receive detail object, mapped to a view. When the specimen is created/collected, this detail object is empty/null. Therefore the API response didn't contain any details of collection and received events. To fix the issue, the collection/received details, for primary specimens, in the response are filled by accessing the event records stored in the DB.
WEB-INF/src/com/krishagni/catissueplus/core/biospecimen/events/SpecimenDetail.java
OPSMN-5572: The collection and received event details of the API response were populated using the "read-only" collection/receive detail object, mapped to a view. When the specimen is created/collected, this detail object is empty/null. Therefore the API response didn't contain any details of collection and received events.
<ide><path>EB-INF/src/com/krishagni/catissueplus/core/biospecimen/events/SpecimenDetail.java <ide> <ide> if (!partial) { <ide> result.setExtensionDetail(ExtensionDetail.from(specimen.getExtension(), excludePhi)); <del> result.setCollectionEvent(CollectionEventDetail.from(specimen.getCollRecvDetails())); <del> result.setReceivedEvent(ReceivedEventDetail.from(specimen.getCollRecvDetails())); <add> if (specimen.isPrimary()) { <add> result.setCollectionEvent(CollectionEventDetail.from(specimen.getCollectionEvent())); <add> result.setReceivedEvent(ReceivedEventDetail.from(specimen.getReceivedEvent())); <add> } else { <add> result.setCollectionEvent(CollectionEventDetail.from(specimen.getCollRecvDetails())); <add> result.setReceivedEvent(ReceivedEventDetail.from(specimen.getCollRecvDetails())); <add> } <ide> } <ide> <ide> result.setUid(specimen.getUid());
Java
lgpl-2.1
1de5e1e54b5fa6769041128e5e563b09b8c18f39
0
fjalvingh/domui,fjalvingh/domui,fjalvingh/domui,fjalvingh/domui,fjalvingh/domui,fjalvingh/domui,fjalvingh/domui
package to.etc.util; import java.io.*; public class ProcessTools { private ProcessTools() { } /** * This is used to async read strout and stderr streams from a process... */ static public class StreamReaderThread extends Thread { /** The stream to read, */ private Reader m_reader; /** The output writer thing. */ private final Writer m_w; private final char[] m_buf; public StreamReaderThread(final Appendable sb, String name, InputStream is) { this(sb, name, is, System.getProperty("file.encoding")); } public StreamReaderThread(final Appendable sb, String name, InputStream is, String encoding) { this(new Writer() { @Override public void write(char[] cbuf, int off, int len) throws IOException { while(len-- > 0) sb.append(cbuf[off++]); } @Override public void flush() throws IOException { } @Override public void close() throws IOException { } }, name, is, encoding); } public StreamReaderThread(Writer sb, String name, InputStream is) { this(sb, name, is, System.getProperty("file.encoding")); } public StreamReaderThread(Writer w, String name, InputStream is, String encoding) { m_w = w; m_buf = new char[1024]; setName("StreamReader" + name); try { m_reader = new InputStreamReader(is, encoding); } catch(UnsupportedEncodingException x) // Fuck James Gosling with his stupid checked exceptions crap { throw new IllegalStateException("Unsupported encoding " + encoding); } } /** * Read data from the stream until it closes line by line; add each line to * the output channel. */ @Override public void run() { try { int szrd; while(0 < (szrd = m_reader.read(m_buf))) { // System.out.println("dbg: writing "+szrd+" chars to the stream"); m_w.write(m_buf, 0, szrd); } m_w.flush(); } catch(Throwable x) { x.printStackTrace(); } finally { try { if(m_reader != null) m_reader.close(); } catch(Exception x) {} } // System.out.println("Reader "+m_name+" terminated."); } } /** * This is used to async read strout and stderr streams from a process into another output stream. */ static public class StreamCopyThread extends Thread { /** The stream to read, */ private InputStream m_is; private OutputStream m_os; private final byte[] m_buf; public StreamCopyThread(final OutputStream os, String name, InputStream is) { m_os = os; m_is = is; m_buf = new byte[1024]; setName("StreamReader" + name); } /** * Read data from the stream until it closes line by line; add each line to * the output channel. */ @Override public void run() { try { int szrd; while(0 < (szrd = m_is.read(m_buf))) { m_os.write(m_buf, 0, szrd); } m_os.flush(); } catch(Throwable x) { x.printStackTrace(); } finally { try { if(m_is != null) m_is.close(); } catch(Exception x) {} } } } /** * Waits for completion of the command and collect data into the streams. */ static public int dumpStreams(Process pr, Appendable iosb) throws Exception { //-- Create two reader classes, StreamReaderThread outr = new StreamReaderThread(iosb, "stdout", pr.getInputStream()); StreamReaderThread errr = new StreamReaderThread(iosb, "stderr", pr.getErrorStream()); //-- Start both of 'm outr.start(); errr.start(); int rc = pr.waitFor(); outr.join(); errr.join(); return rc; } /** * Runs the process whose data is in the ProcessBuilder and captures the result with stdout and stderr merged. * @param pb * @param sb * @return * @throws Exception */ static public int runProcess(ProcessBuilder pb, Appendable sb) throws Exception { pb.redirectErrorStream(true); // Merge stdout and stderr Process pr = pb.start(); StreamReaderThread outr = new StreamReaderThread(sb, "stdout", pr.getInputStream()); outr.start(); int rc = pr.waitFor(); outr.join(); return rc; } /** * Runs the process whose data is in the ProcessBuilder and captures the result. * @param pb * @param sb * @return * @throws Exception */ static public int runProcess(ProcessBuilder pb, OutputStream stdout, Appendable stderrsb) throws Exception { Process pr = pb.start(); StreamReaderThread errr = new StreamReaderThread(stderrsb, "stderr", pr.getErrorStream()); StreamCopyThread outr = new StreamCopyThread(stdout, "stdout", pr.getInputStream()); outr.start(); errr.start(); int rc = pr.waitFor(); outr.join(); errr.join(); return rc; } /** * Runs the process whose data is in the ProcessBuilder and captures the result with stdout and stderr merged. * @param pb * @param sb * @return * @throws Exception */ static public int runProcess(ProcessBuilder pb, Appendable outsb, Appendable errsb) throws Exception { pb.redirectErrorStream(true); // Merge stdout and stderr Process pr = pb.start(); StreamReaderThread outr = new StreamReaderThread(outsb, "stdout", pr.getInputStream()); StreamReaderThread errr = new StreamReaderThread(errsb, "stderr", pr.getErrorStream()); outr.start(); errr.start(); int rc = pr.waitFor(); outr.join(); errr.join(); return rc; } /** * Runs the process whose data is in the ProcessBuilder and captures the * result with stdout and stderr merged into a writer. * @param pb * @param sb * @return * @throws Exception */ static public int runProcess(ProcessBuilder pb, Writer out) throws Exception { pb.redirectErrorStream(true); // Merge stdout and stderr Process pr = pb.start(); StreamReaderThread outr = new StreamReaderThread(out, "stdout", pr.getInputStream()); outr.start(); int rc = pr.waitFor(); outr.join(); return rc; } }
to.etc.alg/src/to/etc/util/ProcessTools.java
package to.etc.util; import java.io.*; public class ProcessTools { private ProcessTools() { } /** * This is used to async read strout and stderr streams from a process... */ static public class StreamReaderThread extends Thread { /** The stream to read, */ private Reader m_reader; /** The output writer thing. */ private final Writer m_w; private final char[] m_buf; public StreamReaderThread(final Appendable sb, String name, InputStream is) { this(sb, name, is, System.getProperty("file.encoding")); } public StreamReaderThread(final Appendable sb, String name, InputStream is, String encoding) { this(new Writer() { @Override public void write(char[] cbuf, int off, int len) throws IOException { while(len-- > 0) sb.append(cbuf[off++]); } @Override public void flush() throws IOException { } @Override public void close() throws IOException { } }, name, is, encoding); } public StreamReaderThread(Writer sb, String name, InputStream is) { this(sb, name, is, System.getProperty("file.encoding")); } public StreamReaderThread(Writer w, String name, InputStream is, String encoding) { m_w = w; m_buf = new char[1024]; setName("StreamReader" + name); try { m_reader = new InputStreamReader(is, encoding); } catch(UnsupportedEncodingException x) // Fuck James Gosling with his stupid checked exceptions crap { throw new IllegalStateException("Unsupported encoding " + encoding); } } /** * Read data from the stream until it closes line by line; add each line to * the output channel. */ @Override public void run() { try { int szrd; while(0 < (szrd = m_reader.read(m_buf))) { // System.out.println("dbg: writing "+szrd+" chars to the stream"); m_w.write(m_buf, 0, szrd); } m_w.flush(); } catch(Throwable x) { x.printStackTrace(); } finally { try { if(m_reader != null) m_reader.close(); } catch(Exception x) {} } // System.out.println("Reader "+m_name+" terminated."); } } /** * Waits for completion of the command and collect data into the streams. */ static public int dumpStreams(Process pr, Appendable iosb) throws Exception { //-- Create two reader classes, StreamReaderThread outr = new StreamReaderThread(iosb, "stdout", pr.getInputStream()); StreamReaderThread errr = new StreamReaderThread(iosb, "stderr", pr.getErrorStream()); //-- Start both of 'm outr.start(); errr.start(); int rc = pr.waitFor(); outr.join(); errr.join(); return rc; } /** * Runs the process whose data is in the ProcessBuilder and captures the result with stdout and stderr merged. * @param pb * @param sb * @return * @throws Exception */ static public int runProcess(ProcessBuilder pb, Appendable sb) throws Exception { pb.redirectErrorStream(true); // Merge stdout and stderr Process pr = pb.start(); StreamReaderThread outr = new StreamReaderThread(sb, "stdout", pr.getInputStream()); outr.start(); int rc = pr.waitFor(); outr.join(); return rc; } /** * Runs the process whose data is in the ProcessBuilder and captures the result with stdout and stderr merged. * @param pb * @param sb * @return * @throws Exception */ static public int runProcess(ProcessBuilder pb, Appendable outsb, Appendable errsb) throws Exception { pb.redirectErrorStream(true); // Merge stdout and stderr Process pr = pb.start(); StreamReaderThread outr = new StreamReaderThread(outsb, "stdout", pr.getInputStream()); StreamReaderThread errr = new StreamReaderThread(errsb, "stderr", pr.getErrorStream()); outr.start(); errr.start(); int rc = pr.waitFor(); outr.join(); errr.join(); return rc; } /** * Runs the process whose data is in the ProcessBuilder and captures the * result with stdout and stderr merged into a writer. * @param pb * @param sb * @return * @throws Exception */ static public int runProcess(ProcessBuilder pb, Writer out) throws Exception { pb.redirectErrorStream(true); // Merge stdout and stderr Process pr = pb.start(); StreamReaderThread outr = new StreamReaderThread(out, "stdout", pr.getInputStream()); outr.start(); int rc = pr.waitFor(); outr.join(); return rc; } }
Add code to copy output to a stream
to.etc.alg/src/to/etc/util/ProcessTools.java
Add code to copy output to a stream
<ide><path>o.etc.alg/src/to/etc/util/ProcessTools.java <ide> } <ide> <ide> /** <add> * This is used to async read strout and stderr streams from a process into another output stream. <add> */ <add> static public class StreamCopyThread extends Thread { <add> /** The stream to read, */ <add> private InputStream m_is; <add> <add> private OutputStream m_os; <add> <add> private final byte[] m_buf; <add> <add> public StreamCopyThread(final OutputStream os, String name, InputStream is) { <add> m_os = os; <add> m_is = is; <add> m_buf = new byte[1024]; <add> setName("StreamReader" + name); <add> } <add> <add> /** <add> * Read data from the stream until it closes line by line; add each line to <add> * the output channel. <add> */ <add> @Override <add> public void run() { <add> try { <add> int szrd; <add> while(0 < (szrd = m_is.read(m_buf))) { <add> m_os.write(m_buf, 0, szrd); <add> } <add> m_os.flush(); <add> } catch(Throwable x) { <add> x.printStackTrace(); <add> } finally { <add> try { <add> if(m_is != null) <add> m_is.close(); <add> } catch(Exception x) {} <add> } <add> } <add> } <add> <add> /** <ide> * Waits for completion of the command and collect data into the streams. <ide> */ <ide> static public int dumpStreams(Process pr, Appendable iosb) throws Exception { <ide> } <ide> <ide> /** <add> * Runs the process whose data is in the ProcessBuilder and captures the result. <add> * @param pb <add> * @param sb <add> * @return <add> * @throws Exception <add> */ <add> static public int runProcess(ProcessBuilder pb, OutputStream stdout, Appendable stderrsb) throws Exception { <add> Process pr = pb.start(); <add> StreamReaderThread errr = new StreamReaderThread(stderrsb, "stderr", pr.getErrorStream()); <add> StreamCopyThread outr = new StreamCopyThread(stdout, "stdout", pr.getInputStream()); <add> outr.start(); <add> errr.start(); <add> int rc = pr.waitFor(); <add> outr.join(); <add> errr.join(); <add> return rc; <add> } <add> <add> /** <ide> * Runs the process whose data is in the ProcessBuilder and captures the result with stdout and stderr merged. <ide> * @param pb <ide> * @param sb
Java
agpl-3.0
51519991c7f7d0b3811921f23ec40cc167a77db3
0
USAID-DELIVER-PROJECT/elmis,USAID-DELIVER-PROJECT/elmis,OpenLMIS/open-lmis,OpenLMIS/open-lmis,USAID-DELIVER-PROJECT/elmis,USAID-DELIVER-PROJECT/elmis,OpenLMIS/open-lmis,OpenLMIS/open-lmis
package org.openlmis.web.controller.vaccine; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JRParameter; import org.openlmis.core.domain.*; import org.openlmis.core.exception.DataException; import org.openlmis.core.service.*; import org.openlmis.core.web.OpenLmisResponse; import org.openlmis.core.web.controller.BaseController; import org.openlmis.report.util.Constants; import org.openlmis.reporting.model.Template; import org.openlmis.reporting.service.JasperReportsViewFactory; import org.openlmis.reporting.service.TemplateService; import org.openlmis.vaccine.domain.VaccineOrderRequisition.VaccineOrderStatus; import org.openlmis.vaccine.domain.inventory.StockMovement; import org.openlmis.vaccine.service.Inventory.VaccineInventoryService; import org.openlmis.vaccine.service.VaccineOrderRequisitionServices.VaccineOrderRequisitionLineItemService; import org.openlmis.vaccine.service.VaccineOrderRequisitionServices.VaccineOrderRequisitionService; import org.openlmis.vaccine.service.VaccineOrderRequisitionServices.VaccineOrderRequisitionsColumnService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PostAuthorize; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.jasperreports.JasperReportsMultiFormatView; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.util.*; import static org.openlmis.core.web.OpenLmisResponse.error; import static org.openlmis.core.web.OpenLmisResponse.response; import static org.openlmis.core.web.OpenLmisResponse.success; import static org.springframework.web.bind.annotation.RequestMethod.GET; @Controller @RequestMapping(value = "/vaccine/orderRequisition/") public class VaccineOrderRequisitionController extends BaseController { public static final String VaccineOrderRequisition = "orderRequisition"; public static final String OrderRequisitionColumns = "columns"; private static final String PROGRAM_PRODUCT_LIST = "programProductList"; private static final String PRINT_ORDER_REQUISITION = "Print Order Requisition"; private static final String PRINT_ISSUE_STOCK = "Print Issue report"; private static final String ORDER_REQUISITION_SEARCH = "search"; @Autowired VaccineOrderRequisitionService service; @Autowired FacilityService facilityService; @Autowired VaccineOrderRequisitionLineItemService lineItemService; @Autowired TemplateService templateService; @Autowired VaccineOrderRequisitionsColumnService columnService; @Autowired ProgramService programService; @Autowired private ProgramProductService programProductService; @Autowired private JasperReportsViewFactory jasperReportsViewFactory; @Autowired UserService userService; @Autowired VaccineInventoryService inventoryService; @Autowired ConfigurationSettingService settingService; @RequestMapping(value = "periods/{facilityId}/{programId}", method = RequestMethod.GET) //TODO// @PreAuthorize("@permissionEvaluator.hasPermission(principal,'CREATE_REQUISITION, AUTHORIZE_REQUISITION')") public ResponseEntity<OpenLmisResponse> getPeriods(@PathVariable Long facilityId, @PathVariable Long programId, HttpServletRequest request){ return response("periods", service.getPeriodsFor(facilityId, programId, new Date())); } @RequestMapping(value = "view-periods/{facilityId}/{programId}", method = RequestMethod.GET) //TODO// @PreAuthorize("@permissionEvaluator.hasPermission(principal,'CREATE_REQUISITION, AUTHORIZE_REQUISITION')") public ResponseEntity<OpenLmisResponse> getViewPeriods(@PathVariable Long facilityId, @PathVariable Long programId, HttpServletRequest request){ return response("periods", service.getReportedPeriodsFor(facilityId, programId)); } @RequestMapping(value = "initialize/{periodId}/{programId}/{facilityId}") //TODO @PreAuthorize("@permissionEvaluator.hasPermission(principal,'CREATE_REQUISITION, AUTHORIZE_REQUISITION')") public ResponseEntity<OpenLmisResponse> initialize( @PathVariable Long periodId, @PathVariable Long programId, @PathVariable Long facilityId, HttpServletRequest request ){ return response("report", service.initialize(periodId, programId, facilityId, loggedInUserId(request))); } @RequestMapping(value = "initializeEmergency/{periodId}/{programId}/{facilityId}") //TODO @PreAuthorize("@permissionEvaluator.hasPermission(principal,'CREATE_ORDER_REQUISITION)") public ResponseEntity<OpenLmisResponse> initializeEmergency( @PathVariable Long periodId, @PathVariable Long programId, @PathVariable Long facilityId, HttpServletRequest request ){ return response("report", service.initializeEmergency(periodId, programId, facilityId, loggedInUserId(request))); } @RequestMapping(value = "submit") //TODO @PreAuthorize("@permissionEvaluator.hasPermission(principal,'CREATE_ORDER_REQUISITION')") public ResponseEntity<OpenLmisResponse> submit(@RequestBody org.openlmis.vaccine.domain.VaccineOrderRequisition.VaccineOrderRequisition orderRequisition, HttpServletRequest request){ service.submit(orderRequisition, loggedInUserId(request)); return response("report", orderRequisition); } @RequestMapping(value = "save") //TODO @PreAuthorize("@permissionEvaluator.hasPermission(principal,'CREATE_ORDER_REQUISITION')") public ResponseEntity<OpenLmisResponse> save(@RequestBody org.openlmis.vaccine.domain.VaccineOrderRequisition.VaccineOrderRequisition orderRequisition, HttpServletRequest request){ service.save(orderRequisition); return response("report", orderRequisition); } @RequestMapping(value = "lastReport/{facilityId}/{programId}", method = RequestMethod.GET) //TODO @PreAuthorize("@permissionEvaluator.hasPermission(principal,'CREATE_ORDER_REQUISITION')") public ResponseEntity<OpenLmisResponse> getLastReport(@PathVariable Long facilityId,@PathVariable Long programId,HttpServletRequest request){ return response("lastReport", service.getLastReport(facilityId, programId)); } @RequestMapping(value = "get/{id}.json", method = RequestMethod.GET) //TODO @PreAuthorize("@permissionEvaluator.hasPermission(principal,'CREATE_REQUISITION, AUTHORIZE_REQUISITION')") public ResponseEntity<OpenLmisResponse> getReport(@PathVariable Long id, HttpServletRequest request){ return response("report", service.getAllDetailsById(id)); } @RequestMapping(value = "userHomeFacility.json", method = RequestMethod.GET) public ResponseEntity<OpenLmisResponse> getUserHomeFacilities(HttpServletRequest request){ return response("homeFacility", facilityService.getHomeFacility(loggedInUserId(request))); } @RequestMapping(value = "orderRequisitionTest/{id}/print", method = RequestMethod.GET, headers = ACCEPT_PDF) @PostAuthorize("@vaccineOrderRequisitionPermissionService.hasPermission(principal, returnObject.model.get(\"orderRequisition\"), 'VIEW_REQUISITION')") public ModelAndView printOrders(@PathVariable Long id) throws JRException, IOException, ClassNotFoundException { ModelAndView modelAndView = new ModelAndView("vaccineOrderRequisition"); org.openlmis.vaccine.domain.VaccineOrderRequisition.VaccineOrderRequisition requisition = service.getAllDetailsById(id); modelAndView.addObject(VaccineOrderRequisition, requisition); modelAndView.addObject(OrderRequisitionColumns,columnService.getAllColumns()); return modelAndView; } @RequestMapping(value = "getPendingRequest/{facilityId}/{programId}", method = RequestMethod.GET,headers = ACCEPT_JSON) public ResponseEntity<OpenLmisResponse> getPendingRequest(@PathVariable Long facilityId,@PathVariable Long programId,HttpServletRequest request){ return response("pendingRequest", service.getPendingRequest(loggedInUserId(request), facilityId, programId)); } @RequestMapping(value = "getAllBy/{programId}/{periodId}/{facilityId}", method = RequestMethod.GET,headers = ACCEPT_JSON) public ResponseEntity<OpenLmisResponse> getAllBy(@PathVariable Long programId ,@PathVariable Long periodId,@PathVariable Long facilityId,HttpServletRequest request){ return response("requisitionList", service.getAllBy(programId, periodId, facilityId)); } @RequestMapping(value = "updateOrderRequest/{orderId}", method = RequestMethod.PUT,headers = ACCEPT_JSON) //TODO @PreAuthorize("@permissionEvaluator.hasPermission(principal,'CREATE_ORDER_REQUISITION')") public ResponseEntity<OpenLmisResponse> updateORStatus(@PathVariable Long orderId,HttpServletRequest request){ try{ service.updateORStatus(orderId); return success("Saved Successifully"); } catch (DataException e) { return error(e, HttpStatus.BAD_REQUEST); } } @RequestMapping(value = "updateOrderRequisition/{orderId}", method = RequestMethod.PUT,headers = ACCEPT_JSON) public ResponseEntity<OpenLmisResponse> update(@PathVariable Long orderId,@RequestBody org.openlmis.vaccine.domain.VaccineOrderRequisition.VaccineOrderRequisition orderRequisition, HttpServletRequest request){ orderRequisition.setId(orderId); orderRequisition.setStatus(VaccineOrderStatus.ISSUED); service.save(orderRequisition); return response("report", orderRequisition); } @RequestMapping(value = "programs.json", method = RequestMethod.GET) public ResponseEntity<OpenLmisResponse> getProgramsForConfiguration() { return response("programs", programService.getAllIvdPrograms()); } @RequestMapping(value = "loggedInUserDetails.json", method = RequestMethod.GET) public ResponseEntity<OpenLmisResponse> getLoggedInUserProfiles(HttpServletRequest request) { Long userId = loggedInUserId(request); User user = userService.getById(userId); return response("userDetails", user); } @RequestMapping(value = "order-requisition/programs.json", method = RequestMethod.GET) public ResponseEntity<OpenLmisResponse> getProgramFormHomeFacility(HttpServletRequest request) { Long userId = loggedInUserId(request); User user = userService.getById(userId); return response("programs", programService.getProgramsSupportedByUserHomeFacilityWithRights(user.getFacilityId(), userId, "CREATE_REQUISITION", "AUTHORIZE_REQUISITION")); } @RequestMapping(value = "/{programId}", method = GET, headers = ACCEPT_JSON) public ResponseEntity<OpenLmisResponse> getProgramProductsByProgram(@PathVariable Long programId) { List<ProgramProduct> programProductsByProgram = programProductService.getByProgram(new Program(programId)); return response(PROGRAM_PRODUCT_LIST, programProductsByProgram); } @RequestMapping(value = "{id}/print", method = GET, headers = ACCEPT_JSON) public ModelAndView printOrder(@PathVariable Long id) throws JRException, IOException, ClassNotFoundException { Template orPrintTemplate = templateService.getByName(PRINT_ORDER_REQUISITION); JasperReportsMultiFormatView jasperView = jasperReportsViewFactory.getJasperReportsView(orPrintTemplate); Map<String, Object> map = new HashMap<>(); map.put("format", "pdf"); Locale currentLocale = messageService.getCurrentLocale(); map.put(JRParameter.REPORT_LOCALE, currentLocale); ResourceBundle resourceBundle = ResourceBundle.getBundle("messages", currentLocale); map.put(JRParameter.REPORT_RESOURCE_BUNDLE, resourceBundle); Resource reportResource = new ClassPathResource("report"); Resource imgResource = new ClassPathResource("images"); ConfigurationSetting configuration = settingService.getByKey(Constants.OPERATOR_NAME); map.put(Constants.OPERATOR_NAME, configuration.getValue()); String separator = System.getProperty("file.separator"); map.put("image_dir", imgResource.getFile().getAbsolutePath() + separator); map.put("ORDER_ID", id.intValue()); return new ModelAndView(jasperView, map); } @RequestMapping(value = "issue/print", method = GET, headers = ACCEPT_JSON) public ModelAndView printIssueStock() throws JRException, IOException, ClassNotFoundException { Template orPrintTemplate = templateService.getByName(PRINT_ISSUE_STOCK); StockMovement stockMovement = inventoryService.getLastStockMovement(); JasperReportsMultiFormatView jasperView = jasperReportsViewFactory.getJasperReportsView(orPrintTemplate); Map<String, Object> map = new HashMap<>(); map.put("format", "pdf"); Locale currentLocale = messageService.getCurrentLocale(); map.put(JRParameter.REPORT_LOCALE, currentLocale); ResourceBundle resourceBundle = ResourceBundle.getBundle("messages", currentLocale); map.put(JRParameter.REPORT_RESOURCE_BUNDLE, resourceBundle); Resource reportResource = new ClassPathResource("report"); Resource imgResource = new ClassPathResource("images"); ConfigurationSetting configuration = settingService.getByKey(Constants.OPERATOR_NAME); map.put(Constants.OPERATOR_NAME, configuration.getValue()); String separator = System.getProperty("file.separator"); map.put("image_dir", imgResource.getFile().getAbsolutePath() + separator); map.put("ISSUE_ID", stockMovement.getId().intValue()); return new ModelAndView(jasperView, map); } @RequestMapping(value = "search", method = GET,headers = ACCEPT_JSON) @PreAuthorize("@permissionEvaluator.hasPermission(principal,'VIEW_ORDER_REQUISITION')") public ResponseEntity<OpenLmisResponse> searchUser(@RequestParam(value = "facilityId", required = false) Long facilityId, @RequestParam(value = "dateRangeStart", required = false) String dateRangeStart, @RequestParam(value = "dateRangeEnd", required = false) String dateRangeEnd, @RequestParam(value = "programId", required = false) Long programId, HttpServletRequest request ) { return response(ORDER_REQUISITION_SEARCH, service.getAllSearchBy(facilityId,dateRangeStart,dateRangeEnd,programId)); } }
modules/openlmis-web/src/main/java/org/openlmis/web/controller/vaccine/VaccineOrderRequisitionController.java
package org.openlmis.web.controller.vaccine; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JRParameter; import org.openlmis.core.domain.*; import org.openlmis.core.exception.DataException; import org.openlmis.core.service.*; import org.openlmis.core.web.OpenLmisResponse; import org.openlmis.core.web.controller.BaseController; import org.openlmis.report.util.Constants; import org.openlmis.reporting.model.Template; import org.openlmis.reporting.service.JasperReportsViewFactory; import org.openlmis.reporting.service.TemplateService; import org.openlmis.vaccine.domain.VaccineOrderRequisition.VaccineOrderRequisitionSearchCriteria; import org.openlmis.vaccine.domain.VaccineOrderRequisition.VaccineOrderStatus; import org.openlmis.vaccine.domain.inventory.StockMovement; import org.openlmis.vaccine.service.Inventory.VaccineInventoryService; import org.openlmis.vaccine.service.VaccineOrderRequisitionServices.VaccineOrderRequisitionLineItemService; import org.openlmis.vaccine.service.VaccineOrderRequisitionServices.VaccineOrderRequisitionService; import org.openlmis.vaccine.service.VaccineOrderRequisitionServices.VaccineOrderRequisitionsColumnService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PostAuthorize; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.jasperreports.JasperReportsMultiFormatView; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletRequest; import java.awt.image.BufferedImage; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import static java.lang.Integer.parseInt; import static org.openlmis.core.web.OpenLmisResponse.error; import static org.openlmis.core.web.OpenLmisResponse.response; import static org.openlmis.core.web.OpenLmisResponse.success; import static org.springframework.web.bind.annotation.RequestMethod.GET; import static java.lang.System.out; @Controller @RequestMapping(value = "/vaccine/orderRequisition/") public class VaccineOrderRequisitionController extends BaseController { public static final String VaccineOrderRequisition = "orderRequisition"; public static final String OrderRequisitionColumns = "columns"; private static final String PROGRAM_PRODUCT_LIST = "programProductList"; private static final String PRINT_ORDER_REQUISITION = "Print Order Requisition"; private static final String PRINT_ISSUE_STOCK = "Print Issue report"; private static final String ORDER_REQUISITION_SEARCH = "search"; @Autowired VaccineOrderRequisitionService service; @Autowired FacilityService facilityService; @Autowired VaccineOrderRequisitionLineItemService lineItemService; @Autowired TemplateService templateService; @Autowired VaccineOrderRequisitionsColumnService columnService; @Autowired ProgramService programService; @Autowired private ProgramProductService programProductService; @Autowired private JasperReportsViewFactory jasperReportsViewFactory; @Autowired UserService userService; @Autowired VaccineInventoryService inventoryService; @Autowired ConfigurationSettingService settingService; @RequestMapping(value = "periods/{facilityId}/{programId}", method = RequestMethod.GET) //TODO// @PreAuthorize("@permissionEvaluator.hasPermission(principal,'CREATE_REQUISITION, AUTHORIZE_REQUISITION')") public ResponseEntity<OpenLmisResponse> getPeriods(@PathVariable Long facilityId, @PathVariable Long programId, HttpServletRequest request){ return response("periods", service.getPeriodsFor(facilityId, programId, new Date())); } @RequestMapping(value = "view-periods/{facilityId}/{programId}", method = RequestMethod.GET) //TODO// @PreAuthorize("@permissionEvaluator.hasPermission(principal,'CREATE_REQUISITION, AUTHORIZE_REQUISITION')") public ResponseEntity<OpenLmisResponse> getViewPeriods(@PathVariable Long facilityId, @PathVariable Long programId, HttpServletRequest request){ return response("periods", service.getReportedPeriodsFor(facilityId, programId)); } @RequestMapping(value = "initialize/{periodId}/{programId}/{facilityId}") //TODO @PreAuthorize("@permissionEvaluator.hasPermission(principal,'CREATE_REQUISITION, AUTHORIZE_REQUISITION')") public ResponseEntity<OpenLmisResponse> initialize( @PathVariable Long periodId, @PathVariable Long programId, @PathVariable Long facilityId, HttpServletRequest request ){ return response("report", service.initialize(periodId, programId, facilityId, loggedInUserId(request))); } @RequestMapping(value = "initializeEmergency/{periodId}/{programId}/{facilityId}") //TODO @PreAuthorize("@permissionEvaluator.hasPermission(principal,'CREATE_ORDER_REQUISITION)") public ResponseEntity<OpenLmisResponse> initializeEmergency( @PathVariable Long periodId, @PathVariable Long programId, @PathVariable Long facilityId, HttpServletRequest request ){ return response("report", service.initializeEmergency(periodId, programId, facilityId, loggedInUserId(request))); } @RequestMapping(value = "submit") //TODO @PreAuthorize("@permissionEvaluator.hasPermission(principal,'CREATE_ORDER_REQUISITION')") public ResponseEntity<OpenLmisResponse> submit(@RequestBody org.openlmis.vaccine.domain.VaccineOrderRequisition.VaccineOrderRequisition orderRequisition, HttpServletRequest request){ service.submit(orderRequisition, loggedInUserId(request)); return response("report", orderRequisition); } @RequestMapping(value = "save") //TODO @PreAuthorize("@permissionEvaluator.hasPermission(principal,'CREATE_ORDER_REQUISITION')") public ResponseEntity<OpenLmisResponse> save(@RequestBody org.openlmis.vaccine.domain.VaccineOrderRequisition.VaccineOrderRequisition orderRequisition, HttpServletRequest request){ service.save(orderRequisition); return response("report", orderRequisition); } @RequestMapping(value = "lastReport/{facilityId}/{programId}", method = RequestMethod.GET) //TODO @PreAuthorize("@permissionEvaluator.hasPermission(principal,'CREATE_ORDER_REQUISITION')") public ResponseEntity<OpenLmisResponse> getLastReport(@PathVariable Long facilityId,@PathVariable Long programId,HttpServletRequest request){ return response("lastReport", service.getLastReport(facilityId, programId)); } @RequestMapping(value = "get/{id}.json", method = RequestMethod.GET) //TODO @PreAuthorize("@permissionEvaluator.hasPermission(principal,'CREATE_REQUISITION, AUTHORIZE_REQUISITION')") public ResponseEntity<OpenLmisResponse> getReport(@PathVariable Long id, HttpServletRequest request){ return response("report", service.getAllDetailsById(id)); } @RequestMapping(value = "userHomeFacility.json", method = RequestMethod.GET) public ResponseEntity<OpenLmisResponse> getUserHomeFacilities(HttpServletRequest request){ return response("homeFacility", facilityService.getHomeFacility(loggedInUserId(request))); } @RequestMapping(value = "orderRequisitionTest/{id}/print", method = RequestMethod.GET, headers = ACCEPT_PDF) @PostAuthorize("@vaccineOrderRequisitionPermissionService.hasPermission(principal, returnObject.model.get(\"orderRequisition\"), 'VIEW_REQUISITION')") public ModelAndView printOrders(@PathVariable Long id) throws JRException, IOException, ClassNotFoundException { ModelAndView modelAndView = new ModelAndView("vaccineOrderRequisition"); org.openlmis.vaccine.domain.VaccineOrderRequisition.VaccineOrderRequisition requisition = service.getAllDetailsById(id); modelAndView.addObject(VaccineOrderRequisition, requisition); modelAndView.addObject(OrderRequisitionColumns,columnService.getAllColumns()); return modelAndView; } @RequestMapping(value = "getPendingRequest/{facilityId}/{programId}", method = RequestMethod.GET,headers = ACCEPT_JSON) public ResponseEntity<OpenLmisResponse> getPendingRequest(@PathVariable Long facilityId,@PathVariable Long programId,HttpServletRequest request){ return response("pendingRequest", service.getPendingRequest(loggedInUserId(request), facilityId, programId)); } @RequestMapping(value = "getAllBy/{programId}/{periodId}/{facilityId}", method = RequestMethod.GET,headers = ACCEPT_JSON) public ResponseEntity<OpenLmisResponse> getAllBy(@PathVariable Long programId ,@PathVariable Long periodId,@PathVariable Long facilityId,HttpServletRequest request){ return response("requisitionList", service.getAllBy(programId, periodId, facilityId)); } @RequestMapping(value = "updateOrderRequest/{orderId}", method = RequestMethod.PUT,headers = ACCEPT_JSON) //TODO @PreAuthorize("@permissionEvaluator.hasPermission(principal,'CREATE_ORDER_REQUISITION')") public ResponseEntity<OpenLmisResponse> updateORStatus(@PathVariable Long orderId,HttpServletRequest request){ try{ service.updateORStatus(orderId); return success("Saved Successifully"); } catch (DataException e) { return error(e, HttpStatus.BAD_REQUEST); } } @RequestMapping(value = "updateOrderRequisition/{orderId}", method = RequestMethod.PUT,headers = ACCEPT_JSON) public ResponseEntity<OpenLmisResponse> update(@PathVariable Long orderId,@RequestBody org.openlmis.vaccine.domain.VaccineOrderRequisition.VaccineOrderRequisition orderRequisition, HttpServletRequest request){ orderRequisition.setId(orderId); orderRequisition.setStatus(VaccineOrderStatus.ISSUED); service.save(orderRequisition); return response("report", orderRequisition); } @RequestMapping(value = "programs.json", method = RequestMethod.GET) public ResponseEntity<OpenLmisResponse> getProgramsForConfiguration() { return response("programs", programService.getAllIvdPrograms()); } @RequestMapping(value = "loggedInUserDetails.json", method = RequestMethod.GET) public ResponseEntity<OpenLmisResponse> getLoggedInUserProfiles(HttpServletRequest request) { Long userId = loggedInUserId(request); User user = userService.getById(userId); return response("userDetails", user); } @RequestMapping(value = "order-requisition/programs.json", method = RequestMethod.GET) public ResponseEntity<OpenLmisResponse> getProgramFormHomeFacility(HttpServletRequest request) { Long userId = loggedInUserId(request); User user = userService.getById(userId); return response("programs", programService.getProgramsSupportedByUserHomeFacilityWithRights(user.getFacilityId(), userId, "CREATE_REQUISITION", "AUTHORIZE_REQUISITION")); } @RequestMapping(value = "/{programId}", method = GET, headers = ACCEPT_JSON) public ResponseEntity<OpenLmisResponse> getProgramProductsByProgram(@PathVariable Long programId) { List<ProgramProduct> programProductsByProgram = programProductService.getByProgram(new Program(programId)); return response(PROGRAM_PRODUCT_LIST, programProductsByProgram); } @RequestMapping(value = "{id}/print", method = GET, headers = ACCEPT_JSON) public ModelAndView printOrder(@PathVariable Long id) throws JRException, IOException, ClassNotFoundException { Template orPrintTemplate = templateService.getByName(PRINT_ORDER_REQUISITION); JasperReportsMultiFormatView jasperView = jasperReportsViewFactory.getJasperReportsView(orPrintTemplate); Map<String, Object> map = new HashMap<>(); map.put("format", "pdf"); Locale currentLocale = messageService.getCurrentLocale(); map.put(JRParameter.REPORT_LOCALE, currentLocale); ResourceBundle resourceBundle = ResourceBundle.getBundle("messages", currentLocale); map.put(JRParameter.REPORT_RESOURCE_BUNDLE, resourceBundle); Resource reportResource = new ClassPathResource("report"); Resource imgResource = new ClassPathResource("images"); ConfigurationSetting configuration = settingService.getByKey(Constants.OPERATOR_NAME); map.put(Constants.OPERATOR_NAME, configuration.getValue()); String separator = System.getProperty("file.separator"); map.put("image_dir", imgResource.getFile().getAbsolutePath() + separator); map.put("ORDER_ID", id.intValue()); return new ModelAndView(jasperView, map); } @RequestMapping(value = "issue/print", method = GET, headers = ACCEPT_JSON) public ModelAndView printIssueStock() throws JRException, IOException, ClassNotFoundException { Template orPrintTemplate = templateService.getByName(PRINT_ISSUE_STOCK); StockMovement stockMovement = inventoryService.getLastStockMovement(); JasperReportsMultiFormatView jasperView = jasperReportsViewFactory.getJasperReportsView(orPrintTemplate); Map<String, Object> map = new HashMap<>(); map.put("format", "pdf"); Locale currentLocale = messageService.getCurrentLocale(); map.put(JRParameter.REPORT_LOCALE, currentLocale); ResourceBundle resourceBundle = ResourceBundle.getBundle("messages", currentLocale); map.put(JRParameter.REPORT_RESOURCE_BUNDLE, resourceBundle); Resource reportResource = new ClassPathResource("report"); Resource imgResource = new ClassPathResource("images"); ConfigurationSetting configuration = settingService.getByKey(Constants.OPERATOR_NAME); map.put(Constants.OPERATOR_NAME, configuration.getValue()); String separator = System.getProperty("file.separator"); map.put("image_dir", imgResource.getFile().getAbsolutePath() + separator); map.put("ISSUE_ID", stockMovement.getId().intValue()); return new ModelAndView(jasperView, map); } @RequestMapping(value = "search", method = GET,headers = ACCEPT_JSON) @PreAuthorize("@permissionEvaluator.hasPermission(principal,'VIEW_ORDER_REQUISITION')") public ResponseEntity<OpenLmisResponse> searchUser(@RequestParam(value = "facilityId", required = false) Long facilityId, @RequestParam(value = "dateRangeStart", required = false) String dateRangeStart, @RequestParam(value = "dateRangeEnd", required = false) String dateRangeEnd, @RequestParam(value = "programId", required = false) Long programId, VaccineOrderRequisitionSearchCriteria criteria, HttpServletRequest request ) { return response(ORDER_REQUISITION_SEARCH, service.getAllSearchBy(facilityId,dateRangeStart,dateRangeEnd,programId)); } }
VIMS-344:Add java controller for Vaccine Order Requisition
modules/openlmis-web/src/main/java/org/openlmis/web/controller/vaccine/VaccineOrderRequisitionController.java
VIMS-344:Add java controller for Vaccine Order Requisition
<ide><path>odules/openlmis-web/src/main/java/org/openlmis/web/controller/vaccine/VaccineOrderRequisitionController.java <ide> import org.openlmis.reporting.model.Template; <ide> import org.openlmis.reporting.service.JasperReportsViewFactory; <ide> import org.openlmis.reporting.service.TemplateService; <del>import org.openlmis.vaccine.domain.VaccineOrderRequisition.VaccineOrderRequisitionSearchCriteria; <ide> import org.openlmis.vaccine.domain.VaccineOrderRequisition.VaccineOrderStatus; <ide> import org.openlmis.vaccine.domain.inventory.StockMovement; <ide> import org.openlmis.vaccine.service.Inventory.VaccineInventoryService; <ide> import org.openlmis.vaccine.service.VaccineOrderRequisitionServices.VaccineOrderRequisitionService; <ide> import org.openlmis.vaccine.service.VaccineOrderRequisitionServices.VaccineOrderRequisitionsColumnService; <ide> import org.springframework.beans.factory.annotation.Autowired; <del>import org.springframework.beans.factory.annotation.Value; <ide> import org.springframework.core.io.ClassPathResource; <ide> import org.springframework.core.io.Resource; <ide> import org.springframework.http.HttpStatus; <ide> import org.springframework.web.servlet.ModelAndView; <ide> import org.springframework.web.servlet.view.jasperreports.JasperReportsMultiFormatView; <ide> <del>import javax.imageio.ImageIO; <ide> import javax.servlet.http.HttpServletRequest; <del>import java.awt.image.BufferedImage; <ide> import java.io.IOException; <del>import java.text.ParseException; <del>import java.text.SimpleDateFormat; <ide> import java.util.*; <del> <del>import static java.lang.Integer.parseInt; <ide> import static org.openlmis.core.web.OpenLmisResponse.error; <ide> import static org.openlmis.core.web.OpenLmisResponse.response; <ide> import static org.openlmis.core.web.OpenLmisResponse.success; <ide> import static org.springframework.web.bind.annotation.RequestMethod.GET; <del>import static java.lang.System.out; <ide> <ide> <ide> @Controller <ide> @RequestParam(value = "dateRangeEnd", required = false) String dateRangeEnd, <ide> @RequestParam(value = "programId", required = false) Long programId, <ide> <del> VaccineOrderRequisitionSearchCriteria criteria, HttpServletRequest request <add> HttpServletRequest request <ide> ) { <del> <ide> return response(ORDER_REQUISITION_SEARCH, service.getAllSearchBy(facilityId,dateRangeStart,dateRangeEnd,programId)); <ide> <ide> }
Java
agpl-3.0
e9ccdcfbbec96da6379286a5a090e0f7fff33ff1
0
Maximvdw/mcMMO,jhonMalcom79/mcMMO_pers,virustotalop/mcMMO,EvilOlaf/mcMMO,isokissa3/mcMMO
package com.gmail.nossr50.commands.mc; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.commands.CommandHelper; import com.gmail.nossr50.config.Config; import com.gmail.nossr50.datatypes.PlayerProfile; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.util.Users; public class McremoveCommand implements CommandExecutor { private final String location; private final mcMMO plugin; public McremoveCommand (mcMMO plugin) { this.plugin = plugin; this.location = mcMMO.usersFile; } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { String playerName; String tablePrefix = Config.getInstance().getMySQLTablePrefix(); String databaseName = Config.getInstance().getMySQLDatabaseName(); String usage = ChatColor.RED + "Proper usage is /mcremove <player>"; //TODO: Needs more locale. String success; if (CommandHelper.noCommandPermissions(sender, "mcmmo.tools.mcremove")) { return true; } switch (args.length) { case 1: playerName = args[0]; success = ChatColor.GREEN + playerName + " was successfully removed from the database!"; //TODO: Locale break; default: sender.sendMessage(usage); return true; } /* MySQL */ if (Config.getInstance().getUseMySQL()) { int userId = 0; userId = mcMMO.database.getInt("SELECT id FROM " + tablePrefix + "users WHERE user = '" + playerName + "'"); if (userId > 0) { mcMMO.database.write("DELETE FROM " + databaseName + "." + tablePrefix + "users WHERE " + tablePrefix + "users.id=" + userId); mcMMO.database.write("DELETE FROM " + databaseName + "." + tablePrefix + "cooldowns WHERE " + tablePrefix + "cooldowns.user_id=" + userId); mcMMO.database.write("DELETE FROM " + databaseName + "." + tablePrefix + "huds WHERE " + tablePrefix + "huds.user_id=" + userId); mcMMO.database.write("DELETE FROM " + databaseName + "." + tablePrefix + "skills WHERE " + tablePrefix + "skills.user_id=" + userId); mcMMO.database.write("DELETE FROM " + databaseName + "." + tablePrefix + "experience WHERE " + tablePrefix + "experience.user_id=" + userId); sender.sendMessage(success); } else { sender.sendMessage(LocaleLoader.getString("Commands.DoesNotExist")); } } else { if (removeFlatFileUser(playerName)) { sender.sendMessage(success); } else { sender.sendMessage(LocaleLoader.getString("Commands.DoesNotExist")); } } //Force PlayerProfile stuff to update OfflinePlayer player = plugin.getServer().getOfflinePlayer(playerName); PlayerProfile playerProfile = Users.getProfile(player); if (playerProfile != null) { Users.removeUser(playerProfile); if (player.isOnline()) { Users.addUser((Player) player); } } return true; } private boolean removeFlatFileUser(String playerName) { boolean worked = false; try { FileReader file = new FileReader(location); BufferedReader in = new BufferedReader(file); StringBuilder writer = new StringBuilder(); String line = ""; while ((line = in.readLine()) != null) { /* Write out the same file but when we get to the player we want to remove, we skip his line. */ if (!line.split(":")[0].equalsIgnoreCase(playerName)) { writer.append(line).append("\r\n"); } else { System.out.println("User found, removing..."); worked = true; continue; //Skip the player } } in.close(); FileWriter out = new FileWriter(location); //Write out the new file out.write(writer.toString()); out.close(); return worked; } catch (Exception e) { plugin.getLogger().severe("Exception while reading " + location + " (Are you sure you formatted it correctly?)" + e.toString()); return worked; } } }
src/main/java/com/gmail/nossr50/commands/mc/McremoveCommand.java
package com.gmail.nossr50.commands.mc; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.commands.CommandHelper; import com.gmail.nossr50.config.Config; import com.gmail.nossr50.datatypes.PlayerProfile; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.util.Users; public class McremoveCommand implements CommandExecutor { private final String location; private final mcMMO plugin; public McremoveCommand (mcMMO plugin) { this.plugin = plugin; this.location = mcMMO.usersFile; } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { String playerName; String tablePrefix = Config.getInstance().getMySQLTablePrefix(); String databaseName = Config.getInstance().getMySQLDatabaseName(); String usage = ChatColor.RED + "Proper usage is /mcremove <player>"; //TODO: Needs more locale. String success; if (CommandHelper.noCommandPermissions(sender, "mcmmo.tools.mcremove")) { return true; } switch (args.length) { case 1: playerName = args[0]; success = ChatColor.GREEN + playerName + "was successfully removed from the database!"; //TODO: Locale break; default: sender.sendMessage(usage); return true; } /* MySQL */ if (Config.getInstance().getUseMySQL()) { int userId = 0; userId = mcMMO.database.getInt("SELECT id FROM " + tablePrefix + "users WHERE user = '" + playerName + "'"); if (userId > 0) { mcMMO.database.write("DELETE FROM " + databaseName + "." + tablePrefix + "users WHERE " + tablePrefix + "users.id=" + userId); mcMMO.database.write("DELETE FROM " + databaseName + "." + tablePrefix + "cooldowns WHERE " + tablePrefix + "cooldowns.user_id=" + userId); mcMMO.database.write("DELETE FROM " + databaseName + "." + tablePrefix + "huds WHERE " + tablePrefix + "huds.user_id=" + userId); mcMMO.database.write("DELETE FROM " + databaseName + "." + tablePrefix + "skills WHERE " + tablePrefix + "skills.user_id=" + userId); mcMMO.database.write("DELETE FROM " + databaseName + "." + tablePrefix + "experience WHERE " + tablePrefix + "experience.user_id=" + userId); sender.sendMessage(success); } else { sender.sendMessage(LocaleLoader.getString("Commands.DoesNotExist")); } } else { if (removeFlatFileUser(playerName)) { sender.sendMessage(success); } else { sender.sendMessage(LocaleLoader.getString("Commands.DoesNotExist")); } } //Force PlayerProfile stuff to update OfflinePlayer player = plugin.getServer().getOfflinePlayer(playerName); PlayerProfile playerProfile = Users.getProfile(player); if (playerProfile != null) { Users.removeUser(playerProfile); if (player.isOnline()) { Users.addUser((Player) player); } } return true; } private boolean removeFlatFileUser(String playerName) { boolean worked = false; try { FileReader file = new FileReader(location); BufferedReader in = new BufferedReader(file); StringBuilder writer = new StringBuilder(); String line = ""; while ((line = in.readLine()) != null) { /* Write out the same file but when we get to the player we want to remove, we skip his line. */ if (!line.split(":")[0].equalsIgnoreCase(playerName)) { writer.append(line).append("\r\n"); } else { System.out.println("User found, removing..."); worked = true; continue; //Skip the player } } in.close(); FileWriter out = new FileWriter(location); //Write out the new file out.write(writer.toString()); out.close(); return worked; } catch (Exception e) { plugin.getLogger().severe("Exception while reading " + location + " (Are you sure you formatted it correctly?)" + e.toString()); return worked; } } }
Missing space!
src/main/java/com/gmail/nossr50/commands/mc/McremoveCommand.java
Missing space!
<ide><path>rc/main/java/com/gmail/nossr50/commands/mc/McremoveCommand.java <ide> switch (args.length) { <ide> case 1: <ide> playerName = args[0]; <del> success = ChatColor.GREEN + playerName + "was successfully removed from the database!"; //TODO: Locale <add> success = ChatColor.GREEN + playerName + " was successfully removed from the database!"; //TODO: Locale <ide> break; <ide> <ide> default:
Java
bsd-3-clause
0739355448db5bdaf471252cbfafae566d9780ed
0
TheFakeMontyOnTheRun/liboldfart
package br.odb.liboldfart; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import br.odb.libstrip.GeneralPolygon; import br.odb.libstrip.Material; import br.odb.libstrip.Mesh; import br.odb.utils.Color; import br.odb.utils.math.Vec3; public class WavefrontOBJLoader { private String buffer = ""; final private ArrayList<Mesh> meshList = new ArrayList<Mesh>(); final private HashMap< String, Material> materials = new HashMap<String, Material>(); private Mesh mesh; private List< Vec3 > vertexes = new ArrayList< Vec3 >(); private int lastIndex; private Material currentMaterial; private void parseMaterialList(InputStream fis) { Material[] list = parseMaterials(fis); for( Material m : list ) { System.out.println( "registering material:" + m.name ); this.materials.put( m.name, m ); } } private static Material[] parseMaterials(InputStream fis) { ArrayList<Material> materials = new ArrayList<Material>(); Material[] toReturn; String line = ""; String opcode; String op1; Material m = null; Color c = null; String[] subToken; try { BufferedReader bis = new BufferedReader(new InputStreamReader(fis)); while (bis.ready()) { try { line = bis.readLine(); subToken = line.split( "[ ]+" ); if (line != null && line.length() > 0 && line.charAt(0) != '#') { opcode = subToken[ 0 ]; if (opcode.equals("newmtl")) { op1 = subToken[ 1 ]; System.out .println(" reading definition for material: " + op1); m = new Material(op1, "", "", "" ); materials.add(m); } if (opcode.equals("Kd") && m != null) { int r = (int) (255 * Float.parseFloat(subToken[ 1 ])); int g = (int) (255 * Float.parseFloat(subToken[ 2 ])); int b = (int) (255 * Float.parseFloat(subToken[ 3 ])); c = new Color(r, g, b); m.mainColor.set(c); System.out.println("got color " + c + " for material " + m.name); } } } catch (Exception e) { e.printStackTrace(); return null; } } } catch (Exception e) { e.printStackTrace(); } if (materials.size() > 0) { System.out.println("materials: " + materials.size()); for (int d = 0; d < materials.size(); ++d) { System.out.println("material(" + d + "): " + materials.get(d) + " name = " + materials.get(d).name); } toReturn = new Material[materials.size()]; materials.toArray(toReturn); return toReturn; } else return null; } private void parseLine(String line ) { Vec3 v; String[] subToken = line.split( "[ ]+" ); switch (line.charAt(0)) { case 'u': currentMaterial = materials.get( subToken[ 1 ] ); System.out.println("now using material: " + currentMaterial.name + " for mesh " + mesh.name ); mesh.material = currentMaterial; break; case 'v': v = new Vec3(Float.parseFloat( subToken[ 1 ] ), Float.parseFloat( subToken[ 3 ] ), Float.parseFloat( subToken[ 2 ] ) ); vertexes.add(v); System.out.println("v: " + v); break; case 'o': System.out.println("reading " + line.substring(2)); lastIndex += vertexes.size(); mesh = new Mesh(line.substring(2)); meshList.add(mesh); vertexes.clear(); break; case 'f': String token = ""; String last = line.substring(1).trim(); GeneralPolygon poly = new GeneralPolygon(); while (last.length() > 0) { if (last.indexOf(' ') != -1) { token = last.substring(0, last.indexOf(' ')).trim(); last = last.substring(last.indexOf(' ') + 1).trim(); } else { token = last.trim(); last = ""; } System.out.println(":" + token); int integer = Integer.parseInt(token); poly.addIndex(integer - lastIndex - 1); } System.out.println("---"); mesh.faces.add(poly); break; } } public ArrayList<Mesh> loadMeshes( String meshName, InputStream fis, InputStream materialData) { buffer = " "; String mybuffer = ""; String line; parseMaterialList(materialData); try { BufferedReader bis = new BufferedReader(new InputStreamReader(fis)); while (bis.ready()) { line = bis.readLine(); if (line != null && line.length() > 0 && line.charAt(0) != '#') mybuffer += line + "\n"; } } catch (Exception e) { } buffer = mybuffer; lastIndex = 0; mesh = new Mesh(meshName); meshList.add(mesh); currentMaterial = null; while (buffer.length() > 0) { line = buffer.substring(0, buffer.indexOf('\n')); buffer = buffer.substring(buffer.indexOf('\n') + 1); parseLine( line ); } return meshList; } }
src/main/java/br/odb/liboldfart/WavefrontOBJLoader.java
package br.odb.liboldfart; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import br.odb.libstrip.GeneralPolygon; import br.odb.libstrip.Material; import br.odb.libstrip.Mesh; import br.odb.utils.Color; import br.odb.utils.math.Vec3; public class WavefrontOBJLoader { private String buffer = ""; final private ArrayList<Mesh> meshList = new ArrayList<Mesh>(); final private HashMap< String, Material> materials = new HashMap<String, Material>(); private Mesh mesh; private int lastIndex; private Material currentMaterial; private void parseMaterialList(InputStream fis) { Material[] list = parseMaterials(fis); for( Material m : list ) { System.out.println( "registering material:" + m.name ); this.materials.put( m.name, m ); } } private static Material[] parseMaterials(InputStream fis) { ArrayList<Material> materials = new ArrayList<Material>(); Material[] toReturn; String line = ""; String opcode; String op1; Material m = null; Color c = null; String[] subToken; try { BufferedReader bis = new BufferedReader(new InputStreamReader(fis)); while (bis.ready()) { try { line = bis.readLine(); subToken = line.split( "[ ]+" ); if (line != null && line.length() > 0 && line.charAt(0) != '#') { opcode = subToken[ 0 ]; if (opcode.equals("newmtl")) { op1 = subToken[ 1 ]; System.out .println(" reading definition for material: " + op1); m = new Material(op1, "", "", "" ); materials.add(m); } if (opcode.equals("Kd") && m != null) { int r = (int) (255 * Float.parseFloat(subToken[ 1 ])); int g = (int) (255 * Float.parseFloat(subToken[ 2 ])); int b = (int) (255 * Float.parseFloat(subToken[ 3 ])); c = new Color(r, g, b); m.mainColor.set(c); System.out.println("got color " + c + " for material " + m.name); } } } catch (Exception e) { e.printStackTrace(); return null; } } } catch (Exception e) { e.printStackTrace(); } if (materials.size() > 0) { System.out.println("materials: " + materials.size()); for (int d = 0; d < materials.size(); ++d) { System.out.println("material(" + d + "): " + materials.get(d) + " name = " + materials.get(d).name); } toReturn = new Material[materials.size()]; materials.toArray(toReturn); return toReturn; } else return null; } private void parseLine(String line ) { Vec3 v; String[] subToken = line.split( "[ ]+" ); switch (line.charAt(0)) { case 'u': currentMaterial = materials.get( subToken[ 1 ] ); System.out.println("now using material: " + currentMaterial.name + " for mesh " + mesh.name ); mesh.material = currentMaterial; break; case 'v': v = new Vec3(Float.parseFloat( subToken[ 1 ] ), Float.parseFloat( subToken[ 3 ] ), Float.parseFloat( subToken[ 2 ] ) ); mesh.points.add(v); System.out.println("v: " + v); break; case 'o': System.out.println("reading " + line.substring(2)); lastIndex += mesh.points.size(); mesh = new Mesh(line.substring(2)); meshList.add(mesh); break; case 'f': String token = ""; String last = line.substring(1).trim(); GeneralPolygon poly = new GeneralPolygon(); while (last.length() > 0) { if (last.indexOf(' ') != -1) { token = last.substring(0, last.indexOf(' ')).trim(); last = last.substring(last.indexOf(' ') + 1).trim(); } else { token = last.trim(); last = ""; } System.out.println(":" + token); int integer = Integer.parseInt(token); poly.addIndex(integer - lastIndex - 1); } System.out.println("---"); mesh.faces.add(poly); break; } } public ArrayList<Mesh> loadMeshes( String meshName, InputStream fis, InputStream materialData) { buffer = " "; String mybuffer = ""; String line; parseMaterialList(materialData); try { BufferedReader bis = new BufferedReader(new InputStreamReader(fis)); while (bis.ready()) { line = bis.readLine(); if (line != null && line.length() > 0 && line.charAt(0) != '#') mybuffer += line + "\n"; } } catch (Exception e) { } buffer = mybuffer; lastIndex = 0; mesh = new Mesh(meshName); meshList.add(mesh); currentMaterial = null; while (buffer.length() > 0) { line = buffer.substring(0, buffer.indexOf('\n')); buffer = buffer.substring(buffer.indexOf('\n') + 1); parseLine( line ); } return meshList; } }
WIP - refactoring Hate to commit WIP, but I have to switch machines
src/main/java/br/odb/liboldfart/WavefrontOBJLoader.java
WIP - refactoring
<ide><path>rc/main/java/br/odb/liboldfart/WavefrontOBJLoader.java <ide> import java.io.InputStreamReader; <ide> import java.util.ArrayList; <ide> import java.util.HashMap; <add>import java.util.List; <ide> <ide> import br.odb.libstrip.GeneralPolygon; <ide> import br.odb.libstrip.Material; <ide> final private ArrayList<Mesh> meshList = new ArrayList<Mesh>(); <ide> final private HashMap< String, Material> materials = new HashMap<String, Material>(); <ide> private Mesh mesh; <add> private List< Vec3 > vertexes = new ArrayList< Vec3 >(); <ide> private int lastIndex; <ide> private Material currentMaterial; <ide> <ide> String[] subToken = line.split( "[ ]+" ); <ide> <ide> switch (line.charAt(0)) { <add> <ide> case 'u': <ide> <ide> currentMaterial = materials.get( subToken[ 1 ] ); <ide> Float.parseFloat( subToken[ 3 ] ), <ide> Float.parseFloat( subToken[ 2 ] ) ); <ide> <del> mesh.points.add(v); <add> <add> <add> vertexes.add(v); <ide> <ide> System.out.println("v: " + v); <del> <del> break; <add> break; <add> <ide> case 'o': <ide> System.out.println("reading " + line.substring(2)); <del> lastIndex += mesh.points.size(); <add> lastIndex += vertexes.size(); <ide> mesh = new Mesh(line.substring(2)); <ide> meshList.add(mesh); <del> break; <add> vertexes.clear(); <add> break; <add> <ide> case 'f': <ide> String token = ""; <ide> String last = line.substring(1).trim();
Java
lgpl-2.1
943b9ce3ed65a28e24a9e0dce4a78f76ccca335e
0
viktorbahr/jaer,viktorbahr/jaer,SensorsINI/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer,viktorbahr/jaer,SensorsINI/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer
/* * Goalie.java * * Created on July 5, 2006, 1:17 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. * * *Copyright July 5, 2006 Tobi Delbruck, Inst. of Neuroinformatics, UNI-ETH Zurich */ package ch.unizh.ini.tobi.goalie; import ch.unizh.ini.caviar.JAERViewer; import ch.unizh.ini.caviar.aemonitor.AEConstants; import ch.unizh.ini.caviar.chip.*; import ch.unizh.ini.caviar.event.EventPacket; import ch.unizh.ini.caviar.eventprocessing.EventFilter2D; import ch.unizh.ini.caviar.eventprocessing.FilterChain; import ch.unizh.ini.caviar.eventprocessing.filter.XYTypeFilter; import ch.unizh.ini.caviar.eventprocessing.tracking.RectangularClusterTracker; import ch.unizh.ini.caviar.graphics.FrameAnnotater; import ch.unizh.ini.caviar.hardwareinterface.*; import ch.unizh.ini.caviar.hardwareinterface.ServoInterface; import ch.unizh.ini.caviar.hardwareinterface.usb.ServoTest; import ch.unizh.ini.caviar.hardwareinterface.usb.SiLabsC8051F320_USBIO_ServoController; import ch.unizh.ini.caviar.util.filter.LowpassFilter; import ch.unizh.ini.tobi.goalie.ServoArm; import com.sun.opengl.util.*; import java.awt.Color; import java.awt.Graphics2D; import java.awt.geom.Point2D; import java.io.*; import java.util.*; import java.util.ArrayList; import java.util.Observable; import java.util.Observer; import java.util.logging.Level; import java.util.prefs.Preferences; import javax.media.opengl.*; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.glu.*; /** * Controls a servo motor that swings an arm in the way of a ball rolling towards a goal box. * Calibrates itself as well. * * @author tGoalielbruck/manuel lang */ public class Goalie extends EventFilter2D implements FrameAnnotater, Observer{ final String LOGGING_FILENAME="goalie.csv"; private boolean useVelocityForGoalie=getPrefs().getBoolean("Goalie.useVelocityForGoalie",true); {setPropertyTooltip("useVelocityForGoalie","uses ball velocity to calc impact position");} private int minPathPointsToUseVelocity=getPrefs().getInt("Goalie.minPathPointsToUseVelocity",10); {setPropertyTooltip("minPathPointsToUseVelocity","only after path has this many points is velocity used to predict path");} private long lastServoPositionTime=0; // used to relax servos after inactivity private int relaxationDelayMs=getPrefs().getInt("Goalie.relaxationDelayMs",500); {setPropertyTooltip("relaxationDelayMs","time [ms] before goalie first relaxes to middle after a movement. Goalie sleeps sleepDelaySec after this.\n");} private int sleepDelaySec=getPrefs().getInt("Goalie.sleepDelaySec",20); {setPropertyTooltip("sleepDelaySec","time [sec] before goalie sleeps");} private long learnDelayMS = getPrefs().getLong("Goalie.learnTimeMs",60000); {setPropertyTooltip("learnDelayMS","time [ms] of no balls present before a new learning cycle starts ");} private float wakeupBallDistance=getPrefs().getFloat("Goalie.wakeupBallDistance",.25f); {setPropertyTooltip("wakeupBallDistance","fraction of vertical image that ball must travel to wake up from SLEEP state");} RectangularClusterTracker tracker; volatile RectangularClusterTracker.Cluster ball=null; final Object ballLock = new Object(); private int armRows=getPrefs().getInt("Goalie.pixelsToEdgeOfGoal",40); {setPropertyTooltip("armRows","arm and ball tracking separation line position [pixels]");} private int pixelsToTipOfArm=getPrefs().getInt("Goalie.pixelsToTipOfArm",32); {setPropertyTooltip("pixelsToTipOfArm","defines distance in rows from bottom of image to tip of arm, used for computing arm position [pixels]");} private boolean useSoonest=getPrefs().getBoolean("Goalie.useSoonest",false); // use soonest ball rather than closest {setPropertyTooltip("useSoonest","react on soonest ball first");} // possible states, ACTIVE meaning blocking ball we can see, // RELAXED is between blocks // SLEEPING is after there have not been any definite balls for a while and we are waiting for a clear ball directed // at the goal before we start blocking again. This reduces annoyance factor due to background mStatent at top of scene. private enum State {ACTIVE, RELAXED, SLEEPING}; private State state=State.SLEEPING; // initial state private int topRowsToIgnore=getPrefs().getInt("Goalie.topRowsToIgnore",0); // balls here are ignored (hands) {setPropertyTooltip("topRowsToIgnore","top rows in scene to ignore for purposes of active ball blocking (balls are still tracked there)");} private int rangeOutsideViewToBlockPixels=getPrefs().getInt("Goalie.rangeOutsideViewToBlockPixels",30); // we only block shots that are this much outside scene, to avoid reacting continuously to people moving around laterally {setPropertyTooltip("rangeOutsideViewToBlockPixels","goalie will ignore balls that are more than this many pixels outside goal line");} //Arm control private ServoArm servoArm; private XYTypeFilter xYFilter; //FilterChain for GUI FilterChain trackingFilterChain; /** * Creates a Goaliestance of Goalie */ public Goalie(AEChip chip) { super(chip); chip.addObserver(this); //build hierachy trackingFilterChain = new FilterChain(chip); tracker=new RectangularClusterTracker(chip); servoArm = new ServoArm(chip); xYFilter = new XYTypeFilter(chip); trackingFilterChain.add(tracker); trackingFilterChain.add(servoArm); setEnclosedFilterChain(trackingFilterChain); tracker.setEnclosedFilter(xYFilter); tracker.setEnclosed(true, this); servoArm.setEnclosed(true, this); xYFilter.setEnclosed(true, tracker); // only top filter xYFilter.setXEnabled(true); xYFilter.setYEnabled(true); xYFilter.setTypeEnabled(false); xYFilter.setStartY(armRows); servoArm.initFilter(); servoArm.setCaptureRange(0,0, 128, armRows); chip.getCanvas().addAnnotator(this); initFilter(); } private float lastBallCrossingX=Float.NaN; // used for logging synchronized public EventPacket<?> filterPacket(EventPacket<?> in) { if(!isFilterEnabled()) return in; tracker.filterPacket(in); servoArm.filterPacket(in); synchronized (ballLock) { ball=getPutativeBallCluster(); // whether ball is returned also depends on state, if sleeping, harder to get one checkToRelax(ball); } switch(state){ case ACTIVE: case RELAXED: case SLEEPING: // not enough time has passed to relax and we might have a ball if(ball==null){ lastBallCrossingX=Float.NaN; }else if(ball.isVisible()){ // check for null because ball seems to disappear on us when using processOnAcquisition mode (realtime mode) // we have a ball, so move servo to position needed. // compute intersection of velocity vector of ball with bottom of view. // this is the place we should put the goalie. // this is computed from time to reach bottom (y/vy) times vx plus the x location. // we also include a parameter pixelsToTipOfArm which is where the goalie arm is in the field of view if(JAERViewer.globalTime1 == 0) JAERViewer.globalTime1 = System.nanoTime(); lastBallCrossingX=getBallCrossingGoalPixel(ball); float x=lastBallCrossingX; if(x>=-rangeOutsideViewToBlockPixels && x<=chip.getSizeX()+rangeOutsideViewToBlockPixels){ // only block balls that are blockable.... servoArm.setPosition((int)x); lastServoPositionTime=System.currentTimeMillis(); checkToRelax_state = 0; //next time idle move arm back to middle state = state.ACTIVE; // we just moved the arm } }else{ // ball not null but not visible yet to goalie } break; } logGoalie(in); return in; } private float getBallCrossingGoalPixel(RectangularClusterTracker.Cluster ball){ if(ball==null) throw new RuntimeException("null ball, shouldn't happen"); float x=(float)ball.location.x; if(useVelocityForGoalie && ball.isVelocityValid() && ball.getPath().size()>=minPathPointsToUseVelocity){ Point2D.Float v=ball.getVelocityPPS(); double v2=v.x*v.x+v.y+v.y; if(v.y<0 /*&& v2>MIN_BALL_SPEED_TO_USE_PPS2*/){ // don't use vel unless ball is rolling towards goal // we need minus sign here because vel.y is negative x-=(float)(ball.location.y-pixelsToTipOfArm)/v.y*v.x; } } return x; } RectangularClusterTracker.Cluster oldBall=null; long lastDefiniteBallTime=0; // final int DEFINITE_BALL_LIFETIME_US=300000; /** * Gets the putative ball cluster. This method applies rules to determine the most likely ball cluster. * Returns null if there is no ball. * * @return ball with min y, assumed closest to viewer. This should filter out a lot of hands that roll the ball towards the goal. * If useVelocityForGoalie is true, then the ball ball must also be moving towards the goal. If useSoonest is true, then the ball * that will first cross the goal line, based on ball y velocity, will be returned. */ private RectangularClusterTracker.Cluster getPutativeBallCluster(){ if(tracker.getNumClusters()==0) return null; float minDistance=Float.POSITIVE_INFINITY, f, minTimeToImpact=Float.POSITIVE_INFINITY; RectangularClusterTracker.Cluster closest=null, soonest=null; for(RectangularClusterTracker.Cluster c:tracker.getClusters()){ if( c.isVisible()){ // cluster must be visible if(!useSoonest){ // compute nearest cluster if((f=(float)c.location.y) < minDistance ) { if( (!useVelocityForGoalie) || (useVelocityForGoalie && c.getVelocityPPS().y<=0)){ // give closest ball unconditionally if not using ball velocity // but if using velocity, then only give ball if it is moving towards goal minDistance=f; closest=c; // will it hit earlier? } } }else{ // use soonest to hit float t=computeTimeToImpactMs(c); if(t<minTimeToImpact) { soonest=c; minTimeToImpact=t; } } } // visible } RectangularClusterTracker.Cluster returnBall; if(useSoonest) returnBall= soonest; else returnBall= closest; if(returnBall!=null && returnBall.location.y>chip.getSizeY()-topRowsToIgnore) return null; // if we are SLEEPING then don't return a ball unless it is definitely one // if we detect a definite ball then we remember the time we saw it and only sleep after // SLEEP_DELAY_MS has passed since we saw a real ball if(returnBall!=null && /*returnBall.getLifetime()>DEFINITE_BALL_LIFETIME_US &&*/ returnBall.getDistanceYFromBirth()< -chip.getMaxSize()*getWakeupBallDistance()){ lastDefiniteBallTime=System.currentTimeMillis(); // we definitely got a real ball }else{ if(state==state.SLEEPING) returnBall=null; } return returnBall; } // getPutativeBallCluster /** @return time in ms to impact of cluster with goal line * @see #pixelsToEdgeOfGoal */ private float computeTimeToImpactMs(RectangularClusterTracker.Cluster cluster){ if(cluster==null){ log.warning("passed null cluster to getTimeToImpactMs"); return Float.POSITIVE_INFINITY; } float y=cluster.location.y; float dy=cluster.getVelocityPPS().y; // velocity of cluster in pixels per second if(dy>=0) return Float.POSITIVE_INFINITY; dy=dy/(AEConstants.TICK_DEFAULT_US*1e-6f); float dt=-1000f*(y-pixelsToTipOfArm)/dy; return dt; } /*private float applyGain(float f){ return .5f+(f-.5f)*gain; }*/ public Object getFilterState() { return null; } public void resetFilter() { tracker.resetFilter(); } /** initializes arm lowpass filter */ public void initFilter() { servoArm.setCaptureRange(0,0, chip.getSizeX(), armRows); } @Override synchronized public void setFilterEnabled(boolean yes){ super.setFilterEnabled(yes); if(!yes && loggingWriter!=null){ loggingWriter.close(); loggingWriter=null; } } /** not used */ public void annotate(float[][][] frame) { } /** not used */ public void annotate(Graphics2D g) { } GLUquadric ballQuad; GLU glu; float[] ballColor=new float[3]; public void annotate(GLAutoDrawable drawable) { if(!isFilterEnabled() ) return; tracker.annotate(drawable); // if(isRelaxed) return; GL gl=drawable.getGL(); gl.glPushMatrix(); float x=0.0f,y=0.0f,radius=0.0f; synchronized(ballLock){ if(ball != null) { ball.getColor().getRGBColorComponents(ballColor); x=ball.location.x; y=ball.location.y; radius=ball.getRadius(); } } if(glu==null) glu=new GLU(); if(ballQuad==null) ballQuad = glu.gluNewQuadric(); gl.glColor3fv(ballColor,0); gl.glPushMatrix(); gl.glTranslatef(x,y,0); glu.gluQuadricDrawStyle(ballQuad,GLU.GLU_FILL); glu.gluDisk(ballQuad,radius-1,radius+1.,16,1); gl.glPopMatrix(); float f=servoArm.getDesiredPosition(); // draw desired position of arm in color of ball being blocked gl.glRectf(f-8,pixelsToTipOfArm+2,f+8,pixelsToTipOfArm-1); gl.glColor3d(0.8,0.8,0.8); f = servoArm.getActualPosition(); // draw actual tracked position of arm in light grey gl.glRectf(f-6,pixelsToTipOfArm+2,f+6,pixelsToTipOfArm-1); gl.glPopMatrix(); // show state of Goalie (arm shows its own state) gl.glPushMatrix(); int font = GLUT.BITMAP_HELVETICA_18; gl.glRasterPos3f(chip.getSizeX() / 2-15, 7,0); // annotate the cluster with the arm state, e.g. relaxed or learning chip.getCanvas().getGlut().glutBitmapString(font, state.toString()); gl.glPopMatrix(); } public boolean isUseVelocityForGoalie() { return useVelocityForGoalie; } /** Sets whether the goalie uses the ball velocity or just the position * @param useVelocityForGoalie true to use ball velocity */ public void setUseVelocityForGoalie(boolean useVelocityForGoalie) { this.useVelocityForGoalie = useVelocityForGoalie; getPrefs().putBoolean("Goalie.useVelocityForGoalie",useVelocityForGoalie); } public int getRelaxationDelayMs() { return relaxationDelayMs; } /** sets the delay after all targets disappear that the goalie relaxes * @param relaxationDelayMs delay in ms */ public void setRelaxationDelayMs(int relaxationDelayMs) { this.relaxationDelayMs = relaxationDelayMs; getPrefs().putInt("Goalie.relaxationDelayMs",relaxationDelayMs); } private int checkToRelax_state = 0; // goalie goes to sleep after sleepDelaySec since last definite ball private final int RELAXED_POSITION_DELAY_MS=200; // ms to get to middle relaxed position private void checkToRelax(RectangularClusterTracker.Cluster ball){ // if enough time has passed AND there is no visible ball, then relax servo long timeSinceLastPosition=System.currentTimeMillis()- lastServoPositionTime; if( state==State.ACTIVE && (ball==null || !ball.isVisible()) && timeSinceLastPosition > relaxationDelayMs && checkToRelax_state == 0 ){ servoArm.setPosition(chip.getSizeX() / 2); state = state.RELAXED; checkToRelax_state = 1; // printState(); } // after relaxationDelayMs position to middle for next ball. if( state == State.RELAXED && (timeSinceLastPosition > relaxationDelayMs+RELAXED_POSITION_DELAY_MS) // wait for arm to get to middle && checkToRelax_state == 1) { servoArm.relax(); // turn off servo (if it is one that turns off when you stop sending pulses) checkToRelax_state = 2; // printState(); } // if we have relaxed to the middle and sufficient time has gone by since we got a ball, then we go to sleep state where its harder // to get a ball if(state==State.RELAXED && checkToRelax_state==2 && (System.currentTimeMillis()-lastDefiniteBallTime)>sleepDelaySec*1000){ state=State.SLEEPING; // printState(); } // if we've been relaxed a really long time start recalibrating if( state == State.SLEEPING && (timeSinceLastPosition > getLearnDelayMS())) { servoArm.startLearning(); lastServoPositionTime = System.currentTimeMillis(); // printState(); } } private void printState(){ log.info(state+" checkToRelax_state="+checkToRelax_state); } public boolean isUseSoonest() { return useSoonest; } /** If true, then goalie uses ball that will hit soonest. If false, goalie uses ball that is closest to goal. * @see #setUseVelocityForGoalie * @param useSoonest true to use soonest threat, false to use closest threat */ public void setUseSoonest(boolean useSoonest) { this.useSoonest = useSoonest; getPrefs().putBoolean("Goalie.useSoonest",useSoonest); } public int getTopRowsToIgnore() { return topRowsToIgnore; } public void setTopRowsToIgnore(int topRowsToIgnore) { if(topRowsToIgnore>chip.getSizeY()) topRowsToIgnore=chip.getSizeY(); this.topRowsToIgnore = topRowsToIgnore; getPrefs().putInt("Goalie.topRowsToIgnore",topRowsToIgnore); } public int getArmRows() { return armRows; } /** Defines the number of retina rows from bottom of image to tip of goalie arm to define tracking region for arm. *If this is too small then the arm will be tracked as balls, greatly confusing things. * Constrained to range 0-chip.getSizeY()/2. * @param armRows the number of rows of pixels */ public void setArmRows(int armRows) { if(armRows<0) armRows=0; else if(armRows>chip.getSizeY()/2) armRows=chip.getSizeY()/2; this.armRows = armRows; ((XYTypeFilter) tracker.getEnclosedFilter()).setStartY(armRows); servoArm.setCaptureRange(0, 0, chip.getSizeX(), armRows); getPrefs().putInt("Goalie.pixelsToEdgeOfGoal",armRows); } // public int getGoalieArmRows() { // return goalieArmRows; // } // /** These rows at bottom of image are ignored for acquiring new balls - they are assumed to come from seeing * our own arm. * @param goalieArmRows the number of retina rows at bottom of image to ignore for acquisition of new balls. Constrained to * 0-chip.getSizeY()/2. */ // public void setGoalieArmRows(int goalieArmRows) { // if(goalieArmRows<0) goalieArmRows=0; else if(goalieArmRows>chip.getSizeY()/2) goalieArmRows=chip.getSizeY()/2; // this.goalieArmRows = goalieArmRows; // getPrefs().putInt("Goalie.goalieArmRows",goalieArmRows); // } //// // public int getGoalieArmTauMs() { // return goalieArmTauMs; // } /** @return the delay before learning starts */ public int getLearnDelayMS() { return (int)learnDelayMS; } public void setLearnDelayMS(int learnDelayMS) { getPrefs().putLong("Goalie.learnTimeMs", (long)learnDelayMS); this.learnDelayMS = (long)learnDelayMS; } public void update(Observable o, Object arg) { servoArm.setCaptureRange(0, 0, chip.getSizeX(), armRows); // when chip changes, we need to set this } public void doResetLearning(){ servoArm.resetLearning(); } public void doLearn() { // since "do"Learn automatically added to GUI servoArm.startLearning(); } public void doRelax() { // automatically built into GUI for Goalie servoArm.relax(); } public int getPixelsToTipOfArm() { return pixelsToTipOfArm; } /** Defines the distance in image rows to the tip of the goalie arm. This number is slightly different *than the armRows parameter because of perspective. *@param pixelsToTipOfArm the number of image rows to the tip */ public void setPixelsToTipOfArm(int pixelsToTipOfArm) { if(pixelsToTipOfArm>chip.getSizeY()/2) pixelsToTipOfArm=chip.getSizeY()/2; this.pixelsToTipOfArm = pixelsToTipOfArm; getPrefs().putInt("Goalie.pixelsToTipOfArm",pixelsToTipOfArm); } /** Returns the ball tracker */ public RectangularClusterTracker getTracker(){ return tracker; } public float getWakeupBallDistance() { return wakeupBallDistance; } public void setWakeupBallDistance(float wakeupBallDistance) { if(wakeupBallDistance>.7f) wakeupBallDistance=.7f; else if(wakeupBallDistance<0) wakeupBallDistance=0; this.wakeupBallDistance = wakeupBallDistance; getPrefs().putFloat("Goalie.wakeupBallDistance",wakeupBallDistance); } public int getSleepDelaySec() { return sleepDelaySec; } public void setSleepDelaySec(int sleepDelaySec) { this.sleepDelaySec = sleepDelaySec; getPrefs().putInt("Goalie.sleepDelaySec",sleepDelaySec); } public XYTypeFilter getXYFilter() { return xYFilter; } public void setXYFilter(XYTypeFilter xYFilter) { this.xYFilter = xYFilter; } public int getRangeOutsideViewToBlockPixels() { return rangeOutsideViewToBlockPixels; } public void setRangeOutsideViewToBlockPixels(int rangeOutsideViewToBlockPixels) { if(rangeOutsideViewToBlockPixels<0)rangeOutsideViewToBlockPixels=0; this.rangeOutsideViewToBlockPixels = rangeOutsideViewToBlockPixels; getPrefs().putInt("Goalie.rangeOutsideViewToBlockPixels",rangeOutsideViewToBlockPixels); } File loggingFile=null; PrintWriter loggingWriter=null; long startLoggingTime; public void doLogging(){ try { loggingFile=new File(LOGGING_FILENAME); loggingWriter=new PrintWriter(new BufferedOutputStream(new FileOutputStream(loggingFile))); startLoggingTime=System.nanoTime(); loggingWriter.println("# goalie logging started "+new Date()); loggingWriter.println("# timeNs, ballx, bally, armDesired, armActual, ballvelx, ballvely, lastBallCrossingX lastTimestamp"); } catch (IOException ex) { ex.printStackTrace(); } } private void logGoalie(EventPacket<?> in){ if(loggingWriter==null) return; long t=System.nanoTime()-startLoggingTime; float ballx=Float.NaN, bally=Float.NaN, ballvelx=Float.NaN, ballvely=Float.NaN; if(ball!=null) { ballx=ball.getLocation().x; bally=ball.getLocation().y; ballvelx=ball.getVelocityPPS().x; ballvely=ball.getVelocityPPS().y; } loggingWriter.format("%d, %f, %f, %d, %d, %f, %f, %f, %d\n", t, ballx, bally, servoArm.getDesiredPosition(), servoArm.getActualPosition(), ballvelx, ballvely, lastBallCrossingX, in.getLastTimestamp() ); } protected void finalize() throws Throwable { if(loggingWriter!=null){ loggingWriter.flush(); loggingWriter.close(); } } public int getMinPathPointsToUseVelocity() { return minPathPointsToUseVelocity; } public void setMinPathPointsToUseVelocity(int minPathPointsToUseVelocity) { this.minPathPointsToUseVelocity = minPathPointsToUseVelocity; getPrefs().putInt("Goalie.minPathPointsToUseVelocity",minPathPointsToUseVelocity); } }
src/ch/unizh/ini/tobi/goalie/Goalie.java
/* * Goalie.java * * Created on July 5, 2006, 1:17 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. * * *Copyright July 5, 2006 Tobi Delbruck, Inst. of Neuroinformatics, UNI-ETH Zurich */ package ch.unizh.ini.tobi.goalie; import ch.unizh.ini.caviar.JAERViewer; import ch.unizh.ini.caviar.aemonitor.AEConstants; import ch.unizh.ini.caviar.chip.*; import ch.unizh.ini.caviar.event.EventPacket; import ch.unizh.ini.caviar.eventprocessing.EventFilter2D; import ch.unizh.ini.caviar.eventprocessing.FilterChain; import ch.unizh.ini.caviar.eventprocessing.filter.XYTypeFilter; import ch.unizh.ini.caviar.eventprocessing.tracking.RectangularClusterTracker; import ch.unizh.ini.caviar.graphics.FrameAnnotater; import ch.unizh.ini.caviar.hardwareinterface.*; import ch.unizh.ini.caviar.hardwareinterface.ServoInterface; import ch.unizh.ini.caviar.hardwareinterface.usb.ServoTest; import ch.unizh.ini.caviar.hardwareinterface.usb.SiLabsC8051F320_USBIO_ServoController; import ch.unizh.ini.caviar.util.filter.LowpassFilter; import ch.unizh.ini.tobi.goalie.ServoArm; import com.sun.opengl.util.*; import java.awt.Color; import java.awt.Graphics2D; import java.awt.geom.Point2D; import java.io.*; import java.util.*; import java.util.ArrayList; import java.util.Observable; import java.util.Observer; import java.util.logging.Level; import java.util.prefs.Preferences; import javax.media.opengl.*; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.glu.*; /** * Controls a servo motor that swings an arm in the way of a ball rolling towards a goal box. * Calibrates itself as well. * * @author tGoalielbruck/manuel lang */ public class Goalie extends EventFilter2D implements FrameAnnotater, Observer{ final String LOGGING_FILENAME="goalie.csv"; private boolean useVelocityForGoalie=getPrefs().getBoolean("Goalie.useVelocityForGoalie",true); {setPropertyTooltip("useVelocityForGoalie","uses ball velocity to calc impact position");} private long lastServoPositionTime=0; // used to relax servos after inactivity private int relaxationDelayMs=getPrefs().getInt("Goalie.relaxationDelayMs",500); {setPropertyTooltip("relaxationDelayMs","time [ms] before goalie first relaxes to middle after a movement. Goalie sleeps sleepDelaySec after this.\n");} private int sleepDelaySec=getPrefs().getInt("Goalie.sleepDelaySec",20); {setPropertyTooltip("sleepDelaySec","time [sec] before goalie sleeps");} private long learnDelayMS = getPrefs().getLong("Goalie.learnTimeMs",60000); {setPropertyTooltip("learnDelayMS","time [ms] of no balls present before a new learning cycle starts ");} private float wakeupBallDistance=getPrefs().getFloat("Goalie.wakeupBallDistance",.25f); {setPropertyTooltip("wakeupBallDistance","fraction of vertical image that ball must travel to wake up from SLEEP state");} RectangularClusterTracker tracker; volatile RectangularClusterTracker.Cluster ball=null; final Object ballLock = new Object(); private int armRows=getPrefs().getInt("Goalie.pixelsToEdgeOfGoal",40); {setPropertyTooltip("armRows","arm and ball tracking separation line position [pixels]");} private int pixelsToTipOfArm=getPrefs().getInt("Goalie.pixelsToTipOfArm",32); {setPropertyTooltip("pixelsToTipOfArm","defines distance in rows from bottom of image to tip of arm, used for computing arm position [pixels]");} private boolean useSoonest=getPrefs().getBoolean("Goalie.useSoonest",false); // use soonest ball rather than closest {setPropertyTooltip("useSoonest","react on soonest ball first");} // possible states, ACTIVE meaning blocking ball we can see, // RELAXED is between blocks // SLEEPING is after there have not been any definite balls for a while and we are waiting for a clear ball directed // at the goal before we start blocking again. This reduces annoyance factor due to background mStatent at top of scene. private enum State {ACTIVE, RELAXED, SLEEPING}; private State state=State.SLEEPING; // initial state private int topRowsToIgnore=getPrefs().getInt("Goalie.topRowsToIgnore",0); // balls here are ignored (hands) {setPropertyTooltip("topRowsToIgnore","top rows in scene to ignore for purposes of active ball blocking (balls are still tracked there)");} private int rangeOutsideViewToBlockPixels=getPrefs().getInt("Goalie.rangeOutsideViewToBlockPixels",30); // we only block shots that are this much outside scene, to avoid reacting continuously to people moving around laterally {setPropertyTooltip("rangeOutsideViewToBlockPixels","goalie will ignore balls that are more than this many pixels outside goal line");} //Arm control private ServoArm servoArm; private XYTypeFilter xYFilter; //FilterChain for GUI FilterChain trackingFilterChain; /** * Creates a Goaliestance of Goalie */ public Goalie(AEChip chip) { super(chip); chip.addObserver(this); //build hierachy trackingFilterChain = new FilterChain(chip); tracker=new RectangularClusterTracker(chip); servoArm = new ServoArm(chip); xYFilter = new XYTypeFilter(chip); trackingFilterChain.add(tracker); trackingFilterChain.add(servoArm); setEnclosedFilterChain(trackingFilterChain); tracker.setEnclosedFilter(xYFilter); tracker.setEnclosed(true, this); servoArm.setEnclosed(true, this); xYFilter.setEnclosed(true, tracker); // only top filter xYFilter.setXEnabled(true); xYFilter.setYEnabled(true); xYFilter.setTypeEnabled(false); xYFilter.setStartY(armRows); servoArm.initFilter(); servoArm.setCaptureRange(0,0, 128, armRows); chip.getCanvas().addAnnotator(this); initFilter(); } private float lastBallCrossingX=Float.NaN; // used for logging synchronized public EventPacket<?> filterPacket(EventPacket<?> in) { if(!isFilterEnabled()) return in; tracker.filterPacket(in); servoArm.filterPacket(in); synchronized (ballLock) { ball=getPutativeBallCluster(); // whether ball is returned also depends on state, if sleeping, harder to get one checkToRelax(ball); } switch(state){ case ACTIVE: case RELAXED: case SLEEPING: // not enough time has passed to relax and we might have a ball if(ball==null){ lastBallCrossingX=Float.NaN; }else if(ball.isVisible()){ // check for null because ball seems to disappear on us when using processOnAcquisition mode (realtime mode) // we have a ball, so move servo to position needed. // compute intersection of velocity vector of ball with bottom of view. // this is the place we should put the goalie. // this is computed from time to reach bottom (y/vy) times vx plus the x location. // we also include a parameter pixelsToTipOfArm which is where the goalie arm is in the field of view if(JAERViewer.globalTime1 == 0) JAERViewer.globalTime1 = System.nanoTime(); lastBallCrossingX=getBallGoalCrossingPixel(ball); float x=lastBallCrossingX; if(x>=-rangeOutsideViewToBlockPixels && x<=chip.getSizeX()+rangeOutsideViewToBlockPixels){ // only block balls that are blockable.... servoArm.setPosition((int)x); lastServoPositionTime=System.currentTimeMillis(); checkToRelax_state = 0; //next time idle move arm back to middle state = state.ACTIVE; // we just moved the arm } }else{ // ball not null but not visible yet to goalie } break; } logGoalie(in); return in; } private float getBallGoalCrossingPixel(RectangularClusterTracker.Cluster ball){ if(ball==null) throw new RuntimeException("null ball, shouldn't happen"); float x=(float)ball.location.x; if(useVelocityForGoalie && ball.isVelocityValid()){ Point2D.Float v=ball.getVelocityPPS(); double v2=v.x*v.x+v.y+v.y; if(v.y<0 /*&& v2>MIN_BALL_SPEED_TO_USE_PPS2*/){ // don't use vel unless ball is rolling towards goal // we need minus sign here because vel.y is negative x-=(float)(ball.location.y-pixelsToTipOfArm)/v.y*v.x; } } return x; } RectangularClusterTracker.Cluster oldBall=null; long lastDefiniteBallTime=0; // final int DEFINITE_BALL_LIFETIME_US=300000; /** * Gets the putative ball cluster. This method applies rules to determine the most likely ball cluster. * Returns null if there is no ball. * * @return ball with min y, assumed closest to viewer. This should filter out a lot of hands that roll the ball towards the goal. * If useVelocityForGoalie is true, then the ball ball must also be moving towards the goal. If useSoonest is true, then the ball * that will first cross the goal line, based on ball y velocity, will be returned. */ private RectangularClusterTracker.Cluster getPutativeBallCluster(){ if(tracker.getNumClusters()==0) return null; float minDistance=Float.POSITIVE_INFINITY, f, minTimeToImpact=Float.POSITIVE_INFINITY; RectangularClusterTracker.Cluster closest=null, soonest=null; for(RectangularClusterTracker.Cluster c:tracker.getClusters()){ if( c.isVisible()){ // cluster must be visible if(!useSoonest){ // compute nearest cluster if((f=(float)c.location.y) < minDistance ) { if( (!useVelocityForGoalie) || (useVelocityForGoalie && c.getVelocityPPS().y<=0)){ // give closest ball unconditionally if not using ball velocity // but if using velocity, then only give ball if it is moving towards goal minDistance=f; closest=c; // will it hit earlier? } } }else{ // use soonest to hit float t=computeTimeToImpactMs(c); if(t<minTimeToImpact) { soonest=c; minTimeToImpact=t; } } } // visible } RectangularClusterTracker.Cluster returnBall; if(useSoonest) returnBall= soonest; else returnBall= closest; if(returnBall!=null && returnBall.location.y>chip.getSizeY()-topRowsToIgnore) return null; // if we are SLEEPING then don't return a ball unless it is definitely one // if we detect a definite ball then we remember the time we saw it and only sleep after // SLEEP_DELAY_MS has passed since we saw a real ball if(returnBall!=null && /*returnBall.getLifetime()>DEFINITE_BALL_LIFETIME_US &&*/ returnBall.getDistanceYFromBirth()< -chip.getMaxSize()*getWakeupBallDistance()){ lastDefiniteBallTime=System.currentTimeMillis(); // we definitely got a real ball }else{ if(state==state.SLEEPING) returnBall=null; } return returnBall; } // getPutativeBallCluster /** @return time in ms to impact of cluster with goal line * @see #pixelsToEdgeOfGoal */ private float computeTimeToImpactMs(RectangularClusterTracker.Cluster cluster){ if(cluster==null){ log.warning("passed null cluster to getTimeToImpactMs"); return Float.POSITIVE_INFINITY; } float y=cluster.location.y; float dy=cluster.getVelocityPPS().y; // velocity of cluster in pixels per second if(dy>=0) return Float.POSITIVE_INFINITY; dy=dy/(AEConstants.TICK_DEFAULT_US*1e-6f); float dt=-1000f*(y-pixelsToTipOfArm)/dy; return dt; } /*private float applyGain(float f){ return .5f+(f-.5f)*gain; }*/ public Object getFilterState() { return null; } public void resetFilter() { tracker.resetFilter(); } /** initializes arm lowpass filter */ public void initFilter() { servoArm.setCaptureRange(0,0, chip.getSizeX(), armRows); } @Override synchronized public void setFilterEnabled(boolean yes){ super.setFilterEnabled(yes); if(!yes && loggingWriter!=null){ loggingWriter.close(); loggingWriter=null; } } /** not used */ public void annotate(float[][][] frame) { } /** not used */ public void annotate(Graphics2D g) { } GLUquadric ballQuad; GLU glu; float[] ballColor=new float[3]; public void annotate(GLAutoDrawable drawable) { if(!isFilterEnabled() ) return; tracker.annotate(drawable); // if(isRelaxed) return; GL gl=drawable.getGL(); gl.glPushMatrix(); float x=0.0f,y=0.0f,radius=0.0f; synchronized(ballLock){ if(ball != null) { ball.getColor().getRGBColorComponents(ballColor); x=ball.location.x; y=ball.location.y; radius=ball.getRadius(); } } if(glu==null) glu=new GLU(); if(ballQuad==null) ballQuad = glu.gluNewQuadric(); gl.glColor3fv(ballColor,0); gl.glPushMatrix(); gl.glTranslatef(x,y,0); glu.gluQuadricDrawStyle(ballQuad,GLU.GLU_FILL); glu.gluDisk(ballQuad,radius-1,radius+1.,16,1); gl.glPopMatrix(); float f=servoArm.getDesiredPosition(); // draw desired position of arm in color of ball being blocked gl.glRectf(f-8,pixelsToTipOfArm+2,f+8,pixelsToTipOfArm-1); gl.glColor3d(0.8,0.8,0.8); f = servoArm.getActualPosition(); // draw actual tracked position of arm in light grey gl.glRectf(f-6,pixelsToTipOfArm+2,f+6,pixelsToTipOfArm-1); gl.glPopMatrix(); // show state of Goalie (arm shows its own state) gl.glPushMatrix(); int font = GLUT.BITMAP_HELVETICA_18; gl.glRasterPos3f(chip.getSizeX() / 2-15, 7,0); // annotate the cluster with the arm state, e.g. relaxed or learning chip.getCanvas().getGlut().glutBitmapString(font, state.toString()); gl.glPopMatrix(); } public boolean isUseVelocityForGoalie() { return useVelocityForGoalie; } /** Sets whether the goalie uses the ball velocity or just the position * @param useVelocityForGoalie true to use ball velocity */ public void setUseVelocityForGoalie(boolean useVelocityForGoalie) { this.useVelocityForGoalie = useVelocityForGoalie; getPrefs().putBoolean("Goalie.useVelocityForGoalie",useVelocityForGoalie); } public int getRelaxationDelayMs() { return relaxationDelayMs; } /** sets the delay after all targets disappear that the goalie relaxes * @param relaxationDelayMs delay in ms */ public void setRelaxationDelayMs(int relaxationDelayMs) { this.relaxationDelayMs = relaxationDelayMs; getPrefs().putInt("Goalie.relaxationDelayMs",relaxationDelayMs); } private int checkToRelax_state = 0; // goalie goes to sleep after sleepDelaySec since last definite ball private final int RELAXED_POSITION_DELAY_MS=200; // ms to get to middle relaxed position private void checkToRelax(RectangularClusterTracker.Cluster ball){ // if enough time has passed AND there is no visible ball, then relax servo long timeSinceLastPosition=System.currentTimeMillis()- lastServoPositionTime; if( state==State.ACTIVE && (ball==null || !ball.isVisible()) && timeSinceLastPosition > relaxationDelayMs && checkToRelax_state == 0 ){ servoArm.setPosition(chip.getSizeX() / 2); state = state.RELAXED; checkToRelax_state = 1; // printState(); } // after relaxationDelayMs position to middle for next ball. if( state == State.RELAXED && (timeSinceLastPosition > relaxationDelayMs+RELAXED_POSITION_DELAY_MS) // wait for arm to get to middle && checkToRelax_state == 1) { servoArm.relax(); // turn off servo (if it is one that turns off when you stop sending pulses) checkToRelax_state = 2; // printState(); } // if we have relaxed to the middle and sufficient time has gone by since we got a ball, then we go to sleep state where its harder // to get a ball if(state==State.RELAXED && checkToRelax_state==2 && (System.currentTimeMillis()-lastDefiniteBallTime)>sleepDelaySec*1000){ state=State.SLEEPING; // printState(); } // if we've been relaxed a really long time start recalibrating if( state == State.SLEEPING && (timeSinceLastPosition > getLearnDelayMS())) { servoArm.startLearning(); lastServoPositionTime = System.currentTimeMillis(); // printState(); } } private void printState(){ log.info(state+" checkToRelax_state="+checkToRelax_state); } public boolean isUseSoonest() { return useSoonest; } /** If true, then goalie uses ball that will hit soonest. If false, goalie uses ball that is closest to goal. * @see #setUseVelocityForGoalie * @param useSoonest true to use soonest threat, false to use closest threat */ public void setUseSoonest(boolean useSoonest) { this.useSoonest = useSoonest; getPrefs().putBoolean("Goalie.useSoonest",useSoonest); } public int getTopRowsToIgnore() { return topRowsToIgnore; } public void setTopRowsToIgnore(int topRowsToIgnore) { if(topRowsToIgnore>chip.getSizeY()) topRowsToIgnore=chip.getSizeY(); this.topRowsToIgnore = topRowsToIgnore; getPrefs().putInt("Goalie.topRowsToIgnore",topRowsToIgnore); } public int getArmRows() { return armRows; } /** Defines the number of retina rows from bottom of image to tip of goalie arm to define tracking region for arm. *If this is too small then the arm will be tracked as balls, greatly confusing things. * Constrained to range 0-chip.getSizeY()/2. * @param armRows the number of rows of pixels */ public void setArmRows(int armRows) { if(armRows<0) armRows=0; else if(armRows>chip.getSizeY()/2) armRows=chip.getSizeY()/2; this.armRows = armRows; ((XYTypeFilter) tracker.getEnclosedFilter()).setStartY(armRows); servoArm.setCaptureRange(0, 0, chip.getSizeX(), armRows); getPrefs().putInt("Goalie.pixelsToEdgeOfGoal",armRows); } // public int getGoalieArmRows() { // return goalieArmRows; // } // /** These rows at bottom of image are ignored for acquiring new balls - they are assumed to come from seeing * our own arm. * @param goalieArmRows the number of retina rows at bottom of image to ignore for acquisition of new balls. Constrained to * 0-chip.getSizeY()/2. */ // public void setGoalieArmRows(int goalieArmRows) { // if(goalieArmRows<0) goalieArmRows=0; else if(goalieArmRows>chip.getSizeY()/2) goalieArmRows=chip.getSizeY()/2; // this.goalieArmRows = goalieArmRows; // getPrefs().putInt("Goalie.goalieArmRows",goalieArmRows); // } //// // public int getGoalieArmTauMs() { // return goalieArmTauMs; // } /** @return the delay before learning starts */ public int getLearnDelayMS() { return (int)learnDelayMS; } public void setLearnDelayMS(int learnDelayMS) { getPrefs().putLong("Goalie.learnTimeMs", (long)learnDelayMS); this.learnDelayMS = (long)learnDelayMS; } public void update(Observable o, Object arg) { servoArm.setCaptureRange(0, 0, chip.getSizeX(), armRows); // when chip changes, we need to set this } public void doResetLearning(){ servoArm.resetLearning(); } public void doLearn() { // since "do"Learn automatically added to GUI servoArm.startLearning(); } public void doRelax() { // automatically built into GUI for Goalie servoArm.relax(); } public int getPixelsToTipOfArm() { return pixelsToTipOfArm; } /** Defines the distance in image rows to the tip of the goalie arm. This number is slightly different *than the armRows parameter because of perspective. *@param pixelsToTipOfArm the number of image rows to the tip */ public void setPixelsToTipOfArm(int pixelsToTipOfArm) { if(pixelsToTipOfArm>chip.getSizeY()/2) pixelsToTipOfArm=chip.getSizeY()/2; this.pixelsToTipOfArm = pixelsToTipOfArm; getPrefs().putInt("Goalie.pixelsToTipOfArm",pixelsToTipOfArm); } /** Returns the ball tracker */ public RectangularClusterTracker getTracker(){ return tracker; } public float getWakeupBallDistance() { return wakeupBallDistance; } public void setWakeupBallDistance(float wakeupBallDistance) { if(wakeupBallDistance>.7f) wakeupBallDistance=.7f; else if(wakeupBallDistance<0) wakeupBallDistance=0; this.wakeupBallDistance = wakeupBallDistance; getPrefs().putFloat("Goalie.wakeupBallDistance",wakeupBallDistance); } public int getSleepDelaySec() { return sleepDelaySec; } public void setSleepDelaySec(int sleepDelaySec) { this.sleepDelaySec = sleepDelaySec; getPrefs().putInt("Goalie.sleepDelaySec",sleepDelaySec); } public XYTypeFilter getXYFilter() { return xYFilter; } public void setXYFilter(XYTypeFilter xYFilter) { this.xYFilter = xYFilter; } public int getRangeOutsideViewToBlockPixels() { return rangeOutsideViewToBlockPixels; } public void setRangeOutsideViewToBlockPixels(int rangeOutsideViewToBlockPixels) { if(rangeOutsideViewToBlockPixels<0)rangeOutsideViewToBlockPixels=0; this.rangeOutsideViewToBlockPixels = rangeOutsideViewToBlockPixels; getPrefs().putInt("Goalie.rangeOutsideViewToBlockPixels",rangeOutsideViewToBlockPixels); } File loggingFile=null; PrintWriter loggingWriter=null; long startLoggingTime; public void doLogging(){ try { loggingFile=new File(LOGGING_FILENAME); loggingWriter=new PrintWriter(new BufferedOutputStream(new FileOutputStream(loggingFile))); startLoggingTime=System.nanoTime(); loggingWriter.println("# goalie logging started "+new Date()); loggingWriter.println("# timeNs, ballx, bally, armDesired, armActual, ballvelx, ballvely, lastBallCrossingX lastTimestamp"); } catch (IOException ex) { ex.printStackTrace(); } } private void logGoalie(EventPacket<?> in){ if(loggingWriter==null) return; long t=System.nanoTime()-startLoggingTime; float ballx=Float.NaN, bally=Float.NaN, ballvelx=Float.NaN, ballvely=Float.NaN; if(ball!=null) { ballx=ball.getLocation().x; bally=ball.getLocation().y; ballvelx=ball.getVelocityPPS().x; ballvely=ball.getVelocityPPS().y; } loggingWriter.format("%d, %f, %f, %d, %d, %f, %f, %f, %d\n", t, ballx, bally, servoArm.getDesiredPosition(), servoArm.getActualPosition(), ballvelx, ballvely, lastBallCrossingX, in.getLastTimestamp() ); } protected void finalize() throws Throwable { if(loggingWriter!=null){ loggingWriter.flush(); loggingWriter.close(); } } }
Goalie now can only pay attention to velocity of balls if there are sufficient points to compute velocity "reliably" (presently this just means a sufficient number of path points, not any measure of goodness of linear regression). plotGoalie.m does a better job of plotting results of measurements. git-svn-id: e3d3b427d532171a6bd7557d8a4952a393b554a2@350 b7f4320f-462c-0410-a916-d9f35bb82d52
src/ch/unizh/ini/tobi/goalie/Goalie.java
Goalie now can only pay attention to velocity of balls if there are sufficient points to compute velocity "reliably" (presently this just means a sufficient number of path points, not any measure of goodness of linear regression). plotGoalie.m does a better job of plotting results of measurements.
<ide><path>rc/ch/unizh/ini/tobi/goalie/Goalie.java <ide> <ide> private boolean useVelocityForGoalie=getPrefs().getBoolean("Goalie.useVelocityForGoalie",true); <ide> {setPropertyTooltip("useVelocityForGoalie","uses ball velocity to calc impact position");} <add> private int minPathPointsToUseVelocity=getPrefs().getInt("Goalie.minPathPointsToUseVelocity",10); <add> {setPropertyTooltip("minPathPointsToUseVelocity","only after path has this many points is velocity used to predict path");} <add> <ide> private long lastServoPositionTime=0; // used to relax servos after inactivity <ide> private int relaxationDelayMs=getPrefs().getInt("Goalie.relaxationDelayMs",500); <ide> {setPropertyTooltip("relaxationDelayMs","time [ms] before goalie first relaxes to middle after a movement. Goalie sleeps sleepDelaySec after this.\n");} <ide> if(JAERViewer.globalTime1 == 0) <ide> JAERViewer.globalTime1 = System.nanoTime(); <ide> <del> lastBallCrossingX=getBallGoalCrossingPixel(ball); <add> lastBallCrossingX=getBallCrossingGoalPixel(ball); <ide> float x=lastBallCrossingX; <ide> <ide> if(x>=-rangeOutsideViewToBlockPixels && x<=chip.getSizeX()+rangeOutsideViewToBlockPixels){ <ide> return in; <ide> } <ide> <del> private float getBallGoalCrossingPixel(RectangularClusterTracker.Cluster ball){ <add> private float getBallCrossingGoalPixel(RectangularClusterTracker.Cluster ball){ <ide> if(ball==null) throw new RuntimeException("null ball, shouldn't happen"); <ide> float x=(float)ball.location.x; <del> if(useVelocityForGoalie && ball.isVelocityValid()){ <add> if(useVelocityForGoalie && ball.isVelocityValid() && ball.getPath().size()>=minPathPointsToUseVelocity){ <ide> Point2D.Float v=ball.getVelocityPPS(); <ide> double v2=v.x*v.x+v.y+v.y; <ide> if(v.y<0 /*&& v2>MIN_BALL_SPEED_TO_USE_PPS2*/){ <ide> loggingWriter.close(); <ide> } <ide> } <add> <add> public int getMinPathPointsToUseVelocity() { <add> return minPathPointsToUseVelocity; <add> } <add> <add> public void setMinPathPointsToUseVelocity(int minPathPointsToUseVelocity) { <add> this.minPathPointsToUseVelocity = minPathPointsToUseVelocity; <add> getPrefs().putInt("Goalie.minPathPointsToUseVelocity",minPathPointsToUseVelocity); <add> } <ide> <ide> <ide> }
Java
apache-2.0
202e292b77ca346d26039e366c9bb9dce87fe9d8
0
KaiHofstetter/foosball-booking-service
package net.softwareminds.foosballbooking.service.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { // @formatter:off auth.inMemoryAuthentication() .withUser("Peter") .password("secret") .roles("USER") .and() .withUser("Bob") .password("secret") .roles("USER"); // @formatter:on } @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/webjars/**"); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override protected void configure(HttpSecurity http) throws Exception { // @formatter:off http.authorizeRequests() .antMatchers("/login.jsp").permitAll() .and() .authorizeRequests() .anyRequest().hasRole("USER") .and() .exceptionHandling() .accessDeniedPage("/login.jsp?authorization_error=true") .and() .formLogin() .loginPage("/login.jsp") .loginProcessingUrl("/login.do") .failureUrl("/login.jsp?authentication_error=true") .and() .csrf().disable(); // @formatter:off } }
src/main/java/net/softwareminds/foosballbooking/service/config/SecurityConfiguration.java
package net.softwareminds.foosballbooking.service.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { // @formatter:off auth.inMemoryAuthentication() .withUser("Peter") .password("secret") .roles("USER") .and() .withUser("Bob") .password("secret") .roles("USER"); // @formatter:on } @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/webjars/**"); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override protected void configure(HttpSecurity http) throws Exception { // @formatter:off http.authorizeRequests() .antMatchers("/login.jsp").permitAll() .and() .authorizeRequests() .anyRequest().hasRole("USER") .and() .exceptionHandling() .accessDeniedPage("/login.jsp?authorization_error=true") .and() .logout() .logoutSuccessUrl("/index.jsp") .logoutUrl("/logout.do") .and() .formLogin() .loginPage("/login.jsp") .loginProcessingUrl("/login.do") .failureUrl("/login.jsp?authentication_error=true") .and() .csrf().disable(); // @formatter:off } }
Logout removed.
src/main/java/net/softwareminds/foosballbooking/service/config/SecurityConfiguration.java
Logout removed.
<ide><path>rc/main/java/net/softwareminds/foosballbooking/service/config/SecurityConfiguration.java <ide> .exceptionHandling() <ide> .accessDeniedPage("/login.jsp?authorization_error=true") <ide> .and() <del> .logout() <del> .logoutSuccessUrl("/index.jsp") <del> .logoutUrl("/logout.do") <del> .and() <ide> .formLogin() <ide> .loginPage("/login.jsp") <ide> .loginProcessingUrl("/login.do")
Java
apache-2.0
7309388bf161b3ad46564d2542a25c6d6997be00
0
pfn/acra,ACRA/acra,F43nd1r/acra,ACRA/acra,ACRA/acra,F43nd1r/acra,ACRA/acra,MaTriXy/acra
/* * Copyright 2010 Emmanuel Astier & Kevin Gaudin * * 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.acra; import android.Manifest.permission; import android.app.Activity; import android.app.Application; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.os.Bundle; import android.os.Looper; import android.support.v4.app.NotificationCompat; import android.widget.Toast; import org.acra.annotation.ReportsCrashes; import org.acra.collector.Compatibility; import org.acra.collector.ConfigurationCollector; import org.acra.collector.CrashReportData; import org.acra.collector.CrashReportDataFactory; import org.acra.common.CrashReportFileNameParser; import org.acra.common.CrashReportFinder; import org.acra.common.CrashReportPersister; import org.acra.jraf.android.util.activitylifecyclecallbackscompat.ActivityLifecycleCallbacksCompat; import org.acra.jraf.android.util.activitylifecyclecallbackscompat.ApplicationHelper; import org.acra.sender.*; import org.acra.util.PackageManagerWrapper; import org.acra.util.ToastSender; import java.io.File; import java.lang.Thread.UncaughtExceptionHandler; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Map; import static org.acra.ACRA.LOG_TAG; import static org.acra.ReportField.IS_SILENT; /** * <p> * The ErrorReporter is a Singleton object in charge of collecting crash context * data and sending crash reports. It registers itself as the Application's * Thread default {@link UncaughtExceptionHandler}. * </p> * <p> * When a crash occurs, it collects data of the crash context (device, system, * stack trace...) and writes a report file in the application private * directory. This report file is then sent: * </p> * <ul> * <li>immediately if {@link ReportsCrashes#mode} is set to * {@link ReportingInteractionMode#SILENT} or * {@link ReportingInteractionMode#TOAST},</li> * <li>on application start if in the previous case the transmission could not * technically be made,</li> * <li>when the user accepts to send it if {@link ReportsCrashes#mode()} is set * to {@link ReportingInteractionMode#NOTIFICATION}.</li> * </ul> * <p> * If an error occurs while sending a report, it is kept for later attempts. * </p> */ public class ErrorReporter implements Thread.UncaughtExceptionHandler { private final boolean supportedAndroidVersion; private boolean enabled = false; private final Application mContext; private final SharedPreferences prefs; /** * Contains the active {@link ReportSender}s. */ private final ArrayList<Class<? extends ReportSenderFactory>> reportSenderFactories = new ArrayList<Class<? extends ReportSenderFactory>>(); private final CrashReportDataFactory crashReportDataFactory; private final CrashReportFileNameParser fileNameParser = new CrashReportFileNameParser(); // A reference to the system's previous default UncaughtExceptionHandler // kept in order to execute the default exception handling after sending the report. private final Thread.UncaughtExceptionHandler mDfltExceptionHandler; private WeakReference<Activity> lastActivityCreated = new WeakReference<Activity>(null); /** * This is used to wait for the crash toast to end it's display duration * before killing the Application. */ private boolean toastWaitEnded = true; private static final ExceptionHandlerInitializer NULL_EXCEPTION_HANDLER_INITIALIZER = new ExceptionHandlerInitializer() { @Override public void initializeExceptionHandler(ErrorReporter reporter) { } }; private volatile ExceptionHandlerInitializer exceptionHandlerInitializer = NULL_EXCEPTION_HANDLER_INITIALIZER; /** * Used to create a new (non-cached) PendingIntent each time a new crash occurs. */ private static int mNotificationCounter = 0; /** * Can only be constructed from within this class. * * @param context Context for the application in which ACRA is running. * @param prefs SharedPreferences used by ACRA. * @param enabled Whether this ErrorReporter should capture Exceptions and forward their reports. * @param listenForUncaughtExceptions Whether to listen for uncaught Exceptions. */ ErrorReporter(Application context, SharedPreferences prefs, boolean enabled, boolean supportedAndroidVersion, boolean listenForUncaughtExceptions) { this.mContext = context; this.prefs = prefs; this.enabled = enabled; this.supportedAndroidVersion = supportedAndroidVersion; this.reportSenderFactories.addAll(Arrays.asList(ACRA.getConfig().reportSenderFactoryClasses())); // Store the initial Configuration state. // This is expensive to gather, so only do so if we plan to report it. final String initialConfiguration; if (ACRA.getConfig().getReportFields().contains(ReportField.INITIAL_CONFIGURATION)) { initialConfiguration = ConfigurationCollector.collectConfiguration(mContext); } else { initialConfiguration = null; } // Sets the application start date. // This will be included in the reports, will be helpful compared to user_crash date. final Calendar appStartDate = new GregorianCalendar(); if (Compatibility.getAPILevel() >= Compatibility.VERSION_CODES.ICE_CREAM_SANDWICH) { // ActivityLifecycleCallback // only available for API14+ ApplicationHelper.registerActivityLifecycleCallbacks(context, new ActivityLifecycleCallbacksCompat() { @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { if (ACRA.DEV_LOGGING) ACRA.log.d(LOG_TAG, "onActivityCreated " + activity.getClass()); if (!(activity instanceof BaseCrashReportDialog)) { // Ignore CrashReportDialog because we want the last // application Activity that was started so that we can explicitly kill it off. lastActivityCreated = new WeakReference<Activity>(activity); } } @Override public void onActivityStarted(Activity activity) { if (ACRA.DEV_LOGGING) ACRA.log.d(LOG_TAG, "onActivityStarted " + activity.getClass()); } @Override public void onActivityResumed(Activity activity) { if (ACRA.DEV_LOGGING) ACRA.log.d(LOG_TAG, "onActivityResumed " + activity.getClass()); } @Override public void onActivityPaused(Activity activity) { if (ACRA.DEV_LOGGING) ACRA.log.d(LOG_TAG, "onActivityPaused " + activity.getClass()); } @Override public void onActivityStopped(Activity activity) { if (ACRA.DEV_LOGGING) ACRA.log.d(LOG_TAG, "onActivityStopped " + activity.getClass()); } @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) { if (ACRA.DEV_LOGGING) ACRA.log.i(LOG_TAG, "onActivitySaveInstanceState " + activity.getClass()); } @Override public void onActivityDestroyed(Activity activity) { if (ACRA.DEV_LOGGING) ACRA.log.i(LOG_TAG, "onActivityDestroyed " + activity.getClass()); } }); } crashReportDataFactory = new CrashReportDataFactory(mContext, prefs, appStartDate, initialConfiguration); if (listenForUncaughtExceptions) { mDfltExceptionHandler = Thread.getDefaultUncaughtExceptionHandler(); Thread.setDefaultUncaughtExceptionHandler(this); } else { mDfltExceptionHandler = null; } } /** * @return the current instance of ErrorReporter. * @throws IllegalStateException * if {@link ACRA#init(android.app.Application)} has not yet * been called. * @deprecated since 4.3.0 Use {@link org.acra.ACRA#getErrorReporter()} * instead. */ @SuppressWarnings("unused") @Deprecated public static ErrorReporter getInstance() { return ACRA.getErrorReporter(); } /** * Deprecated. Use {@link #putCustomData(String, String)}. * * @param key * A key for your custom data. * @param value * The value associated to your key. */ @Deprecated @SuppressWarnings("unused") public void addCustomData(String key, String value) { crashReportDataFactory.putCustomData(key, value); } /** * <p> * Use this method to provide the ErrorReporter with data of your running * application. You should call this at several key places in your code the * same way as you would output important debug data in a log file. Only the * latest value is kept for each key (no history of the values is sent in * the report). * </p> * <p> * The key/value pairs will be stored in the GoogleDoc spreadsheet in the * "custom" column, as a text containing a 'key = value' pair on each line. * </p> * * @param key A key for your custom data. * @param value The value associated to your key. * @return The previous value for this key if there was one, or null. * @see #removeCustomData(String) * @see #getCustomData(String) */ @SuppressWarnings("unused") public String putCustomData(String key, String value) { return crashReportDataFactory.putCustomData(key, value); } /** * <p> * Use this method to perform additional initialization before the * ErrorReporter handles a throwable. This can be used, for example, to put * custom data using {@link #putCustomData(String, String)}, which is not * available immediately after startup. It can be, for example, last 20 * requests or something else. The call is thread safe. * </p> * <p> * {@link ExceptionHandlerInitializer#initializeExceptionHandler(ErrorReporter)} * will be executed on the main thread in case of uncaught exception and on * the caller thread of {@link #handleSilentException(Throwable)} or * {@link #handleException(Throwable)}. * </p> * <p> * Example. Add to the {@link Application#onCreate()}: * </p> * * <pre> * ACRA.getErrorReporter().setExceptionHandlerInitializer(new ExceptionHandlerInitializer() { * <code>@Override</code> public void initializeExceptionHandler(ErrorReporter reporter) { * reporter.putCustomData("CUSTOM_ACCUMULATED_DATA_TAG", someAccumulatedData.toString); * } * }); * </pre> * * @param initializer The initializer. Can be <code>null</code>. */ public void setExceptionHandlerInitializer(ExceptionHandlerInitializer initializer) { exceptionHandlerInitializer = (initializer != null) ? initializer : NULL_EXCEPTION_HANDLER_INITIALIZER; } /** * Removes a key/value pair from your reports custom data field. * * @param key The key of the data to be removed. * @return The value for this key before removal. * @see #putCustomData(String, String) * @see #getCustomData(String) */ @SuppressWarnings("unused") public String removeCustomData(String key) { return crashReportDataFactory.removeCustomData(key); } /** * Removes all key/value pairs from your reports custom data field. */ @SuppressWarnings("unused") public void clearCustomData() { crashReportDataFactory.clearCustomData(); } /** * Gets the current value for a key in your reports custom data field. * * @param key * The key of the data to be retrieved. * @return The value for this key. * @see #putCustomData(String, String) * @see #removeCustomData(String) */ @SuppressWarnings("unused") public String getCustomData(String key) { return crashReportDataFactory.getCustomData(key); } /** * Adds a ReportSenderFactory to the list of factories that will construct {@link ReportSender}s when sending reports. * * Note: you can declare your {@link ReportSenderFactory}s via {@link ReportsCrashes#reportSenderFactoryClasses()}. * * @param senderFactory ReportSenderFactory to add tto the list of existing factories. * @since 4.8.0 */ @SuppressWarnings("unused") public void addReportSenderFactory(Class<? extends ReportSenderFactory> senderFactory) { reportSenderFactories.add(senderFactory); } /** * Remove a {@link ReportSenderFactory} from the list of factories * that will construct {@link ReportSender}s when sending reports. * * Note: you can declare your {@link ReportSenderFactory}s via {@link ReportsCrashes#reportSenderFactoryClasses()}. * * @param senderFactory The {@link ReportSender} class to be removed. * @since 4.8.0 */ @SuppressWarnings("unused") public void removeReportSenderFactory(Class<? extends ReportSenderFactory> senderFactory) { reportSenderFactories.remove(senderFactory); } /** * Clears the list of active {@link ReportSender}s. * * You should then call {@link #addReportSenderFactory(Class)} or ACRA will not send any reports. */ @SuppressWarnings("unused") public void removeAllReportSenders() { reportSenderFactories.clear(); } /** * Removes all previously set {@link ReportSenderFactory}s and set the given one as the sole {@link ReportSenderFactory}. * * Note: you can declare your {@link ReportSenderFactory}s via {@link ReportsCrashes#reportSenderFactoryClasses()}. * * @param senderFactory ReportSenderFactory to set as the creator of {@link ReportSender}s for this ErrorReporter. */ @SuppressWarnings("unused") public void setReportSenderFactory(Class<? extends ReportSenderFactory> senderFactory) { reportSenderFactories.clear(); reportSenderFactories.add(senderFactory); } /* * (non-Javadoc) * * @see * java.lang.Thread.UncaughtExceptionHandler#uncaughtException(java.lang * .Thread, java.lang.Throwable) */ @Override public void uncaughtException(Thread t, Throwable e) { try { // If we're not enabled then just pass the Exception on to any // defaultExceptionHandler. if (!enabled) { if (mDfltExceptionHandler != null) { ACRA.log.e(LOG_TAG, "ACRA is disabled for " + mContext.getPackageName() + " - forwarding uncaught Exception on to default ExceptionHandler"); mDfltExceptionHandler.uncaughtException(t, e); } else { ACRA.log.e(LOG_TAG, "ACRA is disabled for " + mContext.getPackageName() + " - no default ExceptionHandler"); ACRA.log.e(LOG_TAG, "ACRA caught a " + e.getClass().getSimpleName() + " for " + mContext.getPackageName(), e); } return; } ACRA.log.e(LOG_TAG, "ACRA caught a " + e.getClass().getSimpleName() + " for " + mContext.getPackageName(), e); ACRA.log.d(LOG_TAG, "Building report"); // Generate and send crash report reportBuilder() .uncaughtExceptionThread(t) .exception(e) .endsApplication() .send(); } catch (Throwable fatality) { // ACRA failed. Prevent any recursive call to // ACRA.uncaughtException(), let the native reporter do its job. if (mDfltExceptionHandler != null) { mDfltExceptionHandler.uncaughtException(t, e); } } } /** * End the application. */ private void endApplication(Thread uncaughtExceptionThread, Throwable th) { // TODO It would be better to create an explicit config attribute #letDefaultHandlerEndApplication // as the intent is clearer and would allows you to switch it off for SILENT. final boolean letDefaultHandlerEndApplication = ( ACRA.getConfig().mode() == ReportingInteractionMode.SILENT || (ACRA.getConfig().mode() == ReportingInteractionMode.TOAST && ACRA.getConfig().forceCloseDialogAfterToast()) ); final boolean handlingUncaughtException = uncaughtExceptionThread != null; if (handlingUncaughtException && letDefaultHandlerEndApplication && (mDfltExceptionHandler != null)) { // Let the system default handler do it's job and display the force close dialog. ACRA.log.d(LOG_TAG, "Handing Exception on to default ExceptionHandler"); mDfltExceptionHandler.uncaughtException(uncaughtExceptionThread, th); } else { // If ACRA handles user notifications with a Toast or a Notification // the Force Close dialog is one more notification to the user... // We choose to close the process ourselves using the same actions. // Trying to solve https://github.com/ACRA/acra/issues/42#issuecomment-12134144 // Determine the current/last Activity that was started and close // it. Activity#finish (and maybe it's parent too). final Activity lastActivity = lastActivityCreated.get(); if (lastActivity != null) { ACRA.log.i(LOG_TAG, "Finishing the last Activity prior to killing the Process"); lastActivity.finish(); ACRA.log.i(LOG_TAG, "Finished " + lastActivity.getClass()); lastActivityCreated.clear(); } android.os.Process.killProcess(android.os.Process.myPid()); System.exit(10); } } /** * Send a report for this {@link Throwable} silently (forces the use of * {@link ReportingInteractionMode#SILENT} for this report, whatever is the * mode set for the application. Very useful for tracking difficult defects. * * @param e * The {@link Throwable} to be reported. If null the report will * contain a new Exception("Report requested by developer"). */ public void handleSilentException(Throwable e) { // Mark this report as silent. if (enabled) { reportBuilder() .exception(e) .forceSilent() .send(); ACRA.log.d(LOG_TAG, "ACRA sent Silent report."); return; } ACRA.log.d(LOG_TAG, "ACRA is disabled. Silent report not sent."); } /** * Enable or disable this ErrorReporter. By default it is enabled. * * @param enabled * Whether this ErrorReporter should capture Exceptions and * forward them as crash reports. */ public void setEnabled(boolean enabled) { if (!supportedAndroidVersion) { ACRA.log.w(LOG_TAG, "ACRA 4.7.0+ requires Froyo or greater. ACRA is disabled and will NOT catch crashes or send messages."); } else { ACRA.log.i(LOG_TAG, "ACRA is " + (enabled ? "enabled" : "disabled") + " for " + mContext.getPackageName()); this.enabled = enabled; } } /** * Starts a Thread to start sending outstanding error reports. * * @param onlySendSilentReports * If true then only send silent reports. * @param approveReportsFirst * If true then approve unapproved reports first. */ void startSendingReports(boolean onlySendSilentReports, boolean approveReportsFirst) { if (enabled) { ACRA.log.v(LOG_TAG, "About to start SenderService"); final Intent intent = new Intent(mContext, SenderService.class); intent.putExtra(SenderService.EXTRA_ONLY_SEND_SILENT_REPORTS, onlySendSilentReports); intent.putExtra(SenderService.EXTRA_APPROVE_REPORTS_FIRST, approveReportsFirst); intent.putExtra(SenderService.EXTRA_REPORT_SENDER_FACTORIES, reportSenderFactories); mContext.startService(intent); } else { ACRA.log.w(LOG_TAG, "Would be sending reports, but ACRA is disabled"); } } /** * Delete all report files stored. */ void deletePendingReports() { deletePendingReports(true, true, 0); } /** * This method looks for pending reports and does the action required * depending on the interaction mode set. */ public void checkReportsOnApplicationStart() { if (ACRA.getConfig().deleteOldUnsentReportsOnApplicationStart()) { // Delete any old unsent reports if this is a newer version of the app // than when we last started. final long lastVersionNr = prefs.getInt(ACRA.PREF_LAST_VERSION_NR, 0); final PackageManagerWrapper packageManagerWrapper = new PackageManagerWrapper(mContext); final PackageInfo packageInfo = packageManagerWrapper.getPackageInfo(); if (packageInfo != null) { final boolean newVersion = packageInfo.versionCode > lastVersionNr; if (newVersion) { deletePendingReports(); } final SharedPreferences.Editor prefsEditor = prefs.edit(); prefsEditor.putInt(ACRA.PREF_LAST_VERSION_NR, packageInfo.versionCode); prefsEditor.commit(); } } ReportingInteractionMode reportingInteractionMode = ACRA.getConfig().mode(); if ((reportingInteractionMode == ReportingInteractionMode.NOTIFICATION || reportingInteractionMode == ReportingInteractionMode.DIALOG) && ACRA.getConfig().deleteUnapprovedReportsOnApplicationStart()) { // NOTIFICATION or DIALOG mode, and there are unapproved reports to // send (latest notification/dialog has been ignored: neither // accepted // nor refused). The application developer has decided that // these reports should not be renotified ==> destroy them all but // one. deletePendingNonApprovedReports(true); } final CrashReportFinder reportFinder = new CrashReportFinder(mContext); String[] filesList = reportFinder.getCrashReportFiles(); if (filesList != null && filesList.length > 0) { // Immediately send reports for SILENT and TOAST modes. // Immediately send reports in NOTIFICATION mode only if they are // all silent or approved. // If there is still one unapproved report in NOTIFICATION mode, // notify it. // If there are unapproved reports in DIALOG mode, show the dialog final boolean onlySilentOrApprovedReports = containsOnlySilentOrApprovedReports(filesList); if (reportingInteractionMode == ReportingInteractionMode.SILENT || reportingInteractionMode == ReportingInteractionMode.TOAST || (onlySilentOrApprovedReports && (reportingInteractionMode == ReportingInteractionMode.NOTIFICATION || reportingInteractionMode == ReportingInteractionMode.DIALOG))) { if (reportingInteractionMode == ReportingInteractionMode.TOAST && !onlySilentOrApprovedReports) { // Display the Toast in TOAST mode only if there are // non-silent reports. ToastSender.sendToast(mContext, ACRA.getConfig().resToastText(), Toast.LENGTH_LONG); } startSendingReports(false, false); } } } /** * Delete all pending non approved reports. * * @param keepOne * If you need to keep the latest report, set this to true. */ void deletePendingNonApprovedReports(boolean keepOne) { // In NOTIFICATION AND DIALOG mode, we have to keep the latest report // which // has been written before killing the app. final int nbReportsToKeep = keepOne ? 1 : 0; deletePendingReports(false, true, nbReportsToKeep); } /** * Send a report for a {@link Throwable} with the reporting interaction mode * configured by the developer. * * @param e * The {@link Throwable} to be reported. If null the report will * contain a new Exception("Report requested by developer"). * @param endApplication * Set this to true if you want the application to be ended after * sending the report. */ @SuppressWarnings("unused") public void handleException(Throwable e, boolean endApplication) { final ReportBuilder builder = reportBuilder() .exception(e); if (endApplication) { builder.endsApplication(); } builder.send(); } /** * Send a report for a {@link Throwable} with the reporting interaction mode * configured by the developer, the application is then killed and restarted * by the system. * * @param e * The {@link Throwable} to be reported. If null the report will * contain a new Exception("Report requested by developer"). */ @SuppressWarnings("unused") public void handleException(Throwable e) { reportBuilder() .exception(e) .send(); } /** * Creates a new crash report builder * * @return the newly created {@code ReportBuilder} */ public ReportBuilder reportBuilder() { return new ReportBuilder(); } /** * Helps manage */ private static class TimeHelper { private Long initialTimeMillis; public void setInitialTimeMillis(long initialTimeMillis) { this.initialTimeMillis = initialTimeMillis; } /** * @return 0 if the initial time has yet to be set otherwise returns the difference between now and the initial time. */ public long getElapsedTime() { return (initialTimeMillis == null) ? 0 : System.currentTimeMillis() - initialTimeMillis; } } /** * Try to send a report, if an error occurs stores a report file for a later attempt. * * @param reportBuilder The report builder used to assemble the report */ private void report(final ReportBuilder reportBuilder) { if (!enabled) { return; } try { exceptionHandlerInitializer.initializeExceptionHandler(this); } catch (Exception exceptionInRunnable) { ACRA.log.d(LOG_TAG, "Failed to initialize " + exceptionHandlerInitializer + " from #handleException"); } boolean sendOnlySilentReports = false; ReportingInteractionMode reportingInteractionMode; if (!reportBuilder.mForceSilent) { // No interaction mode defined in the ReportBuilder, we assume it has been set during ACRA.initACRA() reportingInteractionMode = ACRA.getConfig().mode(); } else { reportingInteractionMode = ReportingInteractionMode.SILENT; // An interaction mode has been provided. If ACRA has been // initialized with a non SILENT mode and this mode is overridden // with SILENT, then we have to send only reports which have been // explicitly declared as silent via handleSilentException(). if (ACRA.getConfig().mode() != ReportingInteractionMode.SILENT) { sendOnlySilentReports = true; } } final boolean shouldDisplayToast = reportingInteractionMode == ReportingInteractionMode.TOAST || (ACRA.getConfig().resToastText() != 0 && (reportingInteractionMode == ReportingInteractionMode.NOTIFICATION || reportingInteractionMode == ReportingInteractionMode.DIALOG)); final TimeHelper sentToastTimeMillis = new TimeHelper(); if (shouldDisplayToast) { new Thread() { /* * (non-Javadoc) * * @see java.lang.Thread#run() */ @Override public void run() { Looper.prepare(); ToastSender.sendToast(mContext, ACRA.getConfig().resToastText(), Toast.LENGTH_LONG); sentToastTimeMillis.setInitialTimeMillis(System.currentTimeMillis()); Looper.loop(); } }.start(); // We will wait a few seconds at the end of the method to be sure // that the Toast can be read by the user. } final CrashReportData crashReportData = crashReportDataFactory.createCrashData(reportBuilder.mMessage, reportBuilder.mException, reportBuilder.mCustomData, reportBuilder.mForceSilent, reportBuilder.mUncaughtExceptionThread); // Always write the report file final String reportFileName = getReportFileName(crashReportData); saveCrashReportFile(reportFileName, crashReportData); if (reportBuilder.mEndsApplication && !ACRA.getConfig().sendReportsAtShutdown()) { endApplication(reportBuilder.mUncaughtExceptionThread, reportBuilder.mException); } if (reportingInteractionMode == ReportingInteractionMode.SILENT || reportingInteractionMode == ReportingInteractionMode.TOAST || prefs.getBoolean(ACRA.PREF_ALWAYS_ACCEPT, false)) { // Approve and then send reports now startSendingReports(sendOnlySilentReports, true); if ((reportingInteractionMode == ReportingInteractionMode.SILENT) && !reportBuilder.mEndsApplication) { // Report is being sent silently and the application is not ending. // So no need to wait around for the sender to complete. return; } } else if (reportingInteractionMode == ReportingInteractionMode.NOTIFICATION) { ACRA.log.d(LOG_TAG, "Creating Notification."); createNotification(reportFileName, reportBuilder); } toastWaitEnded = true; if (shouldDisplayToast) { // A toast is being displayed, we have to wait for its end before doing anything else. // The toastWaitEnded flag will be checked before any other operation. toastWaitEnded = false; new Thread() { @Override public void run() { ACRA.log.d(LOG_TAG, "Waiting for " + ACRAConstants.TOAST_WAIT_DURATION + " millis from " + sentToastTimeMillis.initialTimeMillis + " currentMillis=" + System.currentTimeMillis()); while (sentToastTimeMillis.getElapsedTime() < ACRAConstants.TOAST_WAIT_DURATION) { try { // Wait a bit to let the user read the toast Thread.sleep(100); } catch (InterruptedException e1) { ACRA.log.d(LOG_TAG, "Interrupted while waiting for Toast to end.", e1); } } toastWaitEnded = true; } }.start(); } final boolean showDirectDialog = (reportingInteractionMode == ReportingInteractionMode.DIALOG) && !prefs.getBoolean(ACRA.PREF_ALWAYS_ACCEPT, false); new Thread() { @Override public void run() { // We have to wait for the toast display to be completed. ACRA.log.d(LOG_TAG, "Waiting for Toast"); while (!toastWaitEnded) { try { Thread.sleep(100); } catch (InterruptedException e1) { ACRA.log.d(LOG_TAG, "Error : ", e1); } } ACRA.log.d(LOG_TAG, "Finished waiting for Toast"); if (showDirectDialog) { // Create a new activity task with the confirmation dialog. // This new task will be persisted on application restart // right after its death. ACRA.log.d(LOG_TAG, "Creating CrashReportDialog for " + reportFileName); final Intent dialogIntent = createCrashReportDialogIntent(reportFileName, reportBuilder); dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(dialogIntent); } ACRA.log.d(LOG_TAG, "Wait for Toast + worker ended. Kill Application ? " + reportBuilder.mEndsApplication); if (reportBuilder.mEndsApplication) { endApplication(reportBuilder.mUncaughtExceptionThread, reportBuilder.mException); } } }.start(); } /** * Creates an Intent that can be used to create and show a CrashReportDialog. * * @param reportFileName Name of the error report to display in the crash report dialog. * @param reportBuilder ReportBuilder containing the details of the crash. */ private Intent createCrashReportDialogIntent(String reportFileName, ReportBuilder reportBuilder) { ACRA.log.d(LOG_TAG, "Creating DialogIntent for " + reportFileName + " exception=" + reportBuilder.mException); final Intent dialogIntent = new Intent(mContext, ACRA.getConfig().reportDialogClass()); dialogIntent.putExtra(ACRAConstants.EXTRA_REPORT_FILE_NAME, reportFileName); dialogIntent.putExtra(ACRAConstants.EXTRA_REPORT_EXCEPTION, reportBuilder.mException); return dialogIntent; } /** * Creates a status bar notification. * * The action triggered when the notification is selected is to start the * {@link CrashReportDialog} Activity. * * @param reportFileName Name of the report file to send. */ private void createNotification(String reportFileName, ReportBuilder reportBuilder) { final NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE); final ReportsCrashes conf = ACRA.getConfig(); // Default notification icon is the warning symbol final int icon = conf.resNotifIcon(); final CharSequence tickerText = mContext.getText(conf.resNotifTickerText()); final long when = System.currentTimeMillis(); ACRA.log.d(LOG_TAG, "Creating Notification for " + reportFileName); final Intent crashReportDialogIntent = createCrashReportDialogIntent(reportFileName, reportBuilder); final PendingIntent contentIntent = PendingIntent.getActivity(mContext, mNotificationCounter++, crashReportDialogIntent, PendingIntent.FLAG_UPDATE_CURRENT); final CharSequence contentTitle = mContext.getText(conf.resNotifTitle()); final CharSequence contentText = mContext.getText(conf.resNotifText()); final NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext); final Notification notification = builder .setSmallIcon(icon) .setTicker(tickerText) .setWhen(when) .setAutoCancel(true) .setContentTitle(contentTitle) .setContentText(contentText) .setContentIntent(contentIntent) .build(); notification.flags = notification.flags | Notification.FLAG_AUTO_CANCEL; // The deleteIntent is invoked when the user swipes away the Notification. // In this case we invoke the CrashReportDialog with EXTRA_FORCE_CANCEL==true // which will cause BaseCrashReportDialog to clear the crash report and finish itself. final Intent deleteIntent = createCrashReportDialogIntent(reportFileName, reportBuilder); deleteIntent.putExtra(ACRAConstants.EXTRA_FORCE_CANCEL, true); notification.deleteIntent = PendingIntent.getActivity(mContext, -1, deleteIntent, 0); // Send new notification notificationManager.notify(ACRAConstants.NOTIF_CRASH_ID, notification); } private String getReportFileName(CrashReportData crashData) { final Calendar now = new GregorianCalendar(); final long timestamp = now.getTimeInMillis(); final String isSilent = crashData.getProperty(IS_SILENT); return "" + timestamp + (isSilent != null ? ACRAConstants.SILENT_SUFFIX : "") + ACRAConstants.REPORTFILE_EXTENSION; } /** * When a report can't be sent, it is saved here in a file in the root of * the application private directory. * * @param fileName * In a few rare cases, we write the report again with additional * data (user comment for example). In such cases, you can * provide the already existing file name here to overwrite the * report file. If null, a new file report will be generated * @param crashData * Can be used to save an alternative (or previously generated) * report data. Used to store again a report with the addition of * user comment. If null, the default current crash data are * used. */ private void saveCrashReportFile(String fileName, CrashReportData crashData) { try { ACRA.log.d(LOG_TAG, "Writing crash report file " + fileName + "."); final CrashReportPersister persister = new CrashReportPersister(mContext); persister.store(crashData, fileName); } catch (Exception e) { ACRA.log.e(LOG_TAG, "An error occurred while writing the report file...", e); } } /** * Delete pending reports. * * @param deleteApprovedReports * Set to true to delete approved and silent reports. * @param deleteNonApprovedReports * Set to true to delete non approved/silent reports. * @param nbOfLatestToKeep * Number of pending reports to retain. */ private void deletePendingReports(boolean deleteApprovedReports, boolean deleteNonApprovedReports, int nbOfLatestToKeep) { // TODO Check logic and instances where nbOfLatestToKeep = X, because // that might stop us from deleting any reports. final CrashReportFinder reportFinder = new CrashReportFinder(mContext); final String[] filesList = reportFinder.getCrashReportFiles(); Arrays.sort(filesList); for (int iFile = 0; iFile < filesList.length - nbOfLatestToKeep; iFile++) { final String fileName = filesList[iFile]; final boolean isReportApproved = fileNameParser.isApproved(fileName); if ((isReportApproved && deleteApprovedReports) || (!isReportApproved && deleteNonApprovedReports)) { final File fileToDelete = new File(mContext.getFilesDir(), fileName); ACRA.log.d(LOG_TAG, "Deleting file " + fileName); if (!fileToDelete.delete()) { ACRA.log.e(LOG_TAG, "Could not delete report : " + fileToDelete); } } } } /** * Checks if an array of reports files names contains only silent or * approved reports. * * @param reportFileNames * Array of report locations to check. * @return True if there are only silent or approved reports. False if there * is at least one non-approved report. */ private boolean containsOnlySilentOrApprovedReports(String[] reportFileNames) { for (String reportFileName : reportFileNames) { if (!fileNameParser.isApproved(reportFileName)) { return false; } } return true; } /** * Fluent API used to assemble the different options used for a crash report */ public final class ReportBuilder { private String mMessage; private Thread mUncaughtExceptionThread; private Throwable mException; private Map<String, String> mCustomData; private boolean mForceSilent = false; private boolean mEndsApplication = false; /** * Set the error message to be reported. * * @param msg the error message * @return the updated {@code ReportBuilder} */ public ReportBuilder message(String msg) { mMessage = msg; return this; } /** * Sets the Thread on which an uncaught Exception occurred. * * @param thread Thread on which an uncaught Exception occurred. * @return the updated {@code ReportBuilder} */ private ReportBuilder uncaughtExceptionThread(Thread thread) { mUncaughtExceptionThread = thread; return this; } /** * Set the stack trace to be reported * * @param e The exception that should be associated with this report * @return the updated {@code ReportBuilder} */ public ReportBuilder exception(Throwable e) { mException = e; return this; } private void initCustomData() { if (mCustomData == null) mCustomData = new HashMap<String, String>(); } /** * Sets additional values to be added to {@code CUSTOM_DATA}. Values * specified here take precedence over globally specified custom data. * * @param customData a map of custom key-values to be attached to the report * @return the updated {@code ReportBuilder} */ @SuppressWarnings("unused") public ReportBuilder customData(Map<String, String> customData) { initCustomData(); mCustomData.putAll(customData); return this; } /** * Sets an additional value to be added to {@code CUSTOM_DATA}. The value * specified here takes precedence over globally specified custom data. * * @param key the key identifying the custom data * @param value the value for the custom data entry * @return the updated {@code ReportBuilder} */ @SuppressWarnings("unused") public ReportBuilder customData(String key, String value) { initCustomData(); mCustomData.put(key, value); return this; } /** * Forces the report to be sent silently, ignoring the default interaction mode set in the config * * @return the updated {@code ReportBuilder} */ public ReportBuilder forceSilent() { mForceSilent = true; return this; } /** * Ends the application after sending the crash report * * @return the updated {@code ReportBuilder} */ public ReportBuilder endsApplication() { mEndsApplication = true; return this; } /** * Assembles and sends the crash report */ public void send() { if (mMessage == null && mException == null) { mMessage = "Report requested by developer"; } report(this); } } }
src/main/java/org/acra/ErrorReporter.java
/* * Copyright 2010 Emmanuel Astier & Kevin Gaudin * * 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.acra; import android.Manifest.permission; import android.app.Activity; import android.app.Application; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.os.Bundle; import android.os.Looper; import android.support.v4.app.NotificationCompat; import android.widget.Toast; import org.acra.annotation.ReportsCrashes; import org.acra.collector.Compatibility; import org.acra.collector.ConfigurationCollector; import org.acra.collector.CrashReportData; import org.acra.collector.CrashReportDataFactory; import org.acra.common.CrashReportFileNameParser; import org.acra.common.CrashReportFinder; import org.acra.common.CrashReportPersister; import org.acra.jraf.android.util.activitylifecyclecallbackscompat.ActivityLifecycleCallbacksCompat; import org.acra.jraf.android.util.activitylifecyclecallbackscompat.ApplicationHelper; import org.acra.sender.*; import org.acra.util.PackageManagerWrapper; import org.acra.util.ToastSender; import java.io.File; import java.lang.Thread.UncaughtExceptionHandler; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Map; import static org.acra.ACRA.LOG_TAG; import static org.acra.ReportField.IS_SILENT; /** * <p> * The ErrorReporter is a Singleton object in charge of collecting crash context * data and sending crash reports. It registers itself as the Application's * Thread default {@link UncaughtExceptionHandler}. * </p> * <p> * When a crash occurs, it collects data of the crash context (device, system, * stack trace...) and writes a report file in the application private * directory. This report file is then sent: * </p> * <ul> * <li>immediately if {@link ReportsCrashes#mode} is set to * {@link ReportingInteractionMode#SILENT} or * {@link ReportingInteractionMode#TOAST},</li> * <li>on application start if in the previous case the transmission could not * technically be made,</li> * <li>when the user accepts to send it if {@link ReportsCrashes#mode()} is set * to {@link ReportingInteractionMode#NOTIFICATION}.</li> * </ul> * <p> * If an error occurs while sending a report, it is kept for later attempts. * </p> */ public class ErrorReporter implements Thread.UncaughtExceptionHandler { private final boolean supportedAndroidVersion; private boolean enabled = false; private final Application mContext; private final SharedPreferences prefs; /** * Contains the active {@link ReportSender}s. */ private final ArrayList<Class<? extends ReportSenderFactory>> reportSenderFactories = new ArrayList<Class<? extends ReportSenderFactory>>(); private final CrashReportDataFactory crashReportDataFactory; private final CrashReportFileNameParser fileNameParser = new CrashReportFileNameParser(); // A reference to the system's previous default UncaughtExceptionHandler // kept in order to execute the default exception handling after sending the report. private final Thread.UncaughtExceptionHandler mDfltExceptionHandler; private WeakReference<Activity> lastActivityCreated = new WeakReference<Activity>(null); /** * This is used to wait for the crash toast to end it's display duration * before killing the Application. */ private boolean toastWaitEnded = true; private static final ExceptionHandlerInitializer NULL_EXCEPTION_HANDLER_INITIALIZER = new ExceptionHandlerInitializer() { @Override public void initializeExceptionHandler(ErrorReporter reporter) { } }; private volatile ExceptionHandlerInitializer exceptionHandlerInitializer = NULL_EXCEPTION_HANDLER_INITIALIZER; /** * Used to create a new (non-cached) PendingIntent each time a new crash occurs. */ private static int mNotificationCounter = 0; /** * Can only be constructed from within this class. * * @param context Context for the application in which ACRA is running. * @param prefs SharedPreferences used by ACRA. * @param enabled Whether this ErrorReporter should capture Exceptions and forward their reports. * @param listenForUncaughtExceptions Whether to listen for uncaught Exceptions. */ ErrorReporter(Application context, SharedPreferences prefs, boolean enabled, boolean supportedAndroidVersion, boolean listenForUncaughtExceptions) { this.mContext = context; this.prefs = prefs; this.enabled = enabled; this.supportedAndroidVersion = supportedAndroidVersion; this.reportSenderFactories.addAll(Arrays.asList(ACRA.getConfig().reportSenderFactoryClasses())); // Store the initial Configuration state. // This is expensive to gather, so only do so if we plan to report it. final String initialConfiguration; if (ACRA.getConfig().getReportFields().contains(ReportField.INITIAL_CONFIGURATION)) { initialConfiguration = ConfigurationCollector.collectConfiguration(mContext); } else { initialConfiguration = null; } // Sets the application start date. // This will be included in the reports, will be helpful compared to user_crash date. final Calendar appStartDate = new GregorianCalendar(); if (Compatibility.getAPILevel() >= Compatibility.VERSION_CODES.ICE_CREAM_SANDWICH) { // ActivityLifecycleCallback // only available for API14+ ApplicationHelper.registerActivityLifecycleCallbacks(context, new ActivityLifecycleCallbacksCompat() { @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { if (ACRA.DEV_LOGGING) ACRA.log.d(LOG_TAG, "onActivityCreated " + activity.getClass()); if (!(activity instanceof BaseCrashReportDialog)) { // Ignore CrashReportDialog because we want the last // application Activity that was started so that we can explicitly kill it off. lastActivityCreated = new WeakReference<Activity>(activity); } } @Override public void onActivityStarted(Activity activity) { if (ACRA.DEV_LOGGING) ACRA.log.d(LOG_TAG, "onActivityStarted " + activity.getClass()); } @Override public void onActivityResumed(Activity activity) { if (ACRA.DEV_LOGGING) ACRA.log.d(LOG_TAG, "onActivityResumed " + activity.getClass()); } @Override public void onActivityPaused(Activity activity) { if (ACRA.DEV_LOGGING) ACRA.log.d(LOG_TAG, "onActivityPaused " + activity.getClass()); } @Override public void onActivityStopped(Activity activity) { if (ACRA.DEV_LOGGING) ACRA.log.d(LOG_TAG, "onActivityStopped " + activity.getClass()); } @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) { if (ACRA.DEV_LOGGING) ACRA.log.i(LOG_TAG, "onActivitySaveInstanceState " + activity.getClass()); } @Override public void onActivityDestroyed(Activity activity) { if (ACRA.DEV_LOGGING) ACRA.log.i(LOG_TAG, "onActivityDestroyed " + activity.getClass()); } }); } crashReportDataFactory = new CrashReportDataFactory(mContext, prefs, appStartDate, initialConfiguration); if (listenForUncaughtExceptions) { mDfltExceptionHandler = Thread.getDefaultUncaughtExceptionHandler(); Thread.setDefaultUncaughtExceptionHandler(this); } else { mDfltExceptionHandler = null; } } /** * @return the current instance of ErrorReporter. * @throws IllegalStateException * if {@link ACRA#init(android.app.Application)} has not yet * been called. * @deprecated since 4.3.0 Use {@link org.acra.ACRA#getErrorReporter()} * instead. */ @SuppressWarnings("unused") @Deprecated public static ErrorReporter getInstance() { return ACRA.getErrorReporter(); } /** * Deprecated. Use {@link #putCustomData(String, String)}. * * @param key * A key for your custom data. * @param value * The value associated to your key. */ @Deprecated @SuppressWarnings("unused") public void addCustomData(String key, String value) { crashReportDataFactory.putCustomData(key, value); } /** * <p> * Use this method to provide the ErrorReporter with data of your running * application. You should call this at several key places in your code the * same way as you would output important debug data in a log file. Only the * latest value is kept for each key (no history of the values is sent in * the report). * </p> * <p> * The key/value pairs will be stored in the GoogleDoc spreadsheet in the * "custom" column, as a text containing a 'key = value' pair on each line. * </p> * * @param key A key for your custom data. * @param value The value associated to your key. * @return The previous value for this key if there was one, or null. * @see #removeCustomData(String) * @see #getCustomData(String) */ @SuppressWarnings("unused") public String putCustomData(String key, String value) { return crashReportDataFactory.putCustomData(key, value); } /** * <p> * Use this method to perform additional initialization before the * ErrorReporter handles a throwable. This can be used, for example, to put * custom data using {@link #putCustomData(String, String)}, which is not * available immediately after startup. It can be, for example, last 20 * requests or something else. The call is thread safe. * </p> * <p> * {@link ExceptionHandlerInitializer#initializeExceptionHandler(ErrorReporter)} * will be executed on the main thread in case of uncaught exception and on * the caller thread of {@link #handleSilentException(Throwable)} or * {@link #handleException(Throwable)}. * </p> * <p> * Example. Add to the {@link Application#onCreate()}: * </p> * * <pre> * ACRA.getErrorReporter().setExceptionHandlerInitializer(new ExceptionHandlerInitializer() { * <code>@Override</code> public void initializeExceptionHandler(ErrorReporter reporter) { * reporter.putCustomData("CUSTOM_ACCUMULATED_DATA_TAG", someAccumulatedData.toString); * } * }); * </pre> * * @param initializer The initializer. Can be <code>null</code>. */ public void setExceptionHandlerInitializer(ExceptionHandlerInitializer initializer) { exceptionHandlerInitializer = (initializer != null) ? initializer : NULL_EXCEPTION_HANDLER_INITIALIZER; } /** * Removes a key/value pair from your reports custom data field. * * @param key The key of the data to be removed. * @return The value for this key before removal. * @see #putCustomData(String, String) * @see #getCustomData(String) */ @SuppressWarnings("unused") public String removeCustomData(String key) { return crashReportDataFactory.removeCustomData(key); } /** * Removes all key/value pairs from your reports custom data field. */ @SuppressWarnings("unused") public void clearCustomData() { crashReportDataFactory.clearCustomData(); } /** * Gets the current value for a key in your reports custom data field. * * @param key * The key of the data to be retrieved. * @return The value for this key. * @see #putCustomData(String, String) * @see #removeCustomData(String) */ @SuppressWarnings("unused") public String getCustomData(String key) { return crashReportDataFactory.getCustomData(key); } /** * Adds a ReportSenderFactory to the list of factories that will construct {@link ReportSender}s when sending reports. * * Note: you can declare your {@link ReportSenderFactory}s via {@link ReportsCrashes#reportSenderFactoryClasses()}. * * @param senderFactory ReportSenderFactory to add tto the list of existing factories. * @since 4.8.0 */ @SuppressWarnings("unused") public void addReportSenderFactory(Class<? extends ReportSenderFactory> senderFactory) { reportSenderFactories.add(senderFactory); } /** * Remove a {@link ReportSenderFactory} from the list of factories * that will construct {@link ReportSender}s when sending reports. * * Note: you can declare your {@link ReportSenderFactory}s via {@link ReportsCrashes#reportSenderFactoryClasses()}. * * @param senderFactory The {@link ReportSender} class to be removed. * @since 4.8.0 */ @SuppressWarnings("unused") public void removeReportSenderFactory(Class<? extends ReportSenderFactory> senderFactory) { reportSenderFactories.remove(senderFactory); } /** * Clears the list of active {@link ReportSender}s. * * You should then call {@link #addReportSenderFactory(Class)} or ACRA will not send any reports. */ @SuppressWarnings("unused") public void removeAllReportSenders() { reportSenderFactories.clear(); } /** * Removes all previously set {@link ReportSenderFactory}s and set the given one as the sole {@link ReportSenderFactory}. * * Note: you can declare your {@link ReportSenderFactory}s via {@link ReportsCrashes#reportSenderFactoryClasses()}. * * @param senderFactory ReportSenderFactory to set as the creator of {@link ReportSender}s for this ErrorReporter. */ @SuppressWarnings("unused") public void setReportSenderFactory(Class<? extends ReportSenderFactory> senderFactory) { reportSenderFactories.clear(); reportSenderFactories.add(senderFactory); } /* * (non-Javadoc) * * @see * java.lang.Thread.UncaughtExceptionHandler#uncaughtException(java.lang * .Thread, java.lang.Throwable) */ @Override public void uncaughtException(Thread t, Throwable e) { try { // If we're not enabled then just pass the Exception on to any // defaultExceptionHandler. if (!enabled) { if (mDfltExceptionHandler != null) { ACRA.log.e(LOG_TAG, "ACRA is disabled for " + mContext.getPackageName() + " - forwarding uncaught Exception on to default ExceptionHandler"); mDfltExceptionHandler.uncaughtException(t, e); } else { ACRA.log.e(LOG_TAG, "ACRA is disabled for " + mContext.getPackageName() + " - no default ExceptionHandler"); ACRA.log.e(LOG_TAG, "ACRA caught a " + e.getClass().getSimpleName() + " for " + mContext.getPackageName(), e); } return; } ACRA.log.e(LOG_TAG, "ACRA caught a " + e.getClass().getSimpleName() + " for " + mContext.getPackageName(), e); ACRA.log.d(LOG_TAG, "Building report"); // Generate and send crash report reportBuilder() .uncaughtExceptionThread(t) .exception(e) .endsApplication() .send(); } catch (Throwable fatality) { // ACRA failed. Prevent any recursive call to // ACRA.uncaughtException(), let the native reporter do its job. if (mDfltExceptionHandler != null) { mDfltExceptionHandler.uncaughtException(t, e); } } } /** * End the application. */ private void endApplication(Thread uncaughtExceptionThread, Throwable th) { // TODO It would be better to create an explicit config attribute #letDefaultHandlerEndApplication // as the intent is clearer and would allows you to switch it off for SILENT. final boolean letDefaultHandlerEndApplication = ( ACRA.getConfig().mode() == ReportingInteractionMode.SILENT || (ACRA.getConfig().mode() == ReportingInteractionMode.TOAST && ACRA.getConfig().forceCloseDialogAfterToast()) ); final boolean handlingUncaughtException = uncaughtExceptionThread != null; if (handlingUncaughtException && letDefaultHandlerEndApplication && (mDfltExceptionHandler != null)) { // Let the system default handler do it's job and display the force close dialog. ACRA.log.d(LOG_TAG, "Handing Exception on to default ExceptionHandler"); mDfltExceptionHandler.uncaughtException(uncaughtExceptionThread, th); } else { // If ACRA handles user notifications with a Toast or a Notification // the Force Close dialog is one more notification to the user... // We choose to close the process ourselves using the same actions. // Trying to solve https://github.com/ACRA/acra/issues/42#issuecomment-12134144 // Determine the current/last Activity that was started and close // it. Activity#finish (and maybe it's parent too). final Activity lastActivity = lastActivityCreated.get(); if (lastActivity != null) { ACRA.log.i(LOG_TAG, "Finishing the last Activity prior to killing the Process"); lastActivity.finish(); ACRA.log.i(LOG_TAG, "Finished " + lastActivity.getClass()); lastActivityCreated.clear(); } android.os.Process.killProcess(android.os.Process.myPid()); System.exit(10); } } /** * Send a report for this {@link Throwable} silently (forces the use of * {@link ReportingInteractionMode#SILENT} for this report, whatever is the * mode set for the application. Very useful for tracking difficult defects. * * @param e * The {@link Throwable} to be reported. If null the report will * contain a new Exception("Report requested by developer"). */ public void handleSilentException(Throwable e) { // Mark this report as silent. if (enabled) { reportBuilder() .exception(e) .forceSilent() .send(); ACRA.log.d(LOG_TAG, "ACRA sent Silent report."); return; } ACRA.log.d(LOG_TAG, "ACRA is disabled. Silent report not sent."); } /** * Enable or disable this ErrorReporter. By default it is enabled. * * @param enabled * Whether this ErrorReporter should capture Exceptions and * forward them as crash reports. */ public void setEnabled(boolean enabled) { if (!supportedAndroidVersion) { ACRA.log.w(LOG_TAG, "ACRA 4.7.0+ requires Froyo or greater. ACRA is disabled and will NOT catch crashes or send messages."); } else { ACRA.log.i(LOG_TAG, "ACRA is " + (enabled ? "enabled" : "disabled") + " for " + mContext.getPackageName()); this.enabled = enabled; } } /** * Starts a Thread to start sending outstanding error reports. * * @param onlySendSilentReports * If true then only send silent reports. * @param approveReportsFirst * If true then approve unapproved reports first. */ void startSendingReports(boolean onlySendSilentReports, boolean approveReportsFirst) { ACRA.log.v(LOG_TAG, "About to start SenderService"); final Intent intent = new Intent(mContext, SenderService.class); intent.putExtra(SenderService.EXTRA_ONLY_SEND_SILENT_REPORTS, onlySendSilentReports); intent.putExtra(SenderService.EXTRA_APPROVE_REPORTS_FIRST, approveReportsFirst); intent.putExtra(SenderService.EXTRA_REPORT_SENDER_FACTORIES, reportSenderFactories); mContext.startService(intent); } /** * Delete all report files stored. */ void deletePendingReports() { deletePendingReports(true, true, 0); } /** * This method looks for pending reports and does the action required * depending on the interaction mode set. */ public void checkReportsOnApplicationStart() { if (ACRA.getConfig().deleteOldUnsentReportsOnApplicationStart()) { // Delete any old unsent reports if this is a newer version of the app // than when we last started. final long lastVersionNr = prefs.getInt(ACRA.PREF_LAST_VERSION_NR, 0); final PackageManagerWrapper packageManagerWrapper = new PackageManagerWrapper(mContext); final PackageInfo packageInfo = packageManagerWrapper.getPackageInfo(); if (packageInfo != null) { final boolean newVersion = packageInfo.versionCode > lastVersionNr; if (newVersion) { deletePendingReports(); } final SharedPreferences.Editor prefsEditor = prefs.edit(); prefsEditor.putInt(ACRA.PREF_LAST_VERSION_NR, packageInfo.versionCode); prefsEditor.commit(); } } ReportingInteractionMode reportingInteractionMode = ACRA.getConfig().mode(); if ((reportingInteractionMode == ReportingInteractionMode.NOTIFICATION || reportingInteractionMode == ReportingInteractionMode.DIALOG) && ACRA.getConfig().deleteUnapprovedReportsOnApplicationStart()) { // NOTIFICATION or DIALOG mode, and there are unapproved reports to // send (latest notification/dialog has been ignored: neither // accepted // nor refused). The application developer has decided that // these reports should not be renotified ==> destroy them all but // one. deletePendingNonApprovedReports(true); } final CrashReportFinder reportFinder = new CrashReportFinder(mContext); String[] filesList = reportFinder.getCrashReportFiles(); if (filesList != null && filesList.length > 0) { // Immediately send reports for SILENT and TOAST modes. // Immediately send reports in NOTIFICATION mode only if they are // all silent or approved. // If there is still one unapproved report in NOTIFICATION mode, // notify it. // If there are unapproved reports in DIALOG mode, show the dialog final boolean onlySilentOrApprovedReports = containsOnlySilentOrApprovedReports(filesList); if (reportingInteractionMode == ReportingInteractionMode.SILENT || reportingInteractionMode == ReportingInteractionMode.TOAST || (onlySilentOrApprovedReports && (reportingInteractionMode == ReportingInteractionMode.NOTIFICATION || reportingInteractionMode == ReportingInteractionMode.DIALOG))) { if (reportingInteractionMode == ReportingInteractionMode.TOAST && !onlySilentOrApprovedReports) { // Display the Toast in TOAST mode only if there are // non-silent reports. ToastSender.sendToast(mContext, ACRA.getConfig().resToastText(), Toast.LENGTH_LONG); } startSendingReports(false, false); } } } /** * Delete all pending non approved reports. * * @param keepOne * If you need to keep the latest report, set this to true. */ void deletePendingNonApprovedReports(boolean keepOne) { // In NOTIFICATION AND DIALOG mode, we have to keep the latest report // which // has been written before killing the app. final int nbReportsToKeep = keepOne ? 1 : 0; deletePendingReports(false, true, nbReportsToKeep); } /** * Send a report for a {@link Throwable} with the reporting interaction mode * configured by the developer. * * @param e * The {@link Throwable} to be reported. If null the report will * contain a new Exception("Report requested by developer"). * @param endApplication * Set this to true if you want the application to be ended after * sending the report. */ @SuppressWarnings("unused") public void handleException(Throwable e, boolean endApplication) { final ReportBuilder builder = reportBuilder() .exception(e); if (endApplication) { builder.endsApplication(); } builder.send(); } /** * Send a report for a {@link Throwable} with the reporting interaction mode * configured by the developer, the application is then killed and restarted * by the system. * * @param e * The {@link Throwable} to be reported. If null the report will * contain a new Exception("Report requested by developer"). */ @SuppressWarnings("unused") public void handleException(Throwable e) { reportBuilder() .exception(e) .send(); } /** * Creates a new crash report builder * * @return the newly created {@code ReportBuilder} */ public ReportBuilder reportBuilder() { return new ReportBuilder(); } /** * Helps manage */ private static class TimeHelper { private Long initialTimeMillis; public void setInitialTimeMillis(long initialTimeMillis) { this.initialTimeMillis = initialTimeMillis; } /** * @return 0 if the initial time has yet to be set otherwise returns the difference between now and the initial time. */ public long getElapsedTime() { return (initialTimeMillis == null) ? 0 : System.currentTimeMillis() - initialTimeMillis; } } /** * Try to send a report, if an error occurs stores a report file for a later * attempt. * * @param reportBuilder The report builder used to assemble the report */ private void report(final ReportBuilder reportBuilder) { if (!enabled) { return; } try { exceptionHandlerInitializer.initializeExceptionHandler(this); } catch (Exception exceptionInRunnable) { ACRA.log.d(LOG_TAG, "Failed to initialize " + exceptionHandlerInitializer + " from #handleException"); } boolean sendOnlySilentReports = false; ReportingInteractionMode reportingInteractionMode; if (!reportBuilder.mForceSilent) { // No interaction mode defined in the ReportBuilder, we assume it has been set during ACRA.initACRA() reportingInteractionMode = ACRA.getConfig().mode(); } else { reportingInteractionMode = ReportingInteractionMode.SILENT; // An interaction mode has been provided. If ACRA has been // initialized with a non SILENT mode and this mode is overridden // with SILENT, then we have to send only reports which have been // explicitly declared as silent via handleSilentException(). if (ACRA.getConfig().mode() != ReportingInteractionMode.SILENT) { sendOnlySilentReports = true; } } final boolean shouldDisplayToast = reportingInteractionMode == ReportingInteractionMode.TOAST || (ACRA.getConfig().resToastText() != 0 && (reportingInteractionMode == ReportingInteractionMode.NOTIFICATION || reportingInteractionMode == ReportingInteractionMode.DIALOG)); final TimeHelper sentToastTimeMillis = new TimeHelper(); if (shouldDisplayToast) { new Thread() { /* * (non-Javadoc) * * @see java.lang.Thread#run() */ @Override public void run() { Looper.prepare(); ToastSender.sendToast(mContext, ACRA.getConfig().resToastText(), Toast.LENGTH_LONG); sentToastTimeMillis.setInitialTimeMillis(System.currentTimeMillis()); Looper.loop(); } }.start(); // We will wait a few seconds at the end of the method to be sure // that the Toast can be read by the user. } final CrashReportData crashReportData = crashReportDataFactory.createCrashData(reportBuilder.mMessage, reportBuilder.mException, reportBuilder.mCustomData, reportBuilder.mForceSilent, reportBuilder.mUncaughtExceptionThread); // Always write the report file final String reportFileName = getReportFileName(crashReportData); saveCrashReportFile(reportFileName, crashReportData); if (reportBuilder.mEndsApplication && !ACRA.getConfig().sendReportsAtShutdown()) { endApplication(reportBuilder.mUncaughtExceptionThread, reportBuilder.mException); } if (reportingInteractionMode == ReportingInteractionMode.SILENT || reportingInteractionMode == ReportingInteractionMode.TOAST || prefs.getBoolean(ACRA.PREF_ALWAYS_ACCEPT, false)) { // Approve and then send reports now startSendingReports(sendOnlySilentReports, true); if ((reportingInteractionMode == ReportingInteractionMode.SILENT) && !reportBuilder.mEndsApplication) { // Report is being sent silently and the application is not ending. // So no need to wait around for the sender to complete. return; } } else if (reportingInteractionMode == ReportingInteractionMode.NOTIFICATION) { ACRA.log.d(LOG_TAG, "Creating Notification."); createNotification(reportFileName, reportBuilder); } toastWaitEnded = true; if (shouldDisplayToast) { // A toast is being displayed, we have to wait for its end before doing anything else. // The toastWaitEnded flag will be checked before any other operation. toastWaitEnded = false; new Thread() { @Override public void run() { ACRA.log.d(LOG_TAG, "Waiting for " + ACRAConstants.TOAST_WAIT_DURATION + " millis from " + sentToastTimeMillis.initialTimeMillis + " currentMillis=" + System.currentTimeMillis()); while (sentToastTimeMillis.getElapsedTime() < ACRAConstants.TOAST_WAIT_DURATION) { try { // Wait a bit to let the user read the toast Thread.sleep(100); } catch (InterruptedException e1) { ACRA.log.d(LOG_TAG, "Interrupted while waiting for Toast to end.", e1); } } toastWaitEnded = true; } }.start(); } final boolean showDirectDialog = (reportingInteractionMode == ReportingInteractionMode.DIALOG) && !prefs.getBoolean(ACRA.PREF_ALWAYS_ACCEPT, false); new Thread() { @Override public void run() { // We have to wait for the toast display to be completed. ACRA.log.d(LOG_TAG, "Waiting for Toast"); while (!toastWaitEnded) { try { Thread.sleep(100); } catch (InterruptedException e1) { ACRA.log.d(LOG_TAG, "Error : ", e1); } } ACRA.log.d(LOG_TAG, "Finished waiting for Toast"); if (showDirectDialog) { // Create a new activity task with the confirmation dialog. // This new task will be persisted on application restart // right after its death. ACRA.log.d(LOG_TAG, "Creating CrashReportDialog for " + reportFileName); final Intent dialogIntent = createCrashReportDialogIntent(reportFileName, reportBuilder); dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(dialogIntent); } ACRA.log.d(LOG_TAG, "Wait for Toast + worker ended. Kill Application ? " + reportBuilder.mEndsApplication); if (reportBuilder.mEndsApplication) { endApplication(reportBuilder.mUncaughtExceptionThread, reportBuilder.mException); } } }.start(); } /** * Creates an Intent that can be used to create and show a CrashReportDialog. * * @param reportFileName Name of the error report to display in the crash report dialog. * @param reportBuilder ReportBuilder containing the details of the crash. */ private Intent createCrashReportDialogIntent(String reportFileName, ReportBuilder reportBuilder) { ACRA.log.d(LOG_TAG, "Creating DialogIntent for " + reportFileName + " exception=" + reportBuilder.mException); final Intent dialogIntent = new Intent(mContext, ACRA.getConfig().reportDialogClass()); dialogIntent.putExtra(ACRAConstants.EXTRA_REPORT_FILE_NAME, reportFileName); dialogIntent.putExtra(ACRAConstants.EXTRA_REPORT_EXCEPTION, reportBuilder.mException); return dialogIntent; } /** * Creates a status bar notification. * * The action triggered when the notification is selected is to start the * {@link CrashReportDialog} Activity. * * @param reportFileName Name of the report file to send. */ private void createNotification(String reportFileName, ReportBuilder reportBuilder) { final NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE); final ReportsCrashes conf = ACRA.getConfig(); // Default notification icon is the warning symbol final int icon = conf.resNotifIcon(); final CharSequence tickerText = mContext.getText(conf.resNotifTickerText()); final long when = System.currentTimeMillis(); ACRA.log.d(LOG_TAG, "Creating Notification for " + reportFileName); final Intent crashReportDialogIntent = createCrashReportDialogIntent(reportFileName, reportBuilder); final PendingIntent contentIntent = PendingIntent.getActivity(mContext, mNotificationCounter++, crashReportDialogIntent, PendingIntent.FLAG_UPDATE_CURRENT); final CharSequence contentTitle = mContext.getText(conf.resNotifTitle()); final CharSequence contentText = mContext.getText(conf.resNotifText()); final NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext); final Notification notification = builder .setSmallIcon(icon) .setTicker(tickerText) .setWhen(when) .setAutoCancel(true) .setContentTitle(contentTitle) .setContentText(contentText) .setContentIntent(contentIntent) .build(); notification.flags = notification.flags | Notification.FLAG_AUTO_CANCEL; // The deleteIntent is invoked when the user swipes away the Notification. // In this case we invoke the CrashReportDialog with EXTRA_FORCE_CANCEL==true // which will cause BaseCrashReportDialog to clear the crash report and finish itself. final Intent deleteIntent = createCrashReportDialogIntent(reportFileName, reportBuilder); deleteIntent.putExtra(ACRAConstants.EXTRA_FORCE_CANCEL, true); notification.deleteIntent = PendingIntent.getActivity(mContext, -1, deleteIntent, 0); // Send new notification notificationManager.notify(ACRAConstants.NOTIF_CRASH_ID, notification); } private String getReportFileName(CrashReportData crashData) { final Calendar now = new GregorianCalendar(); final long timestamp = now.getTimeInMillis(); final String isSilent = crashData.getProperty(IS_SILENT); return "" + timestamp + (isSilent != null ? ACRAConstants.SILENT_SUFFIX : "") + ACRAConstants.REPORTFILE_EXTENSION; } /** * When a report can't be sent, it is saved here in a file in the root of * the application private directory. * * @param fileName * In a few rare cases, we write the report again with additional * data (user comment for example). In such cases, you can * provide the already existing file name here to overwrite the * report file. If null, a new file report will be generated * @param crashData * Can be used to save an alternative (or previously generated) * report data. Used to store again a report with the addition of * user comment. If null, the default current crash data are * used. */ private void saveCrashReportFile(String fileName, CrashReportData crashData) { try { ACRA.log.d(LOG_TAG, "Writing crash report file " + fileName + "."); final CrashReportPersister persister = new CrashReportPersister(mContext); persister.store(crashData, fileName); } catch (Exception e) { ACRA.log.e(LOG_TAG, "An error occurred while writing the report file...", e); } } /** * Delete pending reports. * * @param deleteApprovedReports * Set to true to delete approved and silent reports. * @param deleteNonApprovedReports * Set to true to delete non approved/silent reports. * @param nbOfLatestToKeep * Number of pending reports to retain. */ private void deletePendingReports(boolean deleteApprovedReports, boolean deleteNonApprovedReports, int nbOfLatestToKeep) { // TODO Check logic and instances where nbOfLatestToKeep = X, because // that might stop us from deleting any reports. final CrashReportFinder reportFinder = new CrashReportFinder(mContext); final String[] filesList = reportFinder.getCrashReportFiles(); Arrays.sort(filesList); for (int iFile = 0; iFile < filesList.length - nbOfLatestToKeep; iFile++) { final String fileName = filesList[iFile]; final boolean isReportApproved = fileNameParser.isApproved(fileName); if ((isReportApproved && deleteApprovedReports) || (!isReportApproved && deleteNonApprovedReports)) { final File fileToDelete = new File(mContext.getFilesDir(), fileName); ACRA.log.d(LOG_TAG, "Deleting file " + fileName); if (!fileToDelete.delete()) { ACRA.log.e(LOG_TAG, "Could not delete report : " + fileToDelete); } } } } /** * Checks if an array of reports files names contains only silent or * approved reports. * * @param reportFileNames * Array of report locations to check. * @return True if there are only silent or approved reports. False if there * is at least one non-approved report. */ private boolean containsOnlySilentOrApprovedReports(String[] reportFileNames) { for (String reportFileName : reportFileNames) { if (!fileNameParser.isApproved(reportFileName)) { return false; } } return true; } /** * Fluent API used to assemble the different options used for a crash report */ public final class ReportBuilder { private String mMessage; private Thread mUncaughtExceptionThread; private Throwable mException; private Map<String, String> mCustomData; private boolean mForceSilent = false; private boolean mEndsApplication = false; /** * Set the error message to be reported. * * @param msg the error message * @return the updated {@code ReportBuilder} */ public ReportBuilder message(String msg) { mMessage = msg; return this; } /** * Sets the Thread on which an uncaught Exception occurred. * * @param thread Thread on which an uncaught Exception occurred. * @return the updated {@code ReportBuilder} */ private ReportBuilder uncaughtExceptionThread(Thread thread) { mUncaughtExceptionThread = thread; return this; } /** * Set the stack trace to be reported * * @param e The exception that should be associated with this report * @return the updated {@code ReportBuilder} */ public ReportBuilder exception(Throwable e) { mException = e; return this; } private void initCustomData() { if (mCustomData == null) mCustomData = new HashMap<String, String>(); } /** * Sets additional values to be added to {@code CUSTOM_DATA}. Values * specified here take precedence over globally specified custom data. * * @param customData a map of custom key-values to be attached to the report * @return the updated {@code ReportBuilder} */ @SuppressWarnings("unused") public ReportBuilder customData(Map<String, String> customData) { initCustomData(); mCustomData.putAll(customData); return this; } /** * Sets an additional value to be added to {@code CUSTOM_DATA}. The value * specified here takes precedence over globally specified custom data. * * @param key the key identifying the custom data * @param value the value for the custom data entry * @return the updated {@code ReportBuilder} */ @SuppressWarnings("unused") public ReportBuilder customData(String key, String value) { initCustomData(); mCustomData.put(key, value); return this; } /** * Forces the report to be sent silently, ignoring the default interaction mode set in the config * * @return the updated {@code ReportBuilder} */ public ReportBuilder forceSilent() { mForceSilent = true; return this; } /** * Ends the application after sending the crash report * * @return the updated {@code ReportBuilder} */ public ReportBuilder endsApplication() { mEndsApplication = true; return this; } /** * Assembles and sends the crash report */ public void send() { if (mMessage == null && mException == null) { mMessage = "Report requested by developer"; } report(this); } } }
Don't send reports on startup unless ACRA has been enabled.
src/main/java/org/acra/ErrorReporter.java
Don't send reports on startup unless ACRA has been enabled.
<ide><path>rc/main/java/org/acra/ErrorReporter.java <ide> * If true then approve unapproved reports first. <ide> */ <ide> void startSendingReports(boolean onlySendSilentReports, boolean approveReportsFirst) { <del> ACRA.log.v(LOG_TAG, "About to start SenderService"); <del> final Intent intent = new Intent(mContext, SenderService.class); <del> intent.putExtra(SenderService.EXTRA_ONLY_SEND_SILENT_REPORTS, onlySendSilentReports); <del> intent.putExtra(SenderService.EXTRA_APPROVE_REPORTS_FIRST, approveReportsFirst); <del> intent.putExtra(SenderService.EXTRA_REPORT_SENDER_FACTORIES, reportSenderFactories); <del> mContext.startService(intent); <add> if (enabled) { <add> ACRA.log.v(LOG_TAG, "About to start SenderService"); <add> final Intent intent = new Intent(mContext, SenderService.class); <add> intent.putExtra(SenderService.EXTRA_ONLY_SEND_SILENT_REPORTS, onlySendSilentReports); <add> intent.putExtra(SenderService.EXTRA_APPROVE_REPORTS_FIRST, approveReportsFirst); <add> intent.putExtra(SenderService.EXTRA_REPORT_SENDER_FACTORIES, reportSenderFactories); <add> mContext.startService(intent); <add> } else { <add> ACRA.log.w(LOG_TAG, "Would be sending reports, but ACRA is disabled"); <add> } <ide> } <ide> <ide> /** <ide> } <ide> <ide> /** <del> * Try to send a report, if an error occurs stores a report file for a later <del> * attempt. <add> * Try to send a report, if an error occurs stores a report file for a later attempt. <ide> * <ide> * @param reportBuilder The report builder used to assemble the report <ide> */
Java
apache-2.0
add662907d8002a4c38196c4d8654a0db19a061a
0
guozhangwang/kafka,sslavic/kafka,guozhangwang/kafka,Chasego/kafka,noslowerdna/kafka,apache/kafka,Chasego/kafka,lindong28/kafka,lindong28/kafka,apache/kafka,Chasego/kafka,guozhangwang/kafka,noslowerdna/kafka,lindong28/kafka,noslowerdna/kafka,sslavic/kafka,TiVo/kafka,TiVo/kafka,lindong28/kafka,Chasego/kafka,apache/kafka,apache/kafka,noslowerdna/kafka,TiVo/kafka,guozhangwang/kafka,sslavic/kafka,sslavic/kafka,TiVo/kafka
/* * 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.kafka.trogdor.workload; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.node.TextNode; import org.apache.kafka.clients.admin.NewTopic; import org.apache.kafka.clients.producer.Callback; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.clients.producer.RecordMetadata; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.internals.KafkaFutureImpl; import org.apache.kafka.common.serialization.ByteArraySerializer; import org.apache.kafka.common.utils.Time; import org.apache.kafka.trogdor.common.JsonUtil; import org.apache.kafka.trogdor.common.Platform; import org.apache.kafka.trogdor.common.ThreadUtils; import org.apache.kafka.trogdor.common.WorkerUtils; import org.apache.kafka.trogdor.task.TaskWorker; import org.apache.kafka.trogdor.task.WorkerStatusTracker; import org.apache.kafka.trogdor.workload.TransactionGenerator.TransactionAction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Optional; import java.util.Properties; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; public class ProduceBenchWorker implements TaskWorker { private static final Logger log = LoggerFactory.getLogger(ProduceBenchWorker.class); private static final int THROTTLE_PERIOD_MS = 100; private final String id; private final ProduceBenchSpec spec; private final AtomicBoolean running = new AtomicBoolean(false); private ScheduledExecutorService executor; private WorkerStatusTracker status; private KafkaFutureImpl<String> doneFuture; public ProduceBenchWorker(String id, ProduceBenchSpec spec) { this.id = id; this.spec = spec; } @Override public void start(Platform platform, WorkerStatusTracker status, KafkaFutureImpl<String> doneFuture) throws Exception { if (!running.compareAndSet(false, true)) { throw new IllegalStateException("ProducerBenchWorker is already running."); } log.info("{}: Activating ProduceBenchWorker with {}", id, spec); // Create an executor with 2 threads. We need the second thread so // that the StatusUpdater can run in parallel with SendRecords. this.executor = Executors.newScheduledThreadPool(2, ThreadUtils.createThreadFactory("ProduceBenchWorkerThread%d", false)); this.status = status; this.doneFuture = doneFuture; executor.submit(new Prepare()); } public class Prepare implements Runnable { @Override public void run() { try { Map<String, NewTopic> newTopics = new HashMap<>(); HashSet<TopicPartition> active = new HashSet<>(); for (Map.Entry<String, PartitionsSpec> entry : spec.activeTopics().materialize().entrySet()) { String topicName = entry.getKey(); PartitionsSpec partSpec = entry.getValue(); newTopics.put(topicName, partSpec.newTopic(topicName)); for (Integer partitionNumber : partSpec.partitionNumbers()) { active.add(new TopicPartition(topicName, partitionNumber)); } } if (active.isEmpty()) { throw new RuntimeException("You must specify at least one active topic."); } for (Map.Entry<String, PartitionsSpec> entry : spec.inactiveTopics().materialize().entrySet()) { String topicName = entry.getKey(); PartitionsSpec partSpec = entry.getValue(); newTopics.put(topicName, partSpec.newTopic(topicName)); } status.update(new TextNode("Creating " + newTopics.keySet().size() + " topic(s)")); WorkerUtils.createTopics(log, spec.bootstrapServers(), spec.commonClientConf(), spec.adminClientConf(), newTopics, false); status.update(new TextNode("Created " + newTopics.keySet().size() + " topic(s)")); executor.submit(new SendRecords(active)); } catch (Throwable e) { WorkerUtils.abort(log, "Prepare", e, doneFuture); } } } private static class SendRecordsCallback implements Callback { private final SendRecords sendRecords; private final long startMs; SendRecordsCallback(SendRecords sendRecords, long startMs) { this.sendRecords = sendRecords; this.startMs = startMs; } @Override public void onCompletion(RecordMetadata metadata, Exception exception) { long now = Time.SYSTEM.milliseconds(); long durationMs = now - startMs; sendRecords.recordDuration(durationMs); if (exception != null) { log.error("SendRecordsCallback: error", exception); } } } /** * A subclass of Throttle which flushes the Producer right before the throttle injects a delay. * This avoids including throttling latency in latency measurements. */ private static class SendRecordsThrottle extends Throttle { private final KafkaProducer<?, ?> producer; SendRecordsThrottle(int maxPerPeriod, KafkaProducer<?, ?> producer) { super(maxPerPeriod, THROTTLE_PERIOD_MS); this.producer = producer; } @Override protected synchronized void delay(long amount) throws InterruptedException { long startMs = time().milliseconds(); producer.flush(); long endMs = time().milliseconds(); long delta = endMs - startMs; super.delay(amount - delta); } } public class SendRecords implements Callable<Void> { private final HashSet<TopicPartition> activePartitions; private final Histogram histogram; private final Future<?> statusUpdaterFuture; private final KafkaProducer<byte[], byte[]> producer; private final PayloadIterator keys; private final PayloadIterator values; private final Optional<TransactionGenerator> transactionGenerator; private final Throttle throttle; private Iterator<TopicPartition> partitionsIterator; private Future<RecordMetadata> sendFuture; private AtomicLong transactionsCommitted; private boolean enableTransactions; SendRecords(HashSet<TopicPartition> activePartitions) { this.activePartitions = activePartitions; this.partitionsIterator = activePartitions.iterator(); this.histogram = new Histogram(5000); this.transactionGenerator = spec.transactionGenerator(); this.enableTransactions = this.transactionGenerator.isPresent(); this.transactionsCommitted = new AtomicLong(); int perPeriod = WorkerUtils.perSecToPerPeriod(spec.targetMessagesPerSec(), THROTTLE_PERIOD_MS); this.statusUpdaterFuture = executor.scheduleWithFixedDelay( new StatusUpdater(histogram, transactionsCommitted), 30, 30, TimeUnit.SECONDS); Properties props = new Properties(); props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, spec.bootstrapServers()); if (enableTransactions) props.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "produce-bench-transaction-id-" + UUID.randomUUID()); // add common client configs to producer properties, and then user-specified producer configs WorkerUtils.addConfigsToProperties(props, spec.commonClientConf(), spec.producerConf()); this.producer = new KafkaProducer<>(props, new ByteArraySerializer(), new ByteArraySerializer()); this.keys = new PayloadIterator(spec.keyGenerator()); this.values = new PayloadIterator(spec.valueGenerator()); if (spec.skipFlush()) { this.throttle = new Throttle(perPeriod, THROTTLE_PERIOD_MS); } else { this.throttle = new SendRecordsThrottle(perPeriod, producer); } } @Override public Void call() throws Exception { long startTimeMs = Time.SYSTEM.milliseconds(); try { try { if (enableTransactions) producer.initTransactions(); long sentMessages = 0; while (sentMessages < spec.maxMessages()) { if (enableTransactions) { boolean tookAction = takeTransactionAction(); if (tookAction) continue; } sendMessage(); sentMessages++; } if (enableTransactions) takeTransactionAction(); // give the transactionGenerator a chance to commit if configured evenly } catch (Exception e) { if (enableTransactions) producer.abortTransaction(); throw e; } finally { if (sendFuture != null) { try { sendFuture.get(); } catch (Exception e) { log.error("Exception on final future", e); } } producer.close(); } } catch (Exception e) { WorkerUtils.abort(log, "SendRecords", e, doneFuture); } finally { statusUpdaterFuture.cancel(false); StatusData statusData = new StatusUpdater(histogram, transactionsCommitted).update(); long curTimeMs = Time.SYSTEM.milliseconds(); log.info("Sent {} total record(s) in {} ms. status: {}", histogram.summarize().numSamples(), curTimeMs - startTimeMs, statusData); } doneFuture.complete(""); return null; } private boolean takeTransactionAction() { boolean tookAction = true; TransactionAction nextAction = transactionGenerator.get().nextAction(); switch (nextAction) { case BEGIN_TRANSACTION: log.debug("Beginning transaction."); producer.beginTransaction(); break; case COMMIT_TRANSACTION: log.debug("Committing transaction."); producer.commitTransaction(); transactionsCommitted.getAndIncrement(); break; case ABORT_TRANSACTION: log.debug("Aborting transaction."); producer.abortTransaction(); break; case NO_OP: tookAction = false; break; } return tookAction; } private void sendMessage() throws InterruptedException { if (!partitionsIterator.hasNext()) partitionsIterator = activePartitions.iterator(); TopicPartition partition = partitionsIterator.next(); ProducerRecord<byte[], byte[]> record; if (spec.useConfiguredPartitioner()) { record = new ProducerRecord<>( partition.topic(), keys.next(), values.next()); } else { record = new ProducerRecord<>( partition.topic(), partition.partition(), keys.next(), values.next()); } sendFuture = producer.send(record, new SendRecordsCallback(this, Time.SYSTEM.milliseconds())); throttle.increment(); } void recordDuration(long durationMs) { histogram.add(durationMs); } } public class StatusUpdater implements Runnable { private final Histogram histogram; private final AtomicLong transactionsCommitted; StatusUpdater(Histogram histogram, AtomicLong transactionsCommitted) { this.histogram = histogram; this.transactionsCommitted = transactionsCommitted; } @Override public void run() { try { update(); } catch (Exception e) { WorkerUtils.abort(log, "StatusUpdater", e, doneFuture); } } StatusData update() { Histogram.Summary summary = histogram.summarize(StatusData.PERCENTILES); StatusData statusData = new StatusData(summary.numSamples(), summary.average(), summary.percentiles().get(0).value(), summary.percentiles().get(1).value(), summary.percentiles().get(2).value(), transactionsCommitted.get()); status.update(JsonUtil.JSON_SERDE.valueToTree(statusData)); return statusData; } } public static class StatusData { private final long totalSent; private final float averageLatencyMs; private final int p50LatencyMs; private final int p95LatencyMs; private final int p99LatencyMs; private final long transactionsCommitted; /** * The percentiles to use when calculating the histogram data. * These should match up with the p50LatencyMs, p95LatencyMs, etc. fields. */ final static float[] PERCENTILES = {0.5f, 0.95f, 0.99f}; @JsonCreator StatusData(@JsonProperty("totalSent") long totalSent, @JsonProperty("averageLatencyMs") float averageLatencyMs, @JsonProperty("p50LatencyMs") int p50latencyMs, @JsonProperty("p95LatencyMs") int p95latencyMs, @JsonProperty("p99LatencyMs") int p99latencyMs, @JsonProperty("transactionsCommitted") long transactionsCommitted) { this.totalSent = totalSent; this.averageLatencyMs = averageLatencyMs; this.p50LatencyMs = p50latencyMs; this.p95LatencyMs = p95latencyMs; this.p99LatencyMs = p99latencyMs; this.transactionsCommitted = transactionsCommitted; } @JsonProperty public long totalSent() { return totalSent; } @JsonProperty public long transactionsCommitted() { return transactionsCommitted; } @JsonProperty public float averageLatencyMs() { return averageLatencyMs; } @JsonProperty public int p50LatencyMs() { return p50LatencyMs; } @JsonProperty public int p95LatencyMs() { return p95LatencyMs; } @JsonProperty public int p99LatencyMs() { return p99LatencyMs; } } @Override public void stop(Platform platform) throws Exception { if (!running.compareAndSet(true, false)) { throw new IllegalStateException("ProduceBenchWorker is not running."); } log.info("{}: Deactivating ProduceBenchWorker.", id); doneFuture.complete(""); executor.shutdownNow(); executor.awaitTermination(1, TimeUnit.DAYS); this.executor = null; this.status = null; this.doneFuture = null; } }
tools/src/main/java/org/apache/kafka/trogdor/workload/ProduceBenchWorker.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.kafka.trogdor.workload; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.node.TextNode; import org.apache.kafka.clients.admin.NewTopic; import org.apache.kafka.clients.producer.Callback; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.clients.producer.RecordMetadata; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.internals.KafkaFutureImpl; import org.apache.kafka.common.serialization.ByteArraySerializer; import org.apache.kafka.common.utils.Time; import org.apache.kafka.trogdor.common.JsonUtil; import org.apache.kafka.trogdor.common.Platform; import org.apache.kafka.trogdor.common.ThreadUtils; import org.apache.kafka.trogdor.common.WorkerUtils; import org.apache.kafka.trogdor.task.TaskWorker; import org.apache.kafka.trogdor.task.WorkerStatusTracker; import org.apache.kafka.trogdor.workload.TransactionGenerator.TransactionAction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Optional; import java.util.Properties; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; public class ProduceBenchWorker implements TaskWorker { private static final Logger log = LoggerFactory.getLogger(ProduceBenchWorker.class); private static final int THROTTLE_PERIOD_MS = 100; private final String id; private final ProduceBenchSpec spec; private final AtomicBoolean running = new AtomicBoolean(false); private ScheduledExecutorService executor; private WorkerStatusTracker status; private KafkaFutureImpl<String> doneFuture; public ProduceBenchWorker(String id, ProduceBenchSpec spec) { this.id = id; this.spec = spec; } @Override public void start(Platform platform, WorkerStatusTracker status, KafkaFutureImpl<String> doneFuture) throws Exception { if (!running.compareAndSet(false, true)) { throw new IllegalStateException("ProducerBenchWorker is already running."); } log.info("{}: Activating ProduceBenchWorker with {}", id, spec); // Create an executor with 2 threads. We need the second thread so // that the StatusUpdater can run in parallel with SendRecords. this.executor = Executors.newScheduledThreadPool(2, ThreadUtils.createThreadFactory("ProduceBenchWorkerThread%d", false)); this.status = status; this.doneFuture = doneFuture; executor.submit(new Prepare()); } public class Prepare implements Runnable { @Override public void run() { try { Map<String, NewTopic> newTopics = new HashMap<>(); HashSet<TopicPartition> active = new HashSet<>(); for (Map.Entry<String, PartitionsSpec> entry : spec.activeTopics().materialize().entrySet()) { String topicName = entry.getKey(); PartitionsSpec partSpec = entry.getValue(); newTopics.put(topicName, partSpec.newTopic(topicName)); for (Integer partitionNumber : partSpec.partitionNumbers()) { active.add(new TopicPartition(topicName, partitionNumber)); } } if (active.isEmpty()) { throw new RuntimeException("You must specify at least one active topic."); } for (Map.Entry<String, PartitionsSpec> entry : spec.inactiveTopics().materialize().entrySet()) { String topicName = entry.getKey(); PartitionsSpec partSpec = entry.getValue(); newTopics.put(topicName, partSpec.newTopic(topicName)); } status.update(new TextNode("Creating " + newTopics.keySet().size() + " topic(s)")); WorkerUtils.createTopics(log, spec.bootstrapServers(), spec.commonClientConf(), spec.adminClientConf(), newTopics, false); status.update(new TextNode("Created " + newTopics.keySet().size() + " topic(s)")); executor.submit(new SendRecords(active)); } catch (Throwable e) { WorkerUtils.abort(log, "Prepare", e, doneFuture); } } } private static class SendRecordsCallback implements Callback { private final SendRecords sendRecords; private final long startMs; SendRecordsCallback(SendRecords sendRecords, long startMs) { this.sendRecords = sendRecords; this.startMs = startMs; } @Override public void onCompletion(RecordMetadata metadata, Exception exception) { long now = Time.SYSTEM.milliseconds(); long durationMs = now - startMs; sendRecords.recordDuration(durationMs); if (exception != null) { log.error("SendRecordsCallback: error", exception); } } } /** * A subclass of Throttle which flushes the Producer right before the throttle injects a delay. * This avoids including throttling latency in latency measurements. */ private static class SendRecordsThrottle extends Throttle { private final KafkaProducer<?, ?> producer; SendRecordsThrottle(int maxPerPeriod, KafkaProducer<?, ?> producer) { super(maxPerPeriod, THROTTLE_PERIOD_MS); this.producer = producer; } @Override protected synchronized void delay(long amount) throws InterruptedException { long startMs = time().milliseconds(); producer.flush(); long endMs = time().milliseconds(); long delta = endMs - startMs; super.delay(amount - delta); } } public class SendRecords implements Callable<Void> { private final HashSet<TopicPartition> activePartitions; private final Histogram histogram; private final Future<?> statusUpdaterFuture; private final KafkaProducer<byte[], byte[]> producer; private final PayloadIterator keys; private final PayloadIterator values; private final Optional<TransactionGenerator> transactionGenerator; private final Throttle throttle; private Iterator<TopicPartition> partitionsIterator; private Future<RecordMetadata> sendFuture; private AtomicLong transactionsCommitted; private boolean enableTransactions; SendRecords(HashSet<TopicPartition> activePartitions) { this.activePartitions = activePartitions; this.partitionsIterator = activePartitions.iterator(); this.histogram = new Histogram(5000); this.transactionGenerator = spec.transactionGenerator(); this.enableTransactions = this.transactionGenerator.isPresent(); this.transactionsCommitted = new AtomicLong(); int perPeriod = WorkerUtils.perSecToPerPeriod(spec.targetMessagesPerSec(), THROTTLE_PERIOD_MS); this.statusUpdaterFuture = executor.scheduleWithFixedDelay( new StatusUpdater(histogram, transactionsCommitted), 30, 30, TimeUnit.SECONDS); Properties props = new Properties(); props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, spec.bootstrapServers()); if (enableTransactions) props.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "produce-bench-transaction-id-" + UUID.randomUUID()); // add common client configs to producer properties, and then user-specified producer configs WorkerUtils.addConfigsToProperties(props, spec.commonClientConf(), spec.producerConf()); this.producer = new KafkaProducer<>(props, new ByteArraySerializer(), new ByteArraySerializer()); this.keys = new PayloadIterator(spec.keyGenerator()); this.values = new PayloadIterator(spec.valueGenerator()); if (spec.skipFlush()) { this.throttle = new Throttle(perPeriod, THROTTLE_PERIOD_MS); } else { this.throttle = new SendRecordsThrottle(perPeriod, producer); } } @Override public Void call() throws Exception { long startTimeMs = Time.SYSTEM.milliseconds(); try { try { if (enableTransactions) producer.initTransactions(); long sentMessages = 0; while (sentMessages < spec.maxMessages()) { if (enableTransactions) { boolean tookAction = takeTransactionAction(); if (tookAction) continue; } sendMessage(); sentMessages++; } if (enableTransactions) takeTransactionAction(); // give the transactionGenerator a chance to commit if configured evenly } catch (Exception e) { if (enableTransactions) producer.abortTransaction(); throw e; } finally { if (sendFuture != null) { sendFuture.get(); } producer.close(); } } catch (Exception e) { WorkerUtils.abort(log, "SendRecords", e, doneFuture); } finally { statusUpdaterFuture.cancel(false); StatusData statusData = new StatusUpdater(histogram, transactionsCommitted).update(); long curTimeMs = Time.SYSTEM.milliseconds(); log.info("Sent {} total record(s) in {} ms. status: {}", histogram.summarize().numSamples(), curTimeMs - startTimeMs, statusData); } doneFuture.complete(""); return null; } private boolean takeTransactionAction() { boolean tookAction = true; TransactionAction nextAction = transactionGenerator.get().nextAction(); switch (nextAction) { case BEGIN_TRANSACTION: log.debug("Beginning transaction."); producer.beginTransaction(); break; case COMMIT_TRANSACTION: log.debug("Committing transaction."); producer.commitTransaction(); transactionsCommitted.getAndIncrement(); break; case ABORT_TRANSACTION: log.debug("Aborting transaction."); producer.abortTransaction(); break; case NO_OP: tookAction = false; break; } return tookAction; } private void sendMessage() throws InterruptedException { if (!partitionsIterator.hasNext()) partitionsIterator = activePartitions.iterator(); TopicPartition partition = partitionsIterator.next(); ProducerRecord<byte[], byte[]> record; if (spec.useConfiguredPartitioner()) { record = new ProducerRecord<>( partition.topic(), keys.next(), values.next()); } else { record = new ProducerRecord<>( partition.topic(), partition.partition(), keys.next(), values.next()); } sendFuture = producer.send(record, new SendRecordsCallback(this, Time.SYSTEM.milliseconds())); throttle.increment(); } void recordDuration(long durationMs) { histogram.add(durationMs); } } public class StatusUpdater implements Runnable { private final Histogram histogram; private final AtomicLong transactionsCommitted; StatusUpdater(Histogram histogram, AtomicLong transactionsCommitted) { this.histogram = histogram; this.transactionsCommitted = transactionsCommitted; } @Override public void run() { try { update(); } catch (Exception e) { WorkerUtils.abort(log, "StatusUpdater", e, doneFuture); } } StatusData update() { Histogram.Summary summary = histogram.summarize(StatusData.PERCENTILES); StatusData statusData = new StatusData(summary.numSamples(), summary.average(), summary.percentiles().get(0).value(), summary.percentiles().get(1).value(), summary.percentiles().get(2).value(), transactionsCommitted.get()); status.update(JsonUtil.JSON_SERDE.valueToTree(statusData)); return statusData; } } public static class StatusData { private final long totalSent; private final float averageLatencyMs; private final int p50LatencyMs; private final int p95LatencyMs; private final int p99LatencyMs; private final long transactionsCommitted; /** * The percentiles to use when calculating the histogram data. * These should match up with the p50LatencyMs, p95LatencyMs, etc. fields. */ final static float[] PERCENTILES = {0.5f, 0.95f, 0.99f}; @JsonCreator StatusData(@JsonProperty("totalSent") long totalSent, @JsonProperty("averageLatencyMs") float averageLatencyMs, @JsonProperty("p50LatencyMs") int p50latencyMs, @JsonProperty("p95LatencyMs") int p95latencyMs, @JsonProperty("p99LatencyMs") int p99latencyMs, @JsonProperty("transactionsCommitted") long transactionsCommitted) { this.totalSent = totalSent; this.averageLatencyMs = averageLatencyMs; this.p50LatencyMs = p50latencyMs; this.p95LatencyMs = p95latencyMs; this.p99LatencyMs = p99latencyMs; this.transactionsCommitted = transactionsCommitted; } @JsonProperty public long totalSent() { return totalSent; } @JsonProperty public long transactionsCommitted() { return transactionsCommitted; } @JsonProperty public float averageLatencyMs() { return averageLatencyMs; } @JsonProperty public int p50LatencyMs() { return p50LatencyMs; } @JsonProperty public int p95LatencyMs() { return p95LatencyMs; } @JsonProperty public int p99LatencyMs() { return p99LatencyMs; } } @Override public void stop(Platform platform) throws Exception { if (!running.compareAndSet(true, false)) { throw new IllegalStateException("ProduceBenchWorker is not running."); } log.info("{}: Deactivating ProduceBenchWorker.", id); doneFuture.complete(""); executor.shutdownNow(); executor.awaitTermination(1, TimeUnit.DAYS); this.executor = null; this.status = null; this.doneFuture = null; } }
MINOR: fix ProduceBenchWorker not to fail on final produce (#7254) When sending bad records, the Trogdor task will fail if the final record produced is bad. Instead we should catch the exception to allow the task to finish since sending bad records is a valid use case. Reviewers: Tu V. Tran <[email protected]>, Guozhang Wang <[email protected]>
tools/src/main/java/org/apache/kafka/trogdor/workload/ProduceBenchWorker.java
MINOR: fix ProduceBenchWorker not to fail on final produce (#7254)
<ide><path>ools/src/main/java/org/apache/kafka/trogdor/workload/ProduceBenchWorker.java <ide> throw e; <ide> } finally { <ide> if (sendFuture != null) { <del> sendFuture.get(); <add> try { <add> sendFuture.get(); <add> } catch (Exception e) { <add> log.error("Exception on final future", e); <add> } <ide> } <ide> producer.close(); <ide> }
Java
apache-2.0
65d1d989592213cb1d188796f121d35e076004d0
0
ga4gh/dockstore,ga4gh/dockstore,ga4gh/dockstore
package io.dockstore.webservice.resources; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import com.google.common.collect.Sets; import io.dockstore.common.DescriptorLanguageSubclass; import io.dockstore.common.yaml.DockstoreYaml12; import io.dockstore.common.yaml.DockstoreYamlHelper; import io.dockstore.common.yaml.Service12; import io.dockstore.common.yaml.YamlWorkflow; import io.dockstore.webservice.CustomWebApplicationException; import io.dockstore.webservice.DockstoreWebserviceConfiguration; import io.dockstore.webservice.core.BioWorkflow; import io.dockstore.webservice.core.Checksum; import io.dockstore.webservice.core.LambdaEvent; import io.dockstore.webservice.core.Service; import io.dockstore.webservice.core.SourceFile; import io.dockstore.webservice.core.Token; import io.dockstore.webservice.core.TokenType; import io.dockstore.webservice.core.User; import io.dockstore.webservice.core.Validation; import io.dockstore.webservice.core.Version; import io.dockstore.webservice.core.Workflow; import io.dockstore.webservice.core.WorkflowMode; import io.dockstore.webservice.core.WorkflowVersion; import io.dockstore.webservice.helpers.CacheConfigManager; import io.dockstore.webservice.helpers.FileFormatHelper; import io.dockstore.webservice.helpers.GitHelper; import io.dockstore.webservice.helpers.GitHubHelper; import io.dockstore.webservice.helpers.GitHubSourceCodeRepo; import io.dockstore.webservice.helpers.SourceCodeRepoFactory; import io.dockstore.webservice.helpers.SourceCodeRepoInterface; import io.dockstore.webservice.jdbi.EventDAO; import io.dockstore.webservice.jdbi.FileDAO; import io.dockstore.webservice.jdbi.LambdaEventDAO; import io.dockstore.webservice.jdbi.TokenDAO; import io.dockstore.webservice.jdbi.UserDAO; import io.dockstore.webservice.jdbi.WorkflowDAO; import io.dockstore.webservice.jdbi.WorkflowVersionDAO; import io.swagger.annotations.Api; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.hibernate.SessionFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static io.dockstore.webservice.Constants.DOCKSTORE_YML_PATH; import static io.dockstore.webservice.Constants.LAMBDA_FAILURE; import static io.dockstore.webservice.core.WorkflowMode.DOCKSTORE_YML; import static io.dockstore.webservice.core.WorkflowMode.FULL; import static io.dockstore.webservice.core.WorkflowMode.STUB; /** * Base class for ServiceResource and WorkflowResource. * * Mainly has GitHub app logic, although there is also some BitBucket refresh * token logic that was easier to move in here than refactor out. * * @param <T> */ @Api("workflows") public abstract class AbstractWorkflowResource<T extends Workflow> implements SourceControlResourceInterface, AuthenticatedResourceInterface { private static final Logger LOG = LoggerFactory.getLogger(AbstractWorkflowResource.class); private static final String SHA_TYPE_FOR_SOURCEFILES = "SHA-1"; protected final HttpClient client; protected final TokenDAO tokenDAO; protected final WorkflowDAO workflowDAO; protected final UserDAO userDAO; protected final WorkflowVersionDAO workflowVersionDAO; protected final EventDAO eventDAO; protected final FileDAO fileDAO; protected final LambdaEventDAO lambdaEventDAO; protected final String gitHubPrivateKeyFile; protected final String gitHubAppId; protected final SessionFactory sessionFactory; protected final String bitbucketClientSecret; protected final String bitbucketClientID; private final Class<T> entityClass; public AbstractWorkflowResource(HttpClient client, SessionFactory sessionFactory, DockstoreWebserviceConfiguration configuration, Class<T> clazz) { this.client = client; this.sessionFactory = sessionFactory; this.tokenDAO = new TokenDAO(sessionFactory); this.workflowDAO = new WorkflowDAO(sessionFactory); this.userDAO = new UserDAO(sessionFactory); this.fileDAO = new FileDAO(sessionFactory); this.workflowVersionDAO = new WorkflowVersionDAO(sessionFactory); this.eventDAO = new EventDAO(sessionFactory); this.lambdaEventDAO = new LambdaEventDAO(sessionFactory); this.bitbucketClientID = configuration.getBitbucketClientID(); this.bitbucketClientSecret = configuration.getBitbucketClientSecret(); gitHubPrivateKeyFile = configuration.getGitHubAppPrivateKeyFile(); gitHubAppId = configuration.getGitHubAppId(); this.entityClass = clazz; } /** * Finds all workflows from a general Dockstore path that are of type FULL * @param dockstoreWorkflowPath Dockstore path (ex. github.com/dockstore/dockstore-ui2) * @return List of FULL workflows with the given Dockstore path */ protected List<Workflow> findAllWorkflowsByPath(String dockstoreWorkflowPath, WorkflowMode workflowMode) { return workflowDAO.findAllByPath(dockstoreWorkflowPath, false) .stream() .filter(workflow -> workflow.getMode() == workflowMode) .collect(Collectors.toList()); } protected SourceCodeRepoInterface getSourceCodeRepoInterface(String gitUrl, User user) { List<Token> tokens = getAndRefreshTokens(user, tokenDAO, client, bitbucketClientID, bitbucketClientSecret); final String bitbucketTokenContent = getToken(tokens, TokenType.BITBUCKET_ORG); final String gitHubTokenContent = getToken(tokens, TokenType.GITHUB_COM); final String gitlabTokenContent = getToken(tokens, TokenType.GITLAB_COM); final SourceCodeRepoInterface sourceCodeRepo = SourceCodeRepoFactory .createSourceCodeRepo(gitUrl, client, bitbucketTokenContent, gitlabTokenContent, gitHubTokenContent); if (sourceCodeRepo == null) { throw new CustomWebApplicationException("Git tokens invalid, please re-link your git accounts.", HttpStatus.SC_BAD_REQUEST); } return sourceCodeRepo; } private String getToken(List<Token> tokens, TokenType tokenType) { final Token token = Token.extractToken(tokens, tokenType); return token == null ? null : token.getContent(); } /** * Updates the existing workflow in the database with new information from newWorkflow, including new, updated, and removed * workflow verions. * @param workflow workflow to be updated * @param newWorkflow workflow to grab new content from * @param user * @param versionName */ protected void updateDBWorkflowWithSourceControlWorkflow(Workflow workflow, Workflow newWorkflow, final User user, Optional<String> versionName) { // update root workflow workflow.update(newWorkflow); // update workflow versions Map<String, WorkflowVersion> existingVersionMap = new HashMap<>(); workflow.getWorkflowVersions().forEach(version -> existingVersionMap.put(version.getName(), version)); // delete versions that exist in old workflow but do not exist in newWorkflow if (versionName.isEmpty()) { Map<String, WorkflowVersion> newVersionMap = new HashMap<>(); newWorkflow.getWorkflowVersions().forEach(version -> newVersionMap.put(version.getName(), version)); Sets.SetView<String> removedVersions = Sets.difference(existingVersionMap.keySet(), newVersionMap.keySet()); for (String version : removedVersions) { if (!existingVersionMap.get(version).isFrozen()) { workflow.removeWorkflowVersion(existingVersionMap.get(version)); } } } // Then copy over content that changed for (WorkflowVersion version : newWorkflow.getWorkflowVersions()) { // skip frozen versions WorkflowVersion workflowVersionFromDB = existingVersionMap.get(version.getName()); if (existingVersionMap.containsKey(version.getName())) { if (workflowVersionFromDB.isFrozen()) { continue; } workflowVersionFromDB.update(version); } else { // attach real workflow workflow.addWorkflowVersion(version); final long workflowVersionId = workflowVersionDAO.create(version); workflowVersionFromDB = workflowVersionDAO.findById(workflowVersionId); this.eventDAO.createAddTagToEntryEvent(user, workflow, workflowVersionFromDB); workflow.getWorkflowVersions().add(workflowVersionFromDB); existingVersionMap.put(workflowVersionFromDB.getName(), workflowVersionFromDB); } workflowVersionFromDB.setToolTableJson(null); workflowVersionFromDB.setDagJson(null); // Update sourcefiles updateDBVersionSourceFilesWithRemoteVersionSourceFiles(workflowVersionFromDB, version); } } /** * Updates the sourcefiles in the database to match the sourcefiles on the remote * @param existingVersion * @param remoteVersion * @return WorkflowVersion with updated sourcefiles */ private WorkflowVersion updateDBVersionSourceFilesWithRemoteVersionSourceFiles(WorkflowVersion existingVersion, WorkflowVersion remoteVersion) { // Update source files for each version Map<String, SourceFile> existingFileMap = new HashMap<>(); existingVersion.getSourceFiles().forEach(file -> existingFileMap.put(file.getType().toString() + file.getAbsolutePath(), file)); for (SourceFile file : remoteVersion.getSourceFiles()) { String fileKey = file.getType().toString() + file.getAbsolutePath(); SourceFile existingFile = existingFileMap.get(fileKey); if (existingFileMap.containsKey(fileKey)) { List<Checksum> checksums = new ArrayList<>(); Optional<String> sha = FileFormatHelper.calcSHA1(file.getContent()); if (sha.isPresent()) { checksums.add(new Checksum(SHA_TYPE_FOR_SOURCEFILES, sha.get())); if (existingFile.getChecksums() == null) { existingFile.setChecksums(checksums); } else { existingFile.getChecksums().clear(); existingFileMap.get(fileKey).getChecksums().addAll(checksums); } } existingFile.setContent(file.getContent()); } else { final long fileID = fileDAO.create(file); final SourceFile fileFromDB = fileDAO.findById(fileID); Optional<String> sha = FileFormatHelper.calcSHA1(file.getContent()); if (sha.isPresent()) { fileFromDB.getChecksums().add(new Checksum(SHA_TYPE_FOR_SOURCEFILES, sha.get())); } existingVersion.getSourceFiles().add(fileFromDB); } } // Remove existing files that are no longer present on remote for (Map.Entry<String, SourceFile> entry : existingFileMap.entrySet()) { boolean toDelete = true; for (SourceFile file : remoteVersion.getSourceFiles()) { if (entry.getKey().equals(file.getType().toString() + file.getAbsolutePath())) { toDelete = false; } } if (toDelete) { existingVersion.getSourceFiles().remove(entry.getValue()); } } // Update the validations for (Validation versionValidation : remoteVersion.getValidations()) { existingVersion.addOrUpdateValidation(versionValidation); } return existingVersion; } /** * Handle webhooks from GitHub apps after branch deletion (redirected from AWS Lambda) * - Delete version for corresponding service and workflow * @param repository Repository path (ex. dockstore/dockstore-ui2) * @param gitReference Git reference from GitHub (ex. refs/tags/1.0) * @param username Git user who triggered the event * @param installationId GitHub App installation ID * @return List of updated workflows */ protected List<Workflow> githubWebhookDelete(String repository, String gitReference, String username, String installationId) { // Retrieve name from gitReference Optional<String> gitReferenceName = GitHelper.parseGitHubReference(gitReference); if (gitReferenceName.isEmpty()) { String msg = "Reference " + gitReference + " is not of the valid form"; LOG.error(msg); sessionFactory.getCurrentSession().clear(); LambdaEvent lambdaEvent = createBasicEvent(repository, gitReference, username, LambdaEvent.LambdaEventType.DELETE); lambdaEvent.setMessage(msg); lambdaEvent.setSuccess(false); lambdaEventDAO.create(lambdaEvent); sessionFactory.getCurrentSession().getTransaction().commit(); throw new CustomWebApplicationException(msg, LAMBDA_FAILURE); } // Find all workflows and services that are github apps and use the given repo List<Workflow> workflows = workflowDAO.findAllByPath("github.com/" + repository, false).stream().filter(workflow -> Objects.equals(workflow.getMode(), DOCKSTORE_YML)).collect( Collectors.toList()); // Delete all non-frozen versions that have the same git reference name workflows.forEach(workflow -> workflow.getWorkflowVersions().removeIf(workflowVersion -> Objects.equals(workflowVersion.getName(), gitReferenceName.get()) && !workflowVersion.isFrozen())); LambdaEvent lambdaEvent = createBasicEvent(repository, gitReference, username, LambdaEvent.LambdaEventType.DELETE); lambdaEventDAO.create(lambdaEvent); return workflows; } /** * Handle webhooks from GitHub apps (redirected from AWS Lambda) * - Create services and workflows when necessary * - Add or update version for corresponding service and workflow * @param repository Repository path (ex. dockstore/dockstore-ui2) * @param username Username of GitHub user that triggered action * @param gitReference Git reference from GitHub (ex. refs/tags/1.0) * @param installationId GitHub App installation ID * @return List of new and updated workflows */ protected List<Workflow> githubWebhookRelease(String repository, String username, String gitReference, String installationId) { // Retrieve the user who triggered the call (must exist on Dockstore if workflow is not already present) User user = GitHubHelper.findUserByGitHubUsername(this.tokenDAO, this.userDAO, username, false); // Get Installation Access Token String installationAccessToken = gitHubAppSetup(installationId); // Grab Dockstore YML from GitHub GitHubSourceCodeRepo gitHubSourceCodeRepo = (GitHubSourceCodeRepo)SourceCodeRepoFactory.createGitHubAppRepo(installationAccessToken); try { SourceFile dockstoreYml = gitHubSourceCodeRepo.getDockstoreYml(repository, gitReference); // If this method doesn't throw an exception, it's a valid .dockstore.yml with at least one workflow or service. // It also converts a .dockstore.yml 1.1 file to a 1.2 object, if necessary. final DockstoreYaml12 dockstoreYaml12 = DockstoreYamlHelper.readAsDockstoreYaml12(dockstoreYml.getContent()); final List<Workflow> workflows = new ArrayList(); workflows.addAll(createServicesAndVersionsFromDockstoreYml(dockstoreYaml12.getService(), repository, gitReference, gitHubSourceCodeRepo, user, dockstoreYml)); workflows.addAll(createBioWorkflowsAndVersionsFromDockstoreYml(dockstoreYaml12.getWorkflows(), repository, gitReference, gitHubSourceCodeRepo, user, dockstoreYml)); LambdaEvent lambdaEvent = createBasicEvent(repository, gitReference, username, LambdaEvent.LambdaEventType.PUSH); lambdaEventDAO.create(lambdaEvent); return workflows; } catch (CustomWebApplicationException | ClassCastException | DockstoreYamlHelper.DockstoreYamlException ex) { String errorMessage = ex instanceof CustomWebApplicationException ? ((CustomWebApplicationException)ex).getErrorMessage() : ex.getMessage(); String msg = "User " + username + ": Error handling push event for repository " + repository + " and reference " + gitReference + "\n" + errorMessage; LOG.info(msg, ex); sessionFactory.getCurrentSession().clear(); LambdaEvent lambdaEvent = createBasicEvent(repository, gitReference, username, LambdaEvent.LambdaEventType.PUSH); lambdaEvent.setSuccess(false); lambdaEvent.setMessage(errorMessage); lambdaEventDAO.create(lambdaEvent); sessionFactory.getCurrentSession().getTransaction().commit(); throw new CustomWebApplicationException(msg, LAMBDA_FAILURE); } catch (Exception ex) { String msg = "User " + username + ": Unhandled error while handling push event for repository " + repository + " and reference " + gitReference + "\n" + ex.getMessage(); LOG.error(msg, ex); sessionFactory.getCurrentSession().clear(); LambdaEvent lambdaEvent = createBasicEvent(repository, gitReference, username, LambdaEvent.LambdaEventType.PUSH); lambdaEvent.setSuccess(false); lambdaEvent.setMessage(ex.getMessage()); lambdaEventDAO.create(lambdaEvent); sessionFactory.getCurrentSession().getTransaction().commit(); throw new CustomWebApplicationException(msg, LAMBDA_FAILURE); } } /** * Create a basic lambda event * @param repository repository path * @param gitReference full git reference (ex. refs/heads/master) * @param username Username of GitHub user who triggered the event * @param type Event type * @return New lambda event */ private LambdaEvent createBasicEvent(String repository, String gitReference, String username, LambdaEvent.LambdaEventType type) { LambdaEvent lambdaEvent = new LambdaEvent(); String[] repo = repository.split("/"); lambdaEvent.setOrganization(repo[0]); lambdaEvent.setRepository(repo[1]); lambdaEvent.setReference(gitReference); lambdaEvent.setGithubUsername(username); lambdaEvent.setType(type); User user = userDAO.findByGitHubUsername(username); if (user != null) { lambdaEvent.setUser(user); } return lambdaEvent; } /** * Create or retrieve workflows based on Dockstore.yml, add or update tag version * ONLY WORKS FOR v1.2 * @param repository Repository path (ex. dockstore/dockstore-ui2) * @param gitReference Git reference from GitHub (ex. refs/tags/1.0) * @param gitHubSourceCodeRepo Source Code Repo * @param user User that triggered action * @param dockstoreYml * @return List of new and updated workflows */ private List<Workflow> createBioWorkflowsAndVersionsFromDockstoreYml(List<YamlWorkflow> yamlWorkflows, String repository, String gitReference, GitHubSourceCodeRepo gitHubSourceCodeRepo, User user, final SourceFile dockstoreYml) { try { List<Workflow> updatedWorkflows = new ArrayList<>(); for (YamlWorkflow wf : yamlWorkflows) { String subclass = wf.getSubclass(); String workflowName = wf.getName(); Workflow workflow = createOrGetWorkflow(BioWorkflow.class, repository, user, workflowName, subclass, gitHubSourceCodeRepo); workflow = addDockstoreYmlVersionToWorkflow(repository, gitReference, dockstoreYml, gitHubSourceCodeRepo, workflow); updatedWorkflows.add(workflow); } return updatedWorkflows; } catch (ClassCastException ex) { throw new CustomWebApplicationException("Could not parse workflow array from YML.", LAMBDA_FAILURE); } } /** * Create or retrieve services based on Dockstore.yml, add or update tag version * ONLY WORKS FOR v1.1 * @param repository Repository path (ex. dockstore/dockstore-ui2) * @param gitReference Git reference from GitHub (ex. refs/tags/1.0) * @param gitHubSourceCodeRepo Source Code Repo * @param user User that triggered action * @param dockstoreYml * @return List of new and updated services */ private List<Workflow> createServicesAndVersionsFromDockstoreYml(Service12 service, String repository, String gitReference, GitHubSourceCodeRepo gitHubSourceCodeRepo, User user, final SourceFile dockstoreYml) { final List<Workflow> updatedServices = new ArrayList<>(); if (service != null) { final DescriptorLanguageSubclass subclass = service.getSubclass(); Workflow workflow = createOrGetWorkflow(Service.class, repository, user, "", subclass.getShortName(), gitHubSourceCodeRepo); workflow = addDockstoreYmlVersionToWorkflow(repository, gitReference, dockstoreYml, gitHubSourceCodeRepo, workflow); updatedServices.add(workflow); } return updatedServices; } /** * Create or retrieve workflow or service based on Dockstore.yml * @param workflowType Either BioWorkflow.class or Service.class * @param repository Repository path (ex. dockstore/dockstore-ui2) * @param user User that triggered action * @param workflowName User that triggered action * @param subclass Subclass of the workflow * @param gitHubSourceCodeRepo Source Code Repo * @return New or updated workflow */ private Workflow createOrGetWorkflow(Class workflowType, String repository, User user, String workflowName, String subclass, GitHubSourceCodeRepo gitHubSourceCodeRepo) { // Check for existing workflow String dockstoreWorkflowPath = "github.com/" + repository + (workflowName != null && !workflowName.isEmpty() ? "/" + workflowName : ""); Optional<Workflow> workflow = workflowDAO.findByPath(dockstoreWorkflowPath, false, workflowType); Workflow workflowToUpdate = null; // Create workflow if one does not exist if (workflow.isEmpty()) { // Ensure that a Dockstore user exists to add to the workflow if (user == null) { throw new CustomWebApplicationException("User does not have an account on Dockstore.", LAMBDA_FAILURE); } if (workflowType == BioWorkflow.class) { workflowToUpdate = gitHubSourceCodeRepo.initializeWorkflowFromGitHub(repository, subclass, workflowName); } else if (workflowType == Service.class) { workflowToUpdate = gitHubSourceCodeRepo.initializeServiceFromGitHub(repository, subclass); } else { throw new CustomWebApplicationException(workflowType.getCanonicalName() + " is not a valid workflow type. Currently only workflows and services are supported by GitHub Apps.", LAMBDA_FAILURE); } long workflowId = workflowDAO.create(workflowToUpdate); workflowToUpdate = workflowDAO.findById(workflowId); LOG.info("Workflow " + dockstoreWorkflowPath + " has been created."); } else { workflowToUpdate = workflow.get(); if (Objects.equals(workflowToUpdate.getMode(), FULL) || Objects.equals(workflowToUpdate.getMode(), STUB)) { LOG.info("Converting workflow to DOCKSTORE_YML"); workflowToUpdate.setMode(DOCKSTORE_YML); workflowToUpdate.setDefaultWorkflowPath(DOCKSTORE_YML_PATH); } } if (user != null) { workflowToUpdate.getUsers().add(user); } return workflowToUpdate; } /** * Add versions to a service or workflow based on Dockstore.yml * @param repository Repository path (ex. dockstore/dockstore-ui2) * @param gitReference Git reference from GitHub (ex. refs/tags/1.0) * @param dockstoreYml Dockstore YAML File * @param gitHubSourceCodeRepo Source Code Repo * @return New or updated workflow */ private Workflow addDockstoreYmlVersionToWorkflow(String repository, String gitReference, SourceFile dockstoreYml, GitHubSourceCodeRepo gitHubSourceCodeRepo, Workflow workflow) { try { // Create version and pull relevant files WorkflowVersion remoteWorkflowVersion = gitHubSourceCodeRepo .createVersionForWorkflow(repository, gitReference, workflow, dockstoreYml); remoteWorkflowVersion.setReferenceType(getReferenceTypeFromGitRef(gitReference)); // So we have workflowversion which is the new version, we want to update the version and associated source files Optional<WorkflowVersion> existingWorkflowVersion = workflow.getWorkflowVersions().stream().filter(wv -> wv.equals(remoteWorkflowVersion)).findFirst(); // Update existing source files, add new source files, remove deleted sourcefiles, clear json for dag and tool table if (existingWorkflowVersion.isPresent()) { // Copy over workflow version level information existingWorkflowVersion.get().setWorkflowPath(remoteWorkflowVersion.getWorkflowPath()); existingWorkflowVersion.get().setLastModified(remoteWorkflowVersion.getLastModified()); existingWorkflowVersion.get().setLegacyVersion(remoteWorkflowVersion.isLegacyVersion()); existingWorkflowVersion.get().setAliases(remoteWorkflowVersion.getAliases()); existingWorkflowVersion.get().setSubClass(remoteWorkflowVersion.getSubClass()); existingWorkflowVersion.get().setCommitID(remoteWorkflowVersion.getCommitID()); existingWorkflowVersion.get().setDagJson(null); existingWorkflowVersion.get().setToolTableJson(null); existingWorkflowVersion.get().setReferenceType(remoteWorkflowVersion.getReferenceType()); updateDBVersionSourceFilesWithRemoteVersionSourceFiles(existingWorkflowVersion.get(), remoteWorkflowVersion); } else { workflow.addWorkflowVersion(remoteWorkflowVersion); } Optional<WorkflowVersion> addedVersion = workflow.getWorkflowVersions().stream().filter(workflowVersion -> Objects.equals(workflowVersion.getName(), remoteWorkflowVersion.getName())).findFirst(); addedVersion.ifPresent(workflowVersion -> gitHubSourceCodeRepo .updateVersionMetadata(workflowVersion.getWorkflowPath(), workflowVersion, workflow.getDescriptorType(), repository)); LOG.info("Version " + remoteWorkflowVersion.getName() + " has been added to workflow " + workflow.getWorkflowPath() + "."); } catch (IOException ex) { throw new CustomWebApplicationException("Cannot retrieve the workflow reference from GitHub, ensure that " + gitReference + " is a valid tag.", LAMBDA_FAILURE); } return workflow; } private Version.ReferenceType getReferenceTypeFromGitRef(String gitRef) { if (gitRef.startsWith("refs/heads/")) { return Version.ReferenceType.BRANCH; } else if (gitRef.startsWith("refs/tags/")) { return Version.ReferenceType.TAG; } else { return Version.ReferenceType.NOT_APPLICABLE; } } /** * Add user to any existing Dockstore workflow and services from GitHub apps they should own * @param user */ protected void syncEntitiesForUser(User user) { List<Token> githubByUserId = tokenDAO.findGithubByUserId(user.getId()); if (githubByUserId.isEmpty()) { String msg = "The user does not have a GitHub token, please create one"; LOG.info(msg); throw new CustomWebApplicationException(msg, HttpStatus.SC_BAD_REQUEST); } else { syncEntities(user, githubByUserId.get(0)); } } /** * Syncs entities based on GitHub app installation, optionally limiting to orgs in the GitHub organization <code>organization</code>. * * 1. Finds all repos that have the Dockstore GitHub app installed * 2. For existing entities, ensures that <code>user</code> is one of the entity's users * * @param user * @param gitHubToken */ private void syncEntities(User user, Token gitHubToken) { GitHubSourceCodeRepo gitHubSourceCodeRepo = (GitHubSourceCodeRepo)SourceCodeRepoFactory.createSourceCodeRepo(gitHubToken, client); // Get all GitHub repositories for the user final Map<String, String> workflowGitUrl2Name = gitHubSourceCodeRepo.getWorkflowGitUrl2RepositoryId(); // Filter by organization if necessary final Collection<String> repositories = workflowGitUrl2Name.values(); // Add user to any services they should have access to that already exist on Dockstore final List<Workflow> existingWorkflows = findDockstoreWorkflowsForGitHubRepos(repositories); existingWorkflows.stream() .filter(workflow -> !workflow.getUsers().contains(user)) .forEach(workflow -> workflow.getUsers().add(user)); // No longer adds stub services, though code could be useful // final Set<String> existingWorkflowPaths = existingWorkflows.stream() // .map(workflow -> workflow.getWorkflowPath()).collect(Collectors.toSet()); // // GitHubHelper.checkJWT(gitHubAppId, gitHubPrivateKeyFile); // // GitHubHelper.reposToCreateEntitiesFor(repositories, organization, existingWorkflowPaths).stream() // .forEach(repositoryName -> { // final T entity = initializeEntity(repositoryName, gitHubSourceCodeRepo); // entity.addUser(user); // final long entityId = workflowDAO.create(entity); // final Workflow createdEntity = workflowDAO.findById(entityId); // final Workflow updatedEntity = gitHubSourceCodeRepo.getWorkflow(repositoryName, Optional.of(createdEntity)); // updateDBWorkflowWithSourceControlWorkflow(createdEntity, updatedEntity, user); // }); } /** * From the collection of GitHub repositories, returns the list of Dockstore entities (Service or BioWorkflow) that * exist for those repositories. * * Ideally this would return <code>List&lt;T&gt;</code>, but not sure if I can use getClass instead of WorkflowMode * for workflows (would it apply to both STUB and WORKFLOW?) in filter call below (see TODO)? * * @param repositories * @return */ private List<Workflow> findDockstoreWorkflowsForGitHubRepos(Collection<String> repositories) { final List<String> workflowPaths = repositories.stream().map(repositoryName -> "github.com/" + repositoryName) .collect(Collectors.toList()); return workflowDAO.findByPaths(workflowPaths, false).stream() // TODO: Revisit this when support for workflows added. .filter(workflow -> Objects.equals(workflow.getMode(), DOCKSTORE_YML)) .collect(Collectors.toList()); } /** * Setup tokens required for GitHub apps * @param installationId App installation ID (per repository) * @return Installation access token for the given repository */ private String gitHubAppSetup(String installationId) { GitHubHelper.checkJWT(gitHubAppId, gitHubPrivateKeyFile); String installationAccessToken = CacheConfigManager.getInstance().getInstallationAccessTokenFromCache(installationId); if (installationAccessToken == null) { String msg = "Could not get an installation access token for install with id " + installationId; LOG.info(msg); throw new CustomWebApplicationException(msg, HttpStatus.SC_INTERNAL_SERVER_ERROR); } return installationAccessToken; } }
dockstore-webservice/src/main/java/io/dockstore/webservice/resources/AbstractWorkflowResource.java
package io.dockstore.webservice.resources; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import com.google.common.collect.Sets; import io.dockstore.common.DescriptorLanguageSubclass; import io.dockstore.common.yaml.DockstoreYaml12; import io.dockstore.common.yaml.DockstoreYamlHelper; import io.dockstore.common.yaml.Service12; import io.dockstore.common.yaml.YamlWorkflow; import io.dockstore.webservice.CustomWebApplicationException; import io.dockstore.webservice.DockstoreWebserviceConfiguration; import io.dockstore.webservice.core.BioWorkflow; import io.dockstore.webservice.core.Checksum; import io.dockstore.webservice.core.LambdaEvent; import io.dockstore.webservice.core.Service; import io.dockstore.webservice.core.SourceFile; import io.dockstore.webservice.core.Token; import io.dockstore.webservice.core.TokenType; import io.dockstore.webservice.core.User; import io.dockstore.webservice.core.Validation; import io.dockstore.webservice.core.Version; import io.dockstore.webservice.core.Workflow; import io.dockstore.webservice.core.WorkflowMode; import io.dockstore.webservice.core.WorkflowVersion; import io.dockstore.webservice.helpers.CacheConfigManager; import io.dockstore.webservice.helpers.FileFormatHelper; import io.dockstore.webservice.helpers.GitHelper; import io.dockstore.webservice.helpers.GitHubHelper; import io.dockstore.webservice.helpers.GitHubSourceCodeRepo; import io.dockstore.webservice.helpers.SourceCodeRepoFactory; import io.dockstore.webservice.helpers.SourceCodeRepoInterface; import io.dockstore.webservice.jdbi.EventDAO; import io.dockstore.webservice.jdbi.FileDAO; import io.dockstore.webservice.jdbi.LambdaEventDAO; import io.dockstore.webservice.jdbi.TokenDAO; import io.dockstore.webservice.jdbi.UserDAO; import io.dockstore.webservice.jdbi.WorkflowDAO; import io.dockstore.webservice.jdbi.WorkflowVersionDAO; import io.swagger.annotations.Api; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.hibernate.SessionFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static io.dockstore.webservice.Constants.DOCKSTORE_YML_PATH; import static io.dockstore.webservice.Constants.LAMBDA_FAILURE; import static io.dockstore.webservice.core.WorkflowMode.DOCKSTORE_YML; import static io.dockstore.webservice.core.WorkflowMode.FULL; import static io.dockstore.webservice.core.WorkflowMode.STUB; /** * Base class for ServiceResource and WorkflowResource. * * Mainly has GitHub app logic, although there is also some BitBucket refresh * token logic that was easier to move in here than refactor out. * * @param <T> */ @Api("workflows") public abstract class AbstractWorkflowResource<T extends Workflow> implements SourceControlResourceInterface, AuthenticatedResourceInterface { private static final Logger LOG = LoggerFactory.getLogger(AbstractWorkflowResource.class); private static final String SHA_TYPE_FOR_SOURCEFILES = "SHA-1"; protected final HttpClient client; protected final TokenDAO tokenDAO; protected final WorkflowDAO workflowDAO; protected final UserDAO userDAO; protected final WorkflowVersionDAO workflowVersionDAO; protected final EventDAO eventDAO; protected final FileDAO fileDAO; protected final LambdaEventDAO lambdaEventDAO; protected final String gitHubPrivateKeyFile; protected final String gitHubAppId; protected final SessionFactory sessionFactory; protected final String bitbucketClientSecret; protected final String bitbucketClientID; private final Class<T> entityClass; public AbstractWorkflowResource(HttpClient client, SessionFactory sessionFactory, DockstoreWebserviceConfiguration configuration, Class<T> clazz) { this.client = client; this.sessionFactory = sessionFactory; this.tokenDAO = new TokenDAO(sessionFactory); this.workflowDAO = new WorkflowDAO(sessionFactory); this.userDAO = new UserDAO(sessionFactory); this.fileDAO = new FileDAO(sessionFactory); this.workflowVersionDAO = new WorkflowVersionDAO(sessionFactory); this.eventDAO = new EventDAO(sessionFactory); this.lambdaEventDAO = new LambdaEventDAO(sessionFactory); this.bitbucketClientID = configuration.getBitbucketClientID(); this.bitbucketClientSecret = configuration.getBitbucketClientSecret(); gitHubPrivateKeyFile = configuration.getGitHubAppPrivateKeyFile(); gitHubAppId = configuration.getGitHubAppId(); this.entityClass = clazz; } /** * Finds all workflows from a general Dockstore path that are of type FULL * @param dockstoreWorkflowPath Dockstore path (ex. github.com/dockstore/dockstore-ui2) * @return List of FULL workflows with the given Dockstore path */ protected List<Workflow> findAllWorkflowsByPath(String dockstoreWorkflowPath, WorkflowMode workflowMode) { return workflowDAO.findAllByPath(dockstoreWorkflowPath, false) .stream() .filter(workflow -> workflow.getMode() == workflowMode) .collect(Collectors.toList()); } protected SourceCodeRepoInterface getSourceCodeRepoInterface(String gitUrl, User user) { List<Token> tokens = getAndRefreshTokens(user, tokenDAO, client, bitbucketClientID, bitbucketClientSecret); final String bitbucketTokenContent = getToken(tokens, TokenType.BITBUCKET_ORG); final String gitHubTokenContent = getToken(tokens, TokenType.GITHUB_COM); final String gitlabTokenContent = getToken(tokens, TokenType.GITLAB_COM); final SourceCodeRepoInterface sourceCodeRepo = SourceCodeRepoFactory .createSourceCodeRepo(gitUrl, client, bitbucketTokenContent, gitlabTokenContent, gitHubTokenContent); if (sourceCodeRepo == null) { throw new CustomWebApplicationException("Git tokens invalid, please re-link your git accounts.", HttpStatus.SC_BAD_REQUEST); } return sourceCodeRepo; } private String getToken(List<Token> tokens, TokenType tokenType) { final Token token = Token.extractToken(tokens, tokenType); return token == null ? null : token.getContent(); } /** * Updates the existing workflow in the database with new information from newWorkflow, including new, updated, and removed * workflow verions. * @param workflow workflow to be updated * @param newWorkflow workflow to grab new content from * @param user * @param versionName */ protected void updateDBWorkflowWithSourceControlWorkflow(Workflow workflow, Workflow newWorkflow, final User user, Optional<String> versionName) { // update root workflow workflow.update(newWorkflow); // update workflow versions Map<String, WorkflowVersion> existingVersionMap = new HashMap<>(); workflow.getWorkflowVersions().forEach(version -> existingVersionMap.put(version.getName(), version)); // delete versions that exist in old workflow but do not exist in newWorkflow if (versionName.isEmpty()) { Map<String, WorkflowVersion> newVersionMap = new HashMap<>(); newWorkflow.getWorkflowVersions().forEach(version -> newVersionMap.put(version.getName(), version)); Sets.SetView<String> removedVersions = Sets.difference(existingVersionMap.keySet(), newVersionMap.keySet()); for (String version : removedVersions) { if (!existingVersionMap.get(version).isFrozen()) { workflow.removeWorkflowVersion(existingVersionMap.get(version)); } } } // Then copy over content that changed for (WorkflowVersion version : newWorkflow.getWorkflowVersions()) { // skip frozen versions WorkflowVersion workflowVersionFromDB = existingVersionMap.get(version.getName()); if (existingVersionMap.containsKey(version.getName())) { if (workflowVersionFromDB.isFrozen()) { continue; } workflowVersionFromDB.update(version); } else { // attach real workflow workflow.addWorkflowVersion(version); final long workflowVersionId = workflowVersionDAO.create(version); workflowVersionFromDB = workflowVersionDAO.findById(workflowVersionId); this.eventDAO.createAddTagToEntryEvent(user, workflow, workflowVersionFromDB); workflow.getWorkflowVersions().add(workflowVersionFromDB); existingVersionMap.put(workflowVersionFromDB.getName(), workflowVersionFromDB); } workflowVersionFromDB.setToolTableJson(null); workflowVersionFromDB.setDagJson(null); // Update sourcefiles updateDBVersionSourceFilesWithRemoteVersionSourceFiles(workflowVersionFromDB, version); } } /** * Updates the sourcefiles in the database to match the sourcefiles on the remote * @param existingVersion * @param remoteVersion * @return WorkflowVersion with updated sourcefiles */ private WorkflowVersion updateDBVersionSourceFilesWithRemoteVersionSourceFiles(WorkflowVersion existingVersion, WorkflowVersion remoteVersion) { // Update source files for each version Map<String, SourceFile> existingFileMap = new HashMap<>(); existingVersion.getSourceFiles().forEach(file -> existingFileMap.put(file.getType().toString() + file.getAbsolutePath(), file)); for (SourceFile file : remoteVersion.getSourceFiles()) { String fileKey = file.getType().toString() + file.getAbsolutePath(); SourceFile existingFile = existingFileMap.get(fileKey); if (existingFileMap.containsKey(fileKey)) { List<Checksum> checksums = new ArrayList<>(); Optional<String> sha = FileFormatHelper.calcSHA1(file.getContent()); if (sha.isPresent()) { checksums.add(new Checksum(SHA_TYPE_FOR_SOURCEFILES, sha.get())); if (existingFile.getChecksums() == null) { existingFile.setChecksums(checksums); } else { existingFile.getChecksums().clear(); existingFileMap.get(fileKey).getChecksums().addAll(checksums); } } existingFile.setContent(file.getContent()); } else { final long fileID = fileDAO.create(file); final SourceFile fileFromDB = fileDAO.findById(fileID); Optional<String> sha = FileFormatHelper.calcSHA1(file.getContent()); if (sha.isPresent()) { fileFromDB.getChecksums().add(new Checksum(SHA_TYPE_FOR_SOURCEFILES, sha.get())); } existingVersion.getSourceFiles().add(fileFromDB); } } // Remove existing files that are no longer present on remote for (Map.Entry<String, SourceFile> entry : existingFileMap.entrySet()) { boolean toDelete = true; for (SourceFile file : remoteVersion.getSourceFiles()) { if (entry.getKey().equals(file.getType().toString() + file.getAbsolutePath())) { toDelete = false; } } if (toDelete) { existingVersion.getSourceFiles().remove(entry.getValue()); } } // Update the validations for (Validation versionValidation : remoteVersion.getValidations()) { existingVersion.addOrUpdateValidation(versionValidation); } return existingVersion; } /** * Handle webhooks from GitHub apps after branch deletion (redirected from AWS Lambda) * - Delete version for corresponding service and workflow * @param repository Repository path (ex. dockstore/dockstore-ui2) * @param gitReference Git reference from GitHub (ex. refs/tags/1.0) * @param username Git user who triggered the event * @param installationId GitHub App installation ID * @return List of updated workflows */ protected List<Workflow> githubWebhookDelete(String repository, String gitReference, String username, String installationId) { // Retrieve name from gitReference Optional<String> gitReferenceName = GitHelper.parseGitHubReference(gitReference); if (gitReferenceName.isEmpty()) { String msg = "Reference " + gitReference + " is not of the valid form"; LOG.error(msg); sessionFactory.getCurrentSession().clear(); LambdaEvent lambdaEvent = createBasicEvent(repository, gitReference, username, LambdaEvent.LambdaEventType.DELETE); lambdaEvent.setMessage(msg); lambdaEvent.setSuccess(false); lambdaEventDAO.create(lambdaEvent); sessionFactory.getCurrentSession().getTransaction().commit(); throw new CustomWebApplicationException(msg, LAMBDA_FAILURE); } // Find all workflows and services that are github apps and use the given repo List<Workflow> workflows = workflowDAO.findAllByPath("github.com/" + repository, false).stream().filter(workflow -> Objects.equals(workflow.getMode(), DOCKSTORE_YML)).collect( Collectors.toList()); // Delete all non-frozen versions that have the same git reference name workflows.forEach(workflow -> workflow.getWorkflowVersions().removeIf(workflowVersion -> Objects.equals(workflowVersion.getName(), gitReferenceName.get()) && !workflowVersion.isFrozen())); LambdaEvent lambdaEvent = createBasicEvent(repository, gitReference, username, LambdaEvent.LambdaEventType.DELETE); lambdaEventDAO.create(lambdaEvent); return workflows; } /** * Handle webhooks from GitHub apps (redirected from AWS Lambda) * - Create services and workflows when necessary * - Add or update version for corresponding service and workflow * @param repository Repository path (ex. dockstore/dockstore-ui2) * @param username Username of GitHub user that triggered action * @param gitReference Git reference from GitHub (ex. refs/tags/1.0) * @param installationId GitHub App installation ID * @return List of new and updated workflows */ protected List<Workflow> githubWebhookRelease(String repository, String username, String gitReference, String installationId) { // Retrieve the user who triggered the call (must exist on Dockstore if workflow is not already present) User user = GitHubHelper.findUserByGitHubUsername(this.tokenDAO, this.userDAO, username, false); // Get Installation Access Token String installationAccessToken = gitHubAppSetup(installationId); // Grab Dockstore YML from GitHub GitHubSourceCodeRepo gitHubSourceCodeRepo = (GitHubSourceCodeRepo)SourceCodeRepoFactory.createGitHubAppRepo(installationAccessToken); try { SourceFile dockstoreYml = gitHubSourceCodeRepo.getDockstoreYml(repository, gitReference); // If this method doesn't throw an exception, it's a valid .dockstore.yml with at least one workflow or service. // It also converts a .dockstore.yml 1.1 file to a 1.2 object, if necessary. final DockstoreYaml12 dockstoreYaml12 = DockstoreYamlHelper.readAsDockstoreYaml12(dockstoreYml.getContent()); final List<Workflow> workflows = new ArrayList(); workflows.addAll(createServicesAndVersionsFromDockstoreYml(dockstoreYaml12.getService(), repository, gitReference, gitHubSourceCodeRepo, user, dockstoreYml)); workflows.addAll(createBioWorkflowsAndVersionsFromDockstoreYml(dockstoreYaml12.getWorkflows(), repository, gitReference, gitHubSourceCodeRepo, user, dockstoreYml)); LambdaEvent lambdaEvent = createBasicEvent(repository, gitReference, username, LambdaEvent.LambdaEventType.PUSH); lambdaEventDAO.create(lambdaEvent); return workflows; } catch (CustomWebApplicationException | ClassCastException | DockstoreYamlHelper.DockstoreYamlException ex) { String msg = "User " + username + ": Error handling push event for repository " + repository + " and reference " + gitReference + "\n" + ex.getMessage(); LOG.info(msg, ex); sessionFactory.getCurrentSession().clear(); LambdaEvent lambdaEvent = createBasicEvent(repository, gitReference, username, LambdaEvent.LambdaEventType.PUSH); lambdaEvent.setSuccess(false); lambdaEvent.setMessage(ex.getMessage()); lambdaEventDAO.create(lambdaEvent); sessionFactory.getCurrentSession().getTransaction().commit(); throw new CustomWebApplicationException(msg, LAMBDA_FAILURE); } catch (Exception ex) { String msg = "User " + username + ": Unhandled error while handling push event for repository " + repository + " and reference " + gitReference + "\n" + ex.getMessage(); LOG.error(msg, ex); sessionFactory.getCurrentSession().clear(); LambdaEvent lambdaEvent = createBasicEvent(repository, gitReference, username, LambdaEvent.LambdaEventType.PUSH); lambdaEvent.setSuccess(false); lambdaEvent.setMessage(ex.getMessage()); lambdaEventDAO.create(lambdaEvent); sessionFactory.getCurrentSession().getTransaction().commit(); throw new CustomWebApplicationException(msg, LAMBDA_FAILURE); } } /** * Create a basic lambda event * @param repository repository path * @param gitReference full git reference (ex. refs/heads/master) * @param username Username of GitHub user who triggered the event * @param type Event type * @return New lambda event */ private LambdaEvent createBasicEvent(String repository, String gitReference, String username, LambdaEvent.LambdaEventType type) { LambdaEvent lambdaEvent = new LambdaEvent(); String[] repo = repository.split("/"); lambdaEvent.setOrganization(repo[0]); lambdaEvent.setRepository(repo[1]); lambdaEvent.setReference(gitReference); lambdaEvent.setGithubUsername(username); lambdaEvent.setType(type); User user = userDAO.findByGitHubUsername(username); if (user != null) { lambdaEvent.setUser(user); } return lambdaEvent; } /** * Create or retrieve workflows based on Dockstore.yml, add or update tag version * ONLY WORKS FOR v1.2 * @param repository Repository path (ex. dockstore/dockstore-ui2) * @param gitReference Git reference from GitHub (ex. refs/tags/1.0) * @param gitHubSourceCodeRepo Source Code Repo * @param user User that triggered action * @param dockstoreYml * @return List of new and updated workflows */ private List<Workflow> createBioWorkflowsAndVersionsFromDockstoreYml(List<YamlWorkflow> yamlWorkflows, String repository, String gitReference, GitHubSourceCodeRepo gitHubSourceCodeRepo, User user, final SourceFile dockstoreYml) { try { List<Workflow> updatedWorkflows = new ArrayList<>(); for (YamlWorkflow wf : yamlWorkflows) { String subclass = wf.getSubclass(); String workflowName = wf.getName(); Workflow workflow = createOrGetWorkflow(BioWorkflow.class, repository, user, workflowName, subclass, gitHubSourceCodeRepo); workflow = addDockstoreYmlVersionToWorkflow(repository, gitReference, dockstoreYml, gitHubSourceCodeRepo, workflow); updatedWorkflows.add(workflow); } return updatedWorkflows; } catch (ClassCastException ex) { throw new CustomWebApplicationException("Could not parse workflow array from YML.", LAMBDA_FAILURE); } } /** * Create or retrieve services based on Dockstore.yml, add or update tag version * ONLY WORKS FOR v1.1 * @param repository Repository path (ex. dockstore/dockstore-ui2) * @param gitReference Git reference from GitHub (ex. refs/tags/1.0) * @param gitHubSourceCodeRepo Source Code Repo * @param user User that triggered action * @param dockstoreYml * @return List of new and updated services */ private List<Workflow> createServicesAndVersionsFromDockstoreYml(Service12 service, String repository, String gitReference, GitHubSourceCodeRepo gitHubSourceCodeRepo, User user, final SourceFile dockstoreYml) { final List<Workflow> updatedServices = new ArrayList<>(); if (service != null) { final DescriptorLanguageSubclass subclass = service.getSubclass(); Workflow workflow = createOrGetWorkflow(Service.class, repository, user, "", subclass.getShortName(), gitHubSourceCodeRepo); workflow = addDockstoreYmlVersionToWorkflow(repository, gitReference, dockstoreYml, gitHubSourceCodeRepo, workflow); updatedServices.add(workflow); } return updatedServices; } /** * Create or retrieve workflow or service based on Dockstore.yml * @param workflowType Either BioWorkflow.class or Service.class * @param repository Repository path (ex. dockstore/dockstore-ui2) * @param user User that triggered action * @param workflowName User that triggered action * @param subclass Subclass of the workflow * @param gitHubSourceCodeRepo Source Code Repo * @return New or updated workflow */ private Workflow createOrGetWorkflow(Class workflowType, String repository, User user, String workflowName, String subclass, GitHubSourceCodeRepo gitHubSourceCodeRepo) { // Check for existing workflow String dockstoreWorkflowPath = "github.com/" + repository + (workflowName != null && !workflowName.isEmpty() ? "/" + workflowName : ""); Optional<Workflow> workflow = workflowDAO.findByPath(dockstoreWorkflowPath, false, workflowType); Workflow workflowToUpdate = null; // Create workflow if one does not exist if (workflow.isEmpty()) { // Ensure that a Dockstore user exists to add to the workflow if (user == null) { throw new CustomWebApplicationException("User does not have an account on Dockstore.", LAMBDA_FAILURE); } if (workflowType == BioWorkflow.class) { workflowToUpdate = gitHubSourceCodeRepo.initializeWorkflowFromGitHub(repository, subclass, workflowName); } else if (workflowType == Service.class) { workflowToUpdate = gitHubSourceCodeRepo.initializeServiceFromGitHub(repository, subclass); } else { throw new CustomWebApplicationException(workflowType.getCanonicalName() + " is not a valid workflow type. Currently only workflows and services are supported by GitHub Apps.", LAMBDA_FAILURE); } long workflowId = workflowDAO.create(workflowToUpdate); workflowToUpdate = workflowDAO.findById(workflowId); LOG.info("Workflow " + dockstoreWorkflowPath + " has been created."); } else { workflowToUpdate = workflow.get(); if (Objects.equals(workflowToUpdate.getMode(), FULL) || Objects.equals(workflowToUpdate.getMode(), STUB)) { LOG.info("Converting workflow to DOCKSTORE_YML"); workflowToUpdate.setMode(DOCKSTORE_YML); workflowToUpdate.setDefaultWorkflowPath(DOCKSTORE_YML_PATH); } } if (user != null) { workflowToUpdate.getUsers().add(user); } return workflowToUpdate; } /** * Add versions to a service or workflow based on Dockstore.yml * @param repository Repository path (ex. dockstore/dockstore-ui2) * @param gitReference Git reference from GitHub (ex. refs/tags/1.0) * @param dockstoreYml Dockstore YAML File * @param gitHubSourceCodeRepo Source Code Repo * @return New or updated workflow */ private Workflow addDockstoreYmlVersionToWorkflow(String repository, String gitReference, SourceFile dockstoreYml, GitHubSourceCodeRepo gitHubSourceCodeRepo, Workflow workflow) { try { // Create version and pull relevant files WorkflowVersion remoteWorkflowVersion = gitHubSourceCodeRepo .createVersionForWorkflow(repository, gitReference, workflow, dockstoreYml); remoteWorkflowVersion.setReferenceType(getReferenceTypeFromGitRef(gitReference)); // So we have workflowversion which is the new version, we want to update the version and associated source files Optional<WorkflowVersion> existingWorkflowVersion = workflow.getWorkflowVersions().stream().filter(wv -> wv.equals(remoteWorkflowVersion)).findFirst(); // Update existing source files, add new source files, remove deleted sourcefiles, clear json for dag and tool table if (existingWorkflowVersion.isPresent()) { // Copy over workflow version level information existingWorkflowVersion.get().setWorkflowPath(remoteWorkflowVersion.getWorkflowPath()); existingWorkflowVersion.get().setLastModified(remoteWorkflowVersion.getLastModified()); existingWorkflowVersion.get().setLegacyVersion(remoteWorkflowVersion.isLegacyVersion()); existingWorkflowVersion.get().setAliases(remoteWorkflowVersion.getAliases()); existingWorkflowVersion.get().setSubClass(remoteWorkflowVersion.getSubClass()); existingWorkflowVersion.get().setCommitID(remoteWorkflowVersion.getCommitID()); existingWorkflowVersion.get().setDagJson(null); existingWorkflowVersion.get().setToolTableJson(null); existingWorkflowVersion.get().setReferenceType(remoteWorkflowVersion.getReferenceType()); updateDBVersionSourceFilesWithRemoteVersionSourceFiles(existingWorkflowVersion.get(), remoteWorkflowVersion); } else { workflow.addWorkflowVersion(remoteWorkflowVersion); } Optional<WorkflowVersion> addedVersion = workflow.getWorkflowVersions().stream().filter(workflowVersion -> Objects.equals(workflowVersion.getName(), remoteWorkflowVersion.getName())).findFirst(); addedVersion.ifPresent(workflowVersion -> gitHubSourceCodeRepo .updateVersionMetadata(workflowVersion.getWorkflowPath(), workflowVersion, workflow.getDescriptorType(), repository)); LOG.info("Version " + remoteWorkflowVersion.getName() + " has been added to workflow " + workflow.getWorkflowPath() + "."); } catch (IOException ex) { throw new CustomWebApplicationException("Cannot retrieve the workflow reference from GitHub, ensure that " + gitReference + " is a valid tag.", LAMBDA_FAILURE); } return workflow; } private Version.ReferenceType getReferenceTypeFromGitRef(String gitRef) { if (gitRef.startsWith("refs/heads/")) { return Version.ReferenceType.BRANCH; } else if (gitRef.startsWith("refs/tags/")) { return Version.ReferenceType.TAG; } else { return Version.ReferenceType.NOT_APPLICABLE; } } /** * Add user to any existing Dockstore workflow and services from GitHub apps they should own * @param user */ protected void syncEntitiesForUser(User user) { List<Token> githubByUserId = tokenDAO.findGithubByUserId(user.getId()); if (githubByUserId.isEmpty()) { String msg = "The user does not have a GitHub token, please create one"; LOG.info(msg); throw new CustomWebApplicationException(msg, HttpStatus.SC_BAD_REQUEST); } else { syncEntities(user, githubByUserId.get(0)); } } /** * Syncs entities based on GitHub app installation, optionally limiting to orgs in the GitHub organization <code>organization</code>. * * 1. Finds all repos that have the Dockstore GitHub app installed * 2. For existing entities, ensures that <code>user</code> is one of the entity's users * * @param user * @param gitHubToken */ private void syncEntities(User user, Token gitHubToken) { GitHubSourceCodeRepo gitHubSourceCodeRepo = (GitHubSourceCodeRepo)SourceCodeRepoFactory.createSourceCodeRepo(gitHubToken, client); // Get all GitHub repositories for the user final Map<String, String> workflowGitUrl2Name = gitHubSourceCodeRepo.getWorkflowGitUrl2RepositoryId(); // Filter by organization if necessary final Collection<String> repositories = workflowGitUrl2Name.values(); // Add user to any services they should have access to that already exist on Dockstore final List<Workflow> existingWorkflows = findDockstoreWorkflowsForGitHubRepos(repositories); existingWorkflows.stream() .filter(workflow -> !workflow.getUsers().contains(user)) .forEach(workflow -> workflow.getUsers().add(user)); // No longer adds stub services, though code could be useful // final Set<String> existingWorkflowPaths = existingWorkflows.stream() // .map(workflow -> workflow.getWorkflowPath()).collect(Collectors.toSet()); // // GitHubHelper.checkJWT(gitHubAppId, gitHubPrivateKeyFile); // // GitHubHelper.reposToCreateEntitiesFor(repositories, organization, existingWorkflowPaths).stream() // .forEach(repositoryName -> { // final T entity = initializeEntity(repositoryName, gitHubSourceCodeRepo); // entity.addUser(user); // final long entityId = workflowDAO.create(entity); // final Workflow createdEntity = workflowDAO.findById(entityId); // final Workflow updatedEntity = gitHubSourceCodeRepo.getWorkflow(repositoryName, Optional.of(createdEntity)); // updateDBWorkflowWithSourceControlWorkflow(createdEntity, updatedEntity, user); // }); } /** * From the collection of GitHub repositories, returns the list of Dockstore entities (Service or BioWorkflow) that * exist for those repositories. * * Ideally this would return <code>List&lt;T&gt;</code>, but not sure if I can use getClass instead of WorkflowMode * for workflows (would it apply to both STUB and WORKFLOW?) in filter call below (see TODO)? * * @param repositories * @return */ private List<Workflow> findDockstoreWorkflowsForGitHubRepos(Collection<String> repositories) { final List<String> workflowPaths = repositories.stream().map(repositoryName -> "github.com/" + repositoryName) .collect(Collectors.toList()); return workflowDAO.findByPaths(workflowPaths, false).stream() // TODO: Revisit this when support for workflows added. .filter(workflow -> Objects.equals(workflow.getMode(), DOCKSTORE_YML)) .collect(Collectors.toList()); } /** * Setup tokens required for GitHub apps * @param installationId App installation ID (per repository) * @return Installation access token for the given repository */ private String gitHubAppSetup(String installationId) { GitHubHelper.checkJWT(gitHubAppId, gitHubPrivateKeyFile); String installationAccessToken = CacheConfigManager.getInstance().getInstallationAccessTokenFromCache(installationId); if (installationAccessToken == null) { String msg = "Could not get an installation access token for install with id " + installationId; LOG.info(msg); throw new CustomWebApplicationException(msg, HttpStatus.SC_INTERNAL_SERVER_ERROR); } return installationAccessToken; } }
3687/lambda error message fix (#3696) * print out error message to lambda event for customwebapplicationexceptions * change to one liner
dockstore-webservice/src/main/java/io/dockstore/webservice/resources/AbstractWorkflowResource.java
3687/lambda error message fix (#3696)
<ide><path>ockstore-webservice/src/main/java/io/dockstore/webservice/resources/AbstractWorkflowResource.java <ide> lambdaEventDAO.create(lambdaEvent); <ide> return workflows; <ide> } catch (CustomWebApplicationException | ClassCastException | DockstoreYamlHelper.DockstoreYamlException ex) { <del> String msg = "User " + username + ": Error handling push event for repository " + repository + " and reference " + gitReference + "\n" + ex.getMessage(); <add> String errorMessage = ex instanceof CustomWebApplicationException ? ((CustomWebApplicationException)ex).getErrorMessage() : ex.getMessage(); <add> String msg = "User " + username + ": Error handling push event for repository " + repository + " and reference " + gitReference + "\n" + errorMessage; <ide> LOG.info(msg, ex); <ide> sessionFactory.getCurrentSession().clear(); <ide> LambdaEvent lambdaEvent = createBasicEvent(repository, gitReference, username, LambdaEvent.LambdaEventType.PUSH); <ide> lambdaEvent.setSuccess(false); <del> lambdaEvent.setMessage(ex.getMessage()); <add> lambdaEvent.setMessage(errorMessage); <ide> lambdaEventDAO.create(lambdaEvent); <ide> sessionFactory.getCurrentSession().getTransaction().commit(); <ide> throw new CustomWebApplicationException(msg, LAMBDA_FAILURE);
JavaScript
mit
66a7a530a60ba4519f671ef750243615aa6122db
0
stephanieg0/instaRoute,stephanieg0/instaRoute
app.controller("apiController", ["$scope", "$window", "$firebaseArray", "getUid", '$cookies', "departureTime", "getOrigin", "getDestination", "getRouteTime", "getRouteSummary", "$q", function ($scope, $window, $firebaseArray, idFactory, $cookies, timeFactory, originFactory, destinationFactory, RouteTimeFactory, RouteSummaryFactory, $q) { //getting back the current user data from factory after log in. $scope.userData = idFactory.getUid(); $scope.userId = $scope.userData.uid; // Setting a cookie to remember user id upon page refresh. //if user id is falsy(which it will be when page is refreshed), //then get the cookie, which has the id saved. if (!$scope.userId) { $scope.userId = $cookies.get('userId'); } else { //else, if user id "is" defined, then redefine the cookie to the current user id. $cookies.put('userId', $scope.userId); } //Retrieving Name to Display it console.log("$scope.userId", $scope.userId); var ref = new Firebase("https://instaroute.firebaseio.com/users/" + $scope.userId); ref.on("value", function(snapshot) { $scope.userName = snapshot.val().facebook.displayName; console.log($scope.userName); }, function (errorObject) { console.log("The read failed: " + errorObject.code); }); //Loading routes from firebase and defining scope route for html binding. var ref = new Firebase("https://instaroute.firebaseio.com/routes"); $scope.routes = $firebaseArray(ref); //console.log("$scope.routes", $scope.routes); $scope.routes.currentRoute = {}; //variables for the inputHTML. var fromInput = ""; var toInput = ""; //variables for google instances and objects. $scope.map = ""; var mapOptions = {} $scope.geocoder = ""; $scope.service = ""; //variable to get whole address for geocoder. var address = ""; //array to have more than one marker in the map. $scope.markersArray = []; //setting global latitude and longitud. Deafult to Nashville.Needed to show map. var myLatLng = {lat: 36.166361, lng: -86.781167}; //variables for google's distance matrix. //my origin in address form and coordinates. var origin1 = {lat: 55.93, lng: -3.118}; var origin2 = 'Greenwich, England'; //my destination in address form and coordinates. var destinationA = 'Stockholm, Sweden'; var destinationB = {lat: 50.087, lng: 14.421}; //output for dom. $scope.outputDiv = ""; //Id from firebase to be defined. $scope.currentRouteID = ""; //for time of departure. var timeString = ""; var stringValue = ""; var routeTime = ""; var routeSummary = ""; //initializing the map when app loads(part of the script tag in html). //Deafult to Nashville $window.initMap = function () { //deafult for map mapOptions = { center: myLatLng, zoom: 10 } //creates a map inside the map div map = new google.maps.Map(document.getElementById('map'), mapOptions); //map instances for display. $scope.directionsService = new google.maps.DirectionsService; $scope.directionsDisplay = new google.maps.DirectionsRenderer; $scope.directionsDisplay.setMap(map); //geocoder instance for making address into coordinates. geocoder = new google.maps.Geocoder(); //distance matrix instance to get time from origin to destination. service = new google.maps.DistanceMatrixService; var trafficLayer = new google.maps.TrafficLayer(); trafficLayer.setMap(map); }; //setting autocomplete function for input field. $scope.placesFrom = function (keyEvent) { //get the html element input for the autocomplete var input = document.getElementById('from'); //to use globally fromInput = input; //create autocomplete object. var autocomplete = new $window.google.maps.places.Autocomplete(input, $scope.markersArray); //Get complete address on enter key. if (keyEvent.which === 13) { //getting the input string as address for geocoder. //and passing address to origin2 for distance matrix. origin2 = document.getElementById('from').value; //passing map object and geocoder instance to function. $scope.geocodeAddress(geocoder, map, origin2); $scope.routes.currentRoute = { "timeDuration": "", "routeSummary": "" } }//end if. };//end of placesFrom function. //setting autocomplete function for input field. $scope.placesTo = function (keyEvent) { //get the html element input var input = document.getElementById('to'); //to use input globally toInput = input; //create autocomplete object. var autocomplete = new $window.google.maps.places.Autocomplete(input, $scope.markersArray); //Get complete address on enter key. if (keyEvent.which === 13) { //getting the input string as address for geocoder. //and passing address to destinationA for distance matrix. destinationA = document.getElementById('to').value; //passing map object and geocoder instance to function. $scope.geocodeAddress(geocoder, map, destinationA); }//end if. };//end of placesTo function. //Getting departure time from user input. $scope.DepartureTime = function(index, origin, destination){ console.log("departureTime button"); //getting specific addresses to re-run. origin2 = origin; destinationA = destination; //getting class name by index. var el = document.getElementsByClassName(index); //console.log("el", el); //getting the specific value of current selected. for (var i = 0; i < el.length; i++){ stringValue = el[i].value + ":0"; //console.log("stringValue", stringValue); } //sending stringValue to factory to store and call later. timeFactory.addTime(stringValue); originFactory.addOrigin(origin2); destinationFactory.addDestination(destinationA); }; //This is the saved individual route origin and destination info. //*** origin and destination have to pass through geocode address to give coordinates. $scope.GetTime = function(origin, destination, stringValue) { //$scope.popop = stringValue; console.log("This is GetTime"); console.log("stringValue", stringValue); //need to assign both origin and destination to address variable and pass it to geocoder. origin2 = origin; $scope.geocodeAddress(geocoder, map, origin, stringValue); destinationA = destination; $scope.geocodeAddress(geocoder, map, destination, stringValue); //getting the Selected/current Route in firebase. If origin and destination match. for (var i = 0; i < $scope.routes.length; i ++){ if($scope.routes[i].origin2 === origin && $scope.routes[i].destinationA === destination){ //specific id from firebase. $scope.currentRouteID = $scope.routes[i].$id; //specific route to determine time duration in distance Matrix output. $scope.routes.currentRoute = $scope.routes[i]; //console.log("$scope.routes[i]", $scope.routes[i]); //console.log("GetTime, $scope.routes.currentRoute", $scope.routes.currentRoute); } } };//end of SavedRoute function. //changin the marker position $scope.geocodeAddress = function (geocoder, map, address, stringValue) { console.log("geocodeAddress", address); //pushing address key into the geocode from google to get coordinates and change the map. geocoder.geocode( { 'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); $scope.markersArray.push(new google.maps.Marker({ map: map, position: results[0].geometry.location, zoom: 10, mapTypeId: google.maps.MapTypeId.ROADMAP }));//end of Marker //console.log("$scope.markersArray in geocodeAddress", $scope.markersArray); //** getting the position from orign and destination in any given order. for (var i = 0; i < $scope.markersArray.length; i++) { // console.log("loop markersArray", $scope.markersArray[i].position); //** If the address matches the origin input, assign the current position to the origin. if (origin2 === address){ origin1 = $scope.markersArray[i].position; //console.log("geocoderAddress origin1", origin1); //** If the address matched the destination, assign the current position to the destination. } if (destinationA === address) { destinationB = $scope.markersArray[i].position; //console.log("geocoderAddress destinationA", destinationA); } }//end of loop. //** if geocoder does not have address, give an error. }else { alert("Geocode was not successful for the following reason: " + status); } //** if the markers array contains 2 objects, call GetMatrix function for distance and time. if ($scope.markersArray.length === 2) { //getting the summary on the map. console.log("$scope.directionsService", $scope.directionsService); $scope.calculateAndDisplayRoute($scope.directionsService, $scope.directionsDisplay, stringValue); } $scope.$apply(); });//end of geocoder.geocode() };//end of geocodeAddress. //** Route map display. $scope.calculateAndDisplayRoute = function(directionsService, directionsDisplay, stringValue) { console.log("This is calculateAndDisplayRoute"); $scope.directionsService = directionsService; $scope.directionsDisplay = directionsDisplay; $scope.directionsService.route({ origin: origin2, destination: destinationA, travelMode: google.maps.TravelMode.DRIVING }, function(response, status) { if (status === google.maps.DirectionsStatus.OK) { $scope.directionsDisplay.setDirections(response); //console.log("response", response); //console.log("response.routes[0].summary", response.routes[0].summary); } else { window.alert('Directions request failed due to ' + status); } for (var i = 0; i < response.routes.length; i++){ // console.log("route summay", response.routes[i].summary); $scope.routes.currentRoute.routeSummary = response.routes[i].summary; //passing results to factory. RouteSummaryFactory.addRouteSummary($scope.routes.currentRoute.routeSummary); } $scope.$apply(); $scope.GetMatrix(stringValue); }); }; //** Getting time and distance from geocodeAddress origin and destination format. $scope.GetMatrix = function(stringValue) { console.log("this is GetMatrix"); console.log("stringValue matrix", stringValue); service.getDistanceMatrix({ origins: [origin1, origin2], destinations: [destinationA, destinationB], travelMode: google.maps.TravelMode.DRIVING, unitSystem: google.maps.UnitSystem.METRIC, avoidHighways: false, avoidTolls: false, }, function(response, status) { if (status !== google.maps.DistanceMatrixStatus.OK) { alert('Error was: ' + status); } else { //** new list/format of the origin and destination. var originList = response.originAddresses; var destinationList = response.destinationAddresses; }//end of else //Origin List //** the new origin format is an array. for (var i = 0; i < originList.length; i++) { //Getting distance and duration for origin and destination var results = response.rows[i].elements; geocoder.geocode({'address': originList[i]}, function(results, status) { //geocoder.geocode needs to pass two arguments otherwise, it will error. }); //Destination List for (var j = 0; j < results.length; j++) { geocoder.geocode({'address': destinationList[j]}, function(results, status) { //geocoder.geocode needs to pass two arguments otherwise, it will error. }); //if $scope.routes.currentRoute.timeDuration is found and equals to empty string, then assgin duration. //console.log("GetMatrix, $scope.routes.currentRoute.timeDuration", $scope.routes.currentRoute.timeDuration); $scope.routes.currentRoute.timeDuration = results[j].duration.text; //passing the timeDuration of the route into the factory. RouteTimeFactory.addRouteTime($scope.routes.currentRoute.timeDuration); }//end of loop }//end of loop //string value will be defined only if the departure button is clicked. console.log("stringValue", stringValue); if (stringValue === undefined || stringValue === "") { //do nothing } else { //if the string value is true, alert with current results. alert("Route Details: " + $scope.routes.currentRoute.routeSummary + " " + $scope.routes.currentRoute.timeDuration); } //emptying markerArray. for (var i = 0; i < $scope.markersArray.length; i++) { $scope.markersArray[i].setMap(null); } $scope.markersArray = []; //console.log("$scope.markersArray", $scope.markersArray); //the scope needs to be applied so the outputDiv can show up because of the nested forloops. $scope.$apply(); });//response, status function. };//end of function //Saving a route to firebase. $scope.SaveRoute = function() { //get the html element input for the autocomplete var originTitle = document.getElementById('origin-title').value; var destinationTitle = document.getElementById('destination-title').value; origin2 = document.getElementById('from').value; destinationA = document.getElementById('to').value; //firebase refrences to correct path var routesRef = new Firebase("https://instaroute.firebaseio.com/routes"); //Not allowing the user to create an empty route. if (!fromInput.value || !toInput.value) { //do nothing } else { //pushing route info to firebase routesRef.push({ "originTitle": originTitle, "destinationTitle": destinationTitle, "userId": $scope.userId, "origin2": origin2, "destinationA": destinationA, "timeDuration": "", "routeSummary": "" }); //clearing input values after clicking "create route". document.getElementById('origin-title').value = ""; document.getElementById('destination-title').value = ""; document.getElementById('to').value = ""; document.getElementById('from').value = ""; } }; //Deleting from firebase $scope.DeleteRoute = function(route) { $scope.routes.$remove(route); //console.log(route, "removed"); }; //LogOut $scope.LogOut = function() { //deafult map options to reset the map. mapOptions = { center: myLatLng, zoom: 10 } //Reseting the map when loggin out. map = new google.maps.Map(document.getElementById('map'), mapOptions); //reseting map instances for display. $scope.directionsService = new google.maps.DirectionsService; $scope.directionsDisplay = new google.maps.DirectionsRenderer; $scope.directionsDisplay.setMap(map); var trafficLayer = new google.maps.TrafficLayer(); trafficLayer.setMap(map); //user logged out. $cookies.put('userId', undefined); idFactory.addUid(null); ref.unauth(); }; $scope.popUpWindow = function() { var routeTime = ""; var routeSummary = ""; routeTime = RouteTimeFactory.getRouteTime(); routeSummary = RouteSummaryFactory.getRouteSummary(); if (routeTime !== "" && routeSummary !== ""){ alert("Time: " + routeTime + "Summary: " + routeSummary); } } //Live time. $scope.SetTime = function() { //Getting time //var formatReference = "7:54:0"; var currentTime = new Date(); var hours = currentTime.getHours(); var minutes = currentTime.getMinutes(); minutes = minutes > 9 ? minutes : '0' + minutes; var seconds = currentTime.getSeconds(); //console.log("minutes", minutes); if (hours > 12) { hours -= 12; } else if (hours === 0) { hours = 12; } //concatenating hours, minutes and seconds. timeString = hours + ":" + minutes + ":" + seconds; var t = setTimeout($scope.SetTime, 500); //calling factory for the saved departure time and assigning it to stringValue. stringValue = timeFactory.getTime(); //getting the specific origin from factory. origin2 = originFactory.getOrigin(); //getting specific destination from factory. destinationA = destinationFactory.getDestination(); //comparing stringValue to current time. if (stringValue === timeString){ $scope.GetTime(origin2, destinationA, stringValue); } }; }]);//end of controller
app/controllers/api.js
app.controller("apiController", ["$scope", "$window", "$firebaseArray", "getUid", '$cookies', "departureTime", "getOrigin", "getDestination", "getRouteTime", "getRouteSummary", "$q", function ($scope, $window, $firebaseArray, idFactory, $cookies, timeFactory, originFactory, destinationFactory, RouteTimeFactory, RouteSummaryFactory, $q) { //getting back the current user data from factory after log in. $scope.userData = idFactory.getUid(); $scope.userId = $scope.userData.uid; // Setting a cookie to remember user id upon page refresh. //if user id is falsy(which it will be when page is refreshed), //then get the cookie, which has the id saved. if (!$scope.userId) { $scope.userId = $cookies.get('userId'); } else { //else, if user id "is" defined, then redefine the cookie to the current user id. $cookies.put('userId', $scope.userId); } //Retrieving Name to Display it console.log("$scope.userId", $scope.userId); var ref = new Firebase("https://instaroute.firebaseio.com/users/" + $scope.userId); ref.on("value", function(snapshot) { $scope.userName = snapshot.val().facebook.displayName; console.log($scope.userName); }, function (errorObject) { console.log("The read failed: " + errorObject.code); }); //Loading routes from firebase and defining scope route for html binding. var ref = new Firebase("https://instaroute.firebaseio.com/routes"); $scope.routes = $firebaseArray(ref); //console.log("$scope.routes", $scope.routes); $scope.routes.currentRoute = {}; //variables for the inputHTML. var fromInput = ""; var toInput = ""; //variables for google instances and objects. $scope.map = ""; var mapOptions = {} $scope.geocoder = ""; $scope.service = ""; //variable to get whole address for geocoder. var address = ""; //array to have more than one marker in the map. $scope.markersArray = []; //setting global latitude and longitud. Deafult to Nashville.Needed to show map. var myLatLng = {lat: 36.166361, lng: -86.781167}; //variables for google's distance matrix. //my origin in address form and coordinates. var origin1 = {lat: 55.93, lng: -3.118}; var origin2 = 'Greenwich, England'; //my destination in address form and coordinates. var destinationA = 'Stockholm, Sweden'; var destinationB = {lat: 50.087, lng: 14.421}; //output for dom. $scope.outputDiv = ""; //Id from firebase to be defined. $scope.currentRouteID = ""; //for time of departure. var timeString = ""; var stringValue = ""; var routeTime = ""; var routeSummary = ""; //initializing the map when app loads(part of the script tag in html). //Deafult to Nashville $window.initMap = function () { //deafult for map mapOptions = { center: myLatLng, zoom: 10 } //creates a map inside the map div map = new google.maps.Map(document.getElementById('map'), mapOptions); //map instances for display. $scope.directionsService = new google.maps.DirectionsService; $scope.directionsDisplay = new google.maps.DirectionsRenderer; $scope.directionsDisplay.setMap(map); //geocoder instance for making address into coordinates. geocoder = new google.maps.Geocoder(); //distance matrix instance to get time from origin to destination. service = new google.maps.DistanceMatrixService; var trafficLayer = new google.maps.TrafficLayer(); trafficLayer.setMap(map); }; //setting autocomplete function for input field. $scope.placesFrom = function (keyEvent) { //get the html element input for the autocomplete var input = document.getElementById('from'); //to use globally fromInput = input; //create autocomplete object. var autocomplete = new $window.google.maps.places.Autocomplete(input, $scope.markersArray); //Get complete address on enter key. if (keyEvent.which === 13) { //getting the input string as address for geocoder. //and passing address to origin2 for distance matrix. origin2 = document.getElementById('from').value; //passing map object and geocoder instance to function. $scope.geocodeAddress(geocoder, map, origin2); $scope.routes.currentRoute = { "timeDuration": "", "routeSummary": "" } }//end if. };//end of placesFrom function. //setting autocomplete function for input field. $scope.placesTo = function (keyEvent) { //get the html element input var input = document.getElementById('to'); //to use input globally toInput = input; //create autocomplete object. var autocomplete = new $window.google.maps.places.Autocomplete(input, $scope.markersArray); //Get complete address on enter key. if (keyEvent.which === 13) { //getting the input string as address for geocoder. //and passing address to destinationA for distance matrix. destinationA = document.getElementById('to').value; //passing map object and geocoder instance to function. $scope.geocodeAddress(geocoder, map, destinationA); }//end if. };//end of placesTo function. //Getting departure time from user input. $scope.DepartureTime = function(index, origin, destination){ console.log("departureTime button"); //getting specific addresses to re-run. origin2 = origin; destinationA = destination; //getting class name by index. var el = document.getElementsByClassName(index); //console.log("el", el); //getting the specific value of current selected. for (var i = 0; i < el.length; i++){ stringValue = el[i].value + ":0"; //console.log("stringValue", stringValue); } //sending stringValue to factory to store and call later. timeFactory.addTime(stringValue); originFactory.addOrigin(origin2); destinationFactory.addDestination(destinationA); }; //This is the saved individual route origin and destination info. //*** origin and destination have to pass through geocode address to give coordinates. $scope.GetTime = function(origin, destination, stringValue) { //$scope.popop = stringValue; console.log("This is GetTime"); console.log("stringValue", stringValue); //need to assign both origin and destination to address variable and pass it to geocoder. origin2 = origin; $scope.geocodeAddress(geocoder, map, origin, stringValue); destinationA = destination; $scope.geocodeAddress(geocoder, map, destination, stringValue); //getting the Selected/current Route in firebase. If origin and destination match. for (var i = 0; i < $scope.routes.length; i ++){ if($scope.routes[i].origin2 === origin && $scope.routes[i].destinationA === destination){ //specific id from firebase. $scope.currentRouteID = $scope.routes[i].$id; //specific route to determine time duration in distance Matrix output. $scope.routes.currentRoute = $scope.routes[i]; //console.log("$scope.routes[i]", $scope.routes[i]); //console.log("GetTime, $scope.routes.currentRoute", $scope.routes.currentRoute); } } };//end of SavedRoute function. //changin the marker position $scope.geocodeAddress = function (geocoder, map, address, stringValue) { console.log("geocodeAddress", address); //pushing address key into the geocode from google to get coordinates and change the map. geocoder.geocode( { 'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); $scope.markersArray.push(new google.maps.Marker({ map: map, position: results[0].geometry.location, zoom: 10, mapTypeId: google.maps.MapTypeId.ROADMAP }));//end of Marker //console.log("$scope.markersArray in geocodeAddress", $scope.markersArray); //** getting the position from orign and destination in any given order. for (var i = 0; i < $scope.markersArray.length; i++) { // console.log("loop markersArray", $scope.markersArray[i].position); //** If the address matches the origin input, assign the current position to the origin. if (origin2 === address){ origin1 = $scope.markersArray[i].position; //console.log("geocoderAddress origin1", origin1); //** If the address matched the destination, assign the current position to the destination. } if (destinationA === address) { destinationB = $scope.markersArray[i].position; //console.log("geocoderAddress destinationA", destinationA); } }//end of loop. //** if geocoder does not have address, give an error. }else { alert("Geocode was not successful for the following reason: " + status); } //** if the markers array contains 2 objects, call GetMatrix function for distance and time. if ($scope.markersArray.length === 2) { //getting the summary on the map. console.log("$scope.directionsService", $scope.directionsService); $scope.calculateAndDisplayRoute($scope.directionsService, $scope.directionsDisplay, stringValue); } $scope.$apply(); });//end of geocoder.geocode() };//end of geocodeAddress. //** Route map display. $scope.calculateAndDisplayRoute = function(directionsService, directionsDisplay, stringValue) { console.log("This is calculateAndDisplayRoute"); $scope.directionsService = directionsService; $scope.directionsDisplay = directionsDisplay; $scope.directionsService.route({ origin: origin2, destination: destinationA, travelMode: google.maps.TravelMode.DRIVING }, function(response, status) { if (status === google.maps.DirectionsStatus.OK) { $scope.directionsDisplay.setDirections(response); //console.log("response", response); //console.log("response.routes[0].summary", response.routes[0].summary); } else { window.alert('Directions request failed due to ' + status); } for (var i = 0; i < response.routes.length; i++){ // console.log("route summay", response.routes[i].summary); $scope.routes.currentRoute.routeSummary = response.routes[i].summary; //passing results to factory. RouteSummaryFactory.addRouteSummary($scope.routes.currentRoute.routeSummary); } $scope.$apply(); $scope.GetMatrix(stringValue); }); }; //** Getting time and distance from geocodeAddress origin and destination format. $scope.GetMatrix = function(stringValue) { console.log("this is GetMatrix"); console.log("stringValue matrix", stringValue); service.getDistanceMatrix({ origins: [origin1, origin2], destinations: [destinationA, destinationB], travelMode: google.maps.TravelMode.DRIVING, unitSystem: google.maps.UnitSystem.METRIC, avoidHighways: false, avoidTolls: false, }, function(response, status) { if (status !== google.maps.DistanceMatrixStatus.OK) { alert('Error was: ' + status); } else { //** new list/format of the origin and destination. var originList = response.originAddresses; var destinationList = response.destinationAddresses; }//end of else //Origin List //** the new origin format is an array. for (var i = 0; i < originList.length; i++) { //Getting distance and duration for origin and destination var results = response.rows[i].elements; geocoder.geocode({'address': originList[i]}, function(results, status) { //geocoder.geocode needs to pass two arguments otherwise, it will error. }); //Destination List for (var j = 0; j < results.length; j++) { geocoder.geocode({'address': destinationList[j]}, function(results, status) { //geocoder.geocode needs to pass two arguments otherwise, it will error. }); //if $scope.routes.currentRoute.timeDuration is found and equals to empty string, then assgin duration. //console.log("GetMatrix, $scope.routes.currentRoute.timeDuration", $scope.routes.currentRoute.timeDuration); $scope.routes.currentRoute.timeDuration = results[j].duration.text; //passing the timeDuration of the route into the factory. RouteTimeFactory.addRouteTime($scope.routes.currentRoute.timeDuration); }//end of loop }//end of loop //string value will be defined only if the departure button is clicked. console.log("stringValue", stringValue); if (stringValue === undefined || stringValue === "") { //do nothing } else { //if the string value is true, alert with current results. alert("Route Details: " + $scope.routes.currentRoute.routeSummary + " " + $scope.routes.currentRoute.timeDuration); } //emptying markerArray. for (var i = 0; i < $scope.markersArray.length; i++) { $scope.markersArray[i].setMap(null); } $scope.markersArray = []; //console.log("$scope.markersArray", $scope.markersArray); //the scope needs to be applied so the outputDiv can show up because of the nested forloops. $scope.$apply(); });//response, status function. };//end of function //Saving a route to firebase. $scope.SaveRoute = function() { //console.log("origin1", origin1); //console.log("destinationB", destinationB); //get the html element input for the autocomplete var originTitle = document.getElementById('origin-title').value; var destinationTitle = document.getElementById('destination-title').value; //firebase refrences to correct path var routesRef = new Firebase("https://instaroute.firebaseio.com/routes"); //Not allowing the user to create an empty route. if (!fromInput.value || !toInput.value) { //do nothing } else { //pushing route info to firebase routesRef.push({ "originTitle": originTitle, "destinationTitle": destinationTitle, "userId": $scope.userId, "origin2": origin2, "destinationA": destinationA, "timeDuration": "", "routeSummary": "" }); //clearing input values after clicking "create route". document.getElementById('origin-title').value = ""; document.getElementById('destination-title').value = ""; document.getElementById('to').value = ""; document.getElementById('from').value = ""; } }; //Deleting from firebase $scope.DeleteRoute = function(route) { $scope.routes.$remove(route); //console.log(route, "removed"); }; //LogOut $scope.LogOut = function() { //deafult map options to reset the map. mapOptions = { center: myLatLng, zoom: 10 } //Reseting the map when loggin out. map = new google.maps.Map(document.getElementById('map'), mapOptions); //reseting map instances for display. $scope.directionsService = new google.maps.DirectionsService; $scope.directionsDisplay = new google.maps.DirectionsRenderer; $scope.directionsDisplay.setMap(map); var trafficLayer = new google.maps.TrafficLayer(); trafficLayer.setMap(map); //user logged out. $cookies.put('userId', undefined); idFactory.addUid(null); ref.unauth(); }; $scope.popUpWindow = function() { var routeTime = ""; var routeSummary = ""; routeTime = RouteTimeFactory.getRouteTime(); routeSummary = RouteSummaryFactory.getRouteSummary(); if (routeTime !== "" && routeSummary !== ""){ alert("Time: " + routeTime + "Summary: " + routeSummary); } } //Live time. $scope.SetTime = function() { //Getting time //var formatReference = "7:54:0"; var currentTime = new Date(); var hours = currentTime.getHours(); var minutes = currentTime.getMinutes(); minutes = minutes > 9 ? minutes : '0' + minutes; var seconds = currentTime.getSeconds(); //console.log("minutes", minutes); if (hours > 12) { hours -= 12; } else if (hours === 0) { hours = 12; } //concatenating hours, minutes and seconds. timeString = hours + ":" + minutes + ":" + seconds; var t = setTimeout($scope.SetTime, 500); //calling factory for the saved departure time and assigning it to stringValue. stringValue = timeFactory.getTime(); //getting the specific origin from factory. origin2 = originFactory.getOrigin(); //getting specific destination from factory. destinationA = destinationFactory.getDestination(); //comparing stringValue to current time. if (stringValue === timeString){ $scope.GetTime(origin2, destinationA, stringValue); } }; }]);//end of controller
saving address on click
app/controllers/api.js
saving address on click
<ide><path>pp/controllers/api.js <ide> <ide> //Saving a route to firebase. <ide> $scope.SaveRoute = function() { <del> //console.log("origin1", origin1); <del> //console.log("destinationB", destinationB); <add> <ide> //get the html element input for the autocomplete <ide> var originTitle = document.getElementById('origin-title').value; <ide> var destinationTitle = document.getElementById('destination-title').value; <add> origin2 = document.getElementById('from').value; <add> destinationA = document.getElementById('to').value; <add> <ide> //firebase refrences to correct path <ide> var routesRef = new Firebase("https://instaroute.firebaseio.com/routes"); <ide>
JavaScript
mit
a19a16cdb8ea60bc0f38255ed3b2ab1ab7abff84
0
PinguinJantan/openPackTrack-backend,PinguinJantan/openPackTrack-backend,arnaz06/openPackTrack-backend,PinguinJantan/openPackTrack-backend,arnaz06/openPackTrack-backend
'use strict'; module.exports = { up: function (queryInterface, Sequelize) { /* Add altering commands here. Return a promise to correctly handle asynchronicity. Example: return queryInterface.createTable('users', { id: Sequelize.INTEGER }); */ return queryInterface.renameColumn('Items', 'genre', 'gender') }, down: function (queryInterface, Sequelize) { /* Add reverting commands here. Return a promise to correctly handle asynchronicity. Example: return queryInterface.dropTable('users'); */ } };
migrations/20171026141947-rename-genre-colom-in-item-teble.js
'use strict'; module.exports = { up: function (queryInterface, Sequelize) { /* Add altering commands here. Return a promise to correctly handle asynchronicity. Example: return queryInterface.createTable('users', { id: Sequelize.INTEGER }); */ queryInterface.renameColumn('Items', 'genre', 'gender') }, down: function (queryInterface, Sequelize) { /* Add reverting commands here. Return a promise to correctly handle asynchronicity. Example: return queryInterface.dropTable('users'); */ } };
kurang return
migrations/20171026141947-rename-genre-colom-in-item-teble.js
kurang return
<ide><path>igrations/20171026141947-rename-genre-colom-in-item-teble.js <ide> Example: <ide> return queryInterface.createTable('users', { id: Sequelize.INTEGER }); <ide> */ <del> queryInterface.renameColumn('Items', 'genre', 'gender') <add> return queryInterface.renameColumn('Items', 'genre', 'gender') <ide> }, <ide> <ide> down: function (queryInterface, Sequelize) {
Java
apache-2.0
30deb13d1ec4b398de2abb234802d049533e18d2
0
saurabharora90/MaterialArcMenu
package com.sa90.materialarcmenu; import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.os.Build; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; import android.view.animation.AccelerateInterpolator; import android.widget.FrameLayout; import androidx.annotation.AttrRes; import androidx.annotation.NonNull; import androidx.coordinatorlayout.widget.CoordinatorLayout; import androidx.core.content.ContextCompat; import com.google.android.material.floatingactionbutton.FloatingActionButton; import java.util.ArrayList; import java.util.List; /** * Created by Saurabh on 14/12/15. */ public class ArcMenu extends FrameLayout implements CoordinatorLayout.AttachedBehavior { private static final double POSITIVE_QUADRANT = 90; private static final double NEGATIVE_QUADRANT = -90; private static final double ANGLE_FOR_ONE_SUB_MENU = 0; private static final int ANIMATION_TIME = 300; //This time is in milliseconds FloatingActionButton fabMenu; public Drawable mDrawable; ColorStateList mColorStateList; int mRippleColor; long mAnimationTime; float mCurrentRadius, mFinalRadius, mElevation; int menuMargin; boolean mIsOpened = false; double mQuadrantAngle; MenuSideEnum mMenuSideEnum; int cx, cy; //Represents the center points of the circle whose arc we are considering private StateChangeListener mStateChangeListener; public ArcMenu(Context context) { super(context); } public ArcMenu(Context context, AttributeSet attrs) { super(context, attrs); TypedArray attr = context.obtainStyledAttributes(attrs, R.styleable.ArcMenu, 0, 0); init(attr); fabMenu = new FloatingActionButton(context, attrs); } private void init(TypedArray attr) { Resources resources = getResources(); mDrawable = attr.getDrawable(R.styleable.ArcMenu_menu_scr); mColorStateList = attr.getColorStateList(R.styleable.ArcMenu_menu_color); mFinalRadius = attr.getDimension(R.styleable.ArcMenu_menu_radius, resources.getDimension(R.dimen.default_radius)); mElevation = attr.getDimension(R.styleable.ArcMenu_menu_elevation, resources.getDimension(R.dimen.default_elevation)); mMenuSideEnum = MenuSideEnum.fromId(attr.getInt(R.styleable.ArcMenu_menu_open, 0)); mAnimationTime = attr.getInteger(R.styleable.ArcMenu_menu_animation_time, ANIMATION_TIME); mCurrentRadius = 0; if(mDrawable == null) { mDrawable = ContextCompat.getDrawable(getContext(), android.R.drawable.ic_dialog_email); } mRippleColor = attr.getColor(R.styleable.ArcMenu_menu_ripple_color, getThemeAccentColor(getContext(), R.attr.colorControlHighlight)); if(mColorStateList == null) { mColorStateList = ColorStateList.valueOf(getThemeAccentColor(getContext(), R.attr.colorAccent)); } switch (mMenuSideEnum) { case ARC_LEFT: mQuadrantAngle = POSITIVE_QUADRANT; break; case ARC_TOP_LEFT: mQuadrantAngle = NEGATIVE_QUADRANT; break; case ARC_RIGHT: mQuadrantAngle = NEGATIVE_QUADRANT; break; case ARC_TOP_RIGHT: mQuadrantAngle = POSITIVE_QUADRANT; break; } menuMargin = attr.getDimensionPixelSize(R.styleable.ArcMenu_menu_margin, resources.getDimensionPixelSize(R.dimen.fab_margin)); } /** * Helper method to get theme related attributes * @param context * @param resId * @return */ private int getThemeAccentColor(Context context, @AttrRes int resId) { TypedValue value = new TypedValue (); context.getTheme().resolveAttribute(resId, value, true); return value.data; } private void addMainMenu() { fabMenu.setImageDrawable(mDrawable); fabMenu.setBackgroundTintList(mColorStateList); fabMenu.setOnClickListener(mMenuClickListener); fabMenu.setRippleColor(mRippleColor); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) fabMenu.setElevation(mElevation); addView(fabMenu); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { layoutMenu(); if(!isInEditMode()) layoutChildren(); } private void layoutChildren() { layoutChildrenArc(); } private void layoutChildrenArc() { int childCount = getChildCount(); double eachAngle = getEachArcAngleInDegrees(); int leftPoint, topPoint, left, top; for (int i = 0; i < childCount; i++) { View child = getChildAt(i); if(child == fabMenu || child.getVisibility() == GONE) continue; else { double totalAngleForChild = eachAngle * (i); leftPoint = (int) (mCurrentRadius * Math.cos(Math.toRadians(totalAngleForChild))); topPoint = (int) (mCurrentRadius * Math.sin(Math.toRadians(totalAngleForChild))); switch (mMenuSideEnum) { case ARC_LEFT: case ARC_TOP_LEFT: left = cx - leftPoint; top = cy - topPoint; break; default: left = cx + leftPoint; top = cy + topPoint; break; } child.layout(left, top, left + child.getMeasuredWidth(), top + child.getMeasuredHeight()); } } } /** * Lays out the main fabMenu on the screen. * Currently, the library only supports laying out the menu on the bottom right or bottom left of the screen. * The proper layout position is directly dependent on the which side the radial arch menu will be show. * */ //TODO: work on fixing this private void layoutMenu() { switch (mMenuSideEnum) { case ARC_LEFT: cx = getMeasuredWidth() - fabMenu.getMeasuredWidth() - menuMargin; cy = getMeasuredHeight() - fabMenu.getMeasuredHeight() - menuMargin; break; case ARC_TOP_LEFT: cx = getMeasuredWidth() - fabMenu.getMeasuredWidth() - menuMargin; cy = menuMargin; break; case ARC_RIGHT: cx = menuMargin; cy = getMeasuredHeight() - fabMenu.getMeasuredHeight() - menuMargin; break; case ARC_TOP_RIGHT: cx = menuMargin; cy = menuMargin; break; } fabMenu.layout(cx, cy, cx + fabMenu.getMeasuredWidth(), cy + fabMenu.getMeasuredHeight()); } @Override protected void onFinishInflate() { super.onFinishInflate(); //The main menu is added as the last child of the view. addMainMenu(); toggleVisibilityOfAllChildViews(mIsOpened); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { measureChild(fabMenu, widthMeasureSpec, heightMeasureSpec); int width = fabMenu.getMeasuredWidth(); int height = fabMenu.getMeasuredHeight(); boolean accommodateRadius = false; int maxWidth, maxHeight; maxHeight = maxWidth = 0; int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { View child = getChildAt(i); if(child == fabMenu || child.getVisibility() == GONE) continue; else { accommodateRadius = true; measureChild(child, widthMeasureSpec, heightMeasureSpec); //maxHeight = Math.max(maxHeight, child.getMeasuredHeight()); //maxWidth = Math.max(maxWidth, child.getMeasuredWidth()); } } if(accommodateRadius) { int radius = Math.round(mCurrentRadius); width+=(radius + maxWidth); height+=(radius + maxHeight); } width+= menuMargin; height+= menuMargin; setMeasuredDimension(width, height); } /** * The number of menu items is the number of menu options added by the user. * This is 1 less than the total number of child views, because we manually add one view to the viewgroup which acts as the main menu. * @return */ private int getSubMenuCount() { return getChildCount() - 1; } /** * If there is only onle sub-menu, then it wil be placed at 45 degress. * For the rest, we use 90/(n-1), where n is the number of sub-menus; * @return */ private double getEachArcAngleInDegrees() { if(getSubMenuCount() == 1) return ANGLE_FOR_ONE_SUB_MENU; else return mQuadrantAngle / ((double) getSubMenuCount() - 1); } private void toggleVisibilityOfAllChildViews(boolean show) { for (int i = 0; i < getChildCount(); i++) { View child = getChildAt(i); if(child == fabMenu) continue; if(show) child.setVisibility(VISIBLE); else child.setVisibility(GONE); } } private OnClickListener mMenuClickListener = new OnClickListener() { @Override public void onClick(View v) { toggleMenu(); } }; private void beginOpenAnimation() { ValueAnimator openMenuAnimator = ValueAnimator.ofFloat(0, mFinalRadius); openMenuAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { mCurrentRadius = (float) animation.getAnimatedValue(); requestLayout(); } }); AnimatorSet animatorSet = new AnimatorSet(); animatorSet.setInterpolator(new AccelerateInterpolator()); List<Animator> animationCollection = new ArrayList<>(getSubMenuCount() + 1); animationCollection.add(openMenuAnimator); for (int i = 0; i < getChildCount(); i++) { View view = getChildAt(i); if(view == fabMenu) continue; animationCollection.add(ObjectAnimator.ofFloat(view, "scaleX", 0, 1)); animationCollection.add(ObjectAnimator.ofFloat(view, "scaleY", 0, 1)); animationCollection.add(ObjectAnimator.ofFloat(view, "alpha", 0, 1)); } animatorSet.playTogether(animationCollection); animatorSet.setDuration(mAnimationTime); animatorSet.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { toggleVisibilityOfAllChildViews(mIsOpened); } @Override public void onAnimationEnd(Animator animation) { if(mStateChangeListener!=null) mStateChangeListener.onMenuOpened(); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); animatorSet.start(); } private void beginCloseAnimation() { ValueAnimator closeMenuAnimator = ValueAnimator.ofFloat(mFinalRadius, 0); closeMenuAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { mCurrentRadius = (float) animation.getAnimatedValue(); requestLayout(); } }); final AnimatorSet animatorSet = new AnimatorSet(); animatorSet.setInterpolator(new AccelerateInterpolator()); List<Animator> animationCollection = new ArrayList<>(getSubMenuCount() + 1); animationCollection.add(closeMenuAnimator); AnimatorSet rotateAnimatorSet = new AnimatorSet(); rotateAnimatorSet.setInterpolator(new AccelerateInterpolator()); List<Animator> rotateAnimationCollection = new ArrayList<>(getSubMenuCount()); for (int i = 0; i < getChildCount(); i++) { View view = getChildAt(i); if(view == fabMenu) continue; animationCollection.add(ObjectAnimator.ofFloat(view, "scaleX", 1, 0)); animationCollection.add(ObjectAnimator.ofFloat(view, "scaleY", 1, 0)); animationCollection.add(ObjectAnimator.ofFloat(view, "alpha", 1, 0)); rotateAnimationCollection.add(ObjectAnimator.ofFloat(view, "rotation", 0, 360)); } animatorSet.playTogether(animationCollection); animatorSet.setDuration(mAnimationTime); animatorSet.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { toggleVisibilityOfAllChildViews(mIsOpened); if(mStateChangeListener!=null) mStateChangeListener.onMenuClosed(); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); rotateAnimatorSet.playTogether(rotateAnimationCollection); rotateAnimatorSet.setDuration(mAnimationTime/3); rotateAnimatorSet.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { animatorSet.start(); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); rotateAnimatorSet.start(); } @NonNull @Override public CoordinatorLayout.Behavior getBehavior() { return new MoveUpwardBehaviour(); } //ALL API Calls /** * Toggles the state of the ArcMenu, i.e. closes it if it is open and opens it if it is closed */ public void toggleMenu() { mIsOpened = !mIsOpened; if(mIsOpened) beginOpenAnimation(); else beginCloseAnimation(); } /** * Get the state of the ArcMenu, i.e. whether it is open or closed * @return true if the menu is open */ public boolean isMenuOpened() { return mIsOpened; } /** * Controls the animation time to transition the menu from close to open state and vice versa. * The time is represented in milli-seconds * @param animationTime */ public void setAnimationTime(long animationTime) { mAnimationTime = animationTime; } /** * Allows you to listen to the state changes of the Menu, i.e. * {@link StateChangeListener#onMenuOpened()} and {@link StateChangeListener#onMenuClosed()} events * @param stateChangeListener */ public void setStateChangeListener(StateChangeListener stateChangeListener) { this.mStateChangeListener = stateChangeListener; } @SuppressWarnings("unused") /** * Sets the display radius of the ArcMenu */ public void setRadius(float radius) { this.mFinalRadius = radius; invalidate(); } }
library/src/main/java/com/sa90/materialarcmenu/ArcMenu.java
package com.sa90.materialarcmenu; import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.os.Build; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; import android.view.animation.AccelerateInterpolator; import android.widget.FrameLayout; import androidx.annotation.AttrRes; import androidx.coordinatorlayout.widget.CoordinatorLayout; import androidx.core.content.ContextCompat; import com.google.android.material.floatingactionbutton.FloatingActionButton; import java.util.ArrayList; import java.util.List; /** * Created by Saurabh on 14/12/15. */ @CoordinatorLayout.DefaultBehavior(MoveUpwardBehaviour.class) public class ArcMenu extends FrameLayout { private static final double POSITIVE_QUADRANT = 90; private static final double NEGATIVE_QUADRANT = -90; private static final double ANGLE_FOR_ONE_SUB_MENU = 0; private static final int ANIMATION_TIME = 300; //This time is in milliseconds FloatingActionButton fabMenu; public Drawable mDrawable; ColorStateList mColorStateList; int mRippleColor; long mAnimationTime; float mCurrentRadius, mFinalRadius, mElevation; int menuMargin; boolean mIsOpened = false; double mQuadrantAngle; MenuSideEnum mMenuSideEnum; int cx, cy; //Represents the center points of the circle whose arc we are considering private StateChangeListener mStateChangeListener; public ArcMenu(Context context) { super(context); } public ArcMenu(Context context, AttributeSet attrs) { super(context, attrs); TypedArray attr = context.obtainStyledAttributes(attrs, R.styleable.ArcMenu, 0, 0); init(attr); fabMenu = new FloatingActionButton(context, attrs); } private void init(TypedArray attr) { Resources resources = getResources(); mDrawable = attr.getDrawable(R.styleable.ArcMenu_menu_scr); mColorStateList = attr.getColorStateList(R.styleable.ArcMenu_menu_color); mFinalRadius = attr.getDimension(R.styleable.ArcMenu_menu_radius, resources.getDimension(R.dimen.default_radius)); mElevation = attr.getDimension(R.styleable.ArcMenu_menu_elevation, resources.getDimension(R.dimen.default_elevation)); mMenuSideEnum = MenuSideEnum.fromId(attr.getInt(R.styleable.ArcMenu_menu_open, 0)); mAnimationTime = attr.getInteger(R.styleable.ArcMenu_menu_animation_time, ANIMATION_TIME); mCurrentRadius = 0; if(mDrawable == null) { mDrawable = ContextCompat.getDrawable(getContext(), android.R.drawable.ic_dialog_email); } mRippleColor = attr.getColor(R.styleable.ArcMenu_menu_ripple_color, getThemeAccentColor(getContext(), R.attr.colorControlHighlight)); if(mColorStateList == null) { mColorStateList = ColorStateList.valueOf(getThemeAccentColor(getContext(), R.attr.colorAccent)); } switch (mMenuSideEnum) { case ARC_LEFT: mQuadrantAngle = POSITIVE_QUADRANT; break; case ARC_TOP_LEFT: mQuadrantAngle = NEGATIVE_QUADRANT; break; case ARC_RIGHT: mQuadrantAngle = NEGATIVE_QUADRANT; break; case ARC_TOP_RIGHT: mQuadrantAngle = POSITIVE_QUADRANT; break; } menuMargin = attr.getDimensionPixelSize(R.styleable.ArcMenu_menu_margin, resources.getDimensionPixelSize(R.dimen.fab_margin)); } /** * Helper method to get theme related attributes * @param context * @param resId * @return */ private int getThemeAccentColor(Context context, @AttrRes int resId) { TypedValue value = new TypedValue (); context.getTheme().resolveAttribute(resId, value, true); return value.data; } private void addMainMenu() { fabMenu.setImageDrawable(mDrawable); fabMenu.setBackgroundTintList(mColorStateList); fabMenu.setOnClickListener(mMenuClickListener); fabMenu.setRippleColor(mRippleColor); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) fabMenu.setElevation(mElevation); addView(fabMenu); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { layoutMenu(); if(!isInEditMode()) layoutChildren(); } private void layoutChildren() { layoutChildrenArc(); } private void layoutChildrenArc() { int childCount = getChildCount(); double eachAngle = getEachArcAngleInDegrees(); int leftPoint, topPoint, left, top; for (int i = 0; i < childCount; i++) { View child = getChildAt(i); if(child == fabMenu || child.getVisibility() == GONE) continue; else { double totalAngleForChild = eachAngle * (i); leftPoint = (int) (mCurrentRadius * Math.cos(Math.toRadians(totalAngleForChild))); topPoint = (int) (mCurrentRadius * Math.sin(Math.toRadians(totalAngleForChild))); switch (mMenuSideEnum) { case ARC_LEFT: case ARC_TOP_LEFT: left = cx - leftPoint; top = cy - topPoint; break; default: left = cx + leftPoint; top = cy + topPoint; break; } child.layout(left, top, left + child.getMeasuredWidth(), top + child.getMeasuredHeight()); } } } /** * Lays out the main fabMenu on the screen. * Currently, the library only supports laying out the menu on the bottom right or bottom left of the screen. * The proper layout position is directly dependent on the which side the radial arch menu will be show. * */ //TODO: work on fixing this private void layoutMenu() { switch (mMenuSideEnum) { case ARC_LEFT: cx = getMeasuredWidth() - fabMenu.getMeasuredWidth() - menuMargin; cy = getMeasuredHeight() - fabMenu.getMeasuredHeight() - menuMargin; break; case ARC_TOP_LEFT: cx = getMeasuredWidth() - fabMenu.getMeasuredWidth() - menuMargin; cy = menuMargin; break; case ARC_RIGHT: cx = menuMargin; cy = getMeasuredHeight() - fabMenu.getMeasuredHeight() - menuMargin; break; case ARC_TOP_RIGHT: cx = menuMargin; cy = menuMargin; break; } fabMenu.layout(cx, cy, cx + fabMenu.getMeasuredWidth(), cy + fabMenu.getMeasuredHeight()); } @Override protected void onFinishInflate() { super.onFinishInflate(); //The main menu is added as the last child of the view. addMainMenu(); toggleVisibilityOfAllChildViews(mIsOpened); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { measureChild(fabMenu, widthMeasureSpec, heightMeasureSpec); int width = fabMenu.getMeasuredWidth(); int height = fabMenu.getMeasuredHeight(); boolean accommodateRadius = false; int maxWidth, maxHeight; maxHeight = maxWidth = 0; int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { View child = getChildAt(i); if(child == fabMenu || child.getVisibility() == GONE) continue; else { accommodateRadius = true; measureChild(child, widthMeasureSpec, heightMeasureSpec); //maxHeight = Math.max(maxHeight, child.getMeasuredHeight()); //maxWidth = Math.max(maxWidth, child.getMeasuredWidth()); } } if(accommodateRadius) { int radius = Math.round(mCurrentRadius); width+=(radius + maxWidth); height+=(radius + maxHeight); } width+= menuMargin; height+= menuMargin; setMeasuredDimension(width, height); } /** * The number of menu items is the number of menu options added by the user. * This is 1 less than the total number of child views, because we manually add one view to the viewgroup which acts as the main menu. * @return */ private int getSubMenuCount() { return getChildCount() - 1; } /** * If there is only onle sub-menu, then it wil be placed at 45 degress. * For the rest, we use 90/(n-1), where n is the number of sub-menus; * @return */ private double getEachArcAngleInDegrees() { if(getSubMenuCount() == 1) return ANGLE_FOR_ONE_SUB_MENU; else return mQuadrantAngle / ((double) getSubMenuCount() - 1); } private void toggleVisibilityOfAllChildViews(boolean show) { for (int i = 0; i < getChildCount(); i++) { View child = getChildAt(i); if(child == fabMenu) continue; if(show) child.setVisibility(VISIBLE); else child.setVisibility(GONE); } } private OnClickListener mMenuClickListener = new OnClickListener() { @Override public void onClick(View v) { toggleMenu(); } }; private void beginOpenAnimation() { ValueAnimator openMenuAnimator = ValueAnimator.ofFloat(0, mFinalRadius); openMenuAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { mCurrentRadius = (float) animation.getAnimatedValue(); requestLayout(); } }); AnimatorSet animatorSet = new AnimatorSet(); animatorSet.setInterpolator(new AccelerateInterpolator()); List<Animator> animationCollection = new ArrayList<>(getSubMenuCount() + 1); animationCollection.add(openMenuAnimator); for (int i = 0; i < getChildCount(); i++) { View view = getChildAt(i); if(view == fabMenu) continue; animationCollection.add(ObjectAnimator.ofFloat(view, "scaleX", 0, 1)); animationCollection.add(ObjectAnimator.ofFloat(view, "scaleY", 0, 1)); animationCollection.add(ObjectAnimator.ofFloat(view, "alpha", 0, 1)); } animatorSet.playTogether(animationCollection); animatorSet.setDuration(mAnimationTime); animatorSet.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { toggleVisibilityOfAllChildViews(mIsOpened); } @Override public void onAnimationEnd(Animator animation) { if(mStateChangeListener!=null) mStateChangeListener.onMenuOpened(); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); animatorSet.start(); } private void beginCloseAnimation() { ValueAnimator closeMenuAnimator = ValueAnimator.ofFloat(mFinalRadius, 0); closeMenuAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { mCurrentRadius = (float) animation.getAnimatedValue(); requestLayout(); } }); final AnimatorSet animatorSet = new AnimatorSet(); animatorSet.setInterpolator(new AccelerateInterpolator()); List<Animator> animationCollection = new ArrayList<>(getSubMenuCount() + 1); animationCollection.add(closeMenuAnimator); AnimatorSet rotateAnimatorSet = new AnimatorSet(); rotateAnimatorSet.setInterpolator(new AccelerateInterpolator()); List<Animator> rotateAnimationCollection = new ArrayList<>(getSubMenuCount()); for (int i = 0; i < getChildCount(); i++) { View view = getChildAt(i); if(view == fabMenu) continue; animationCollection.add(ObjectAnimator.ofFloat(view, "scaleX", 1, 0)); animationCollection.add(ObjectAnimator.ofFloat(view, "scaleY", 1, 0)); animationCollection.add(ObjectAnimator.ofFloat(view, "alpha", 1, 0)); rotateAnimationCollection.add(ObjectAnimator.ofFloat(view, "rotation", 0, 360)); } animatorSet.playTogether(animationCollection); animatorSet.setDuration(mAnimationTime); animatorSet.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { toggleVisibilityOfAllChildViews(mIsOpened); if(mStateChangeListener!=null) mStateChangeListener.onMenuClosed(); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); rotateAnimatorSet.playTogether(rotateAnimationCollection); rotateAnimatorSet.setDuration(mAnimationTime/3); rotateAnimatorSet.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { animatorSet.start(); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); rotateAnimatorSet.start(); } //ALL API Calls /** * Toggles the state of the ArcMenu, i.e. closes it if it is open and opens it if it is closed */ public void toggleMenu() { mIsOpened = !mIsOpened; if(mIsOpened) beginOpenAnimation(); else beginCloseAnimation(); } /** * Get the state of the ArcMenu, i.e. whether it is open or closed * @return true if the menu is open */ public boolean isMenuOpened() { return mIsOpened; } /** * Controls the animation time to transition the menu from close to open state and vice versa. * The time is represented in milli-seconds * @param animationTime */ public void setAnimationTime(long animationTime) { mAnimationTime = animationTime; } /** * Allows you to listen to the state changes of the Menu, i.e. * {@link StateChangeListener#onMenuOpened()} and {@link StateChangeListener#onMenuClosed()} events * @param stateChangeListener */ public void setStateChangeListener(StateChangeListener stateChangeListener) { this.mStateChangeListener = stateChangeListener; } @SuppressWarnings("unused") /** * Sets the display radius of the ArcMenu */ public void setRadius(float radius) { this.mFinalRadius = radius; invalidate(); } }
remove deprecated functions
library/src/main/java/com/sa90/materialarcmenu/ArcMenu.java
remove deprecated functions
<ide><path>ibrary/src/main/java/com/sa90/materialarcmenu/ArcMenu.java <ide> import android.widget.FrameLayout; <ide> <ide> import androidx.annotation.AttrRes; <add>import androidx.annotation.NonNull; <ide> import androidx.coordinatorlayout.widget.CoordinatorLayout; <ide> import androidx.core.content.ContextCompat; <ide> <ide> /** <ide> * Created by Saurabh on 14/12/15. <ide> */ <del>@CoordinatorLayout.DefaultBehavior(MoveUpwardBehaviour.class) <del>public class ArcMenu extends FrameLayout { <add>public class ArcMenu extends FrameLayout implements CoordinatorLayout.AttachedBehavior { <ide> <ide> private static final double POSITIVE_QUADRANT = 90; <ide> private static final double NEGATIVE_QUADRANT = -90; <ide> rotateAnimatorSet.start(); <ide> } <ide> <add> @NonNull <add> @Override <add> public CoordinatorLayout.Behavior getBehavior() { <add> return new MoveUpwardBehaviour(); <add> } <add> <ide> //ALL API Calls <ide> <ide> /**
Java
apache-2.0
e486c9e724fe6ea3af5687f2617d7f9fa2531072
0
vorburger/mifos-head,vorburger/mifos-head,jpodeszwik/mifos,maduhu/head,maduhu/head,maduhu/head,AArhin/head,vorburger/mifos-head,maduhu/mifos-head,jpodeszwik/mifos,maduhu/mifos-head,jpodeszwik/mifos,AArhin/head,maduhu/mifos-head,AArhin/head,maduhu/mifos-head,maduhu/head,maduhu/head,AArhin/head,maduhu/mifos-head,jpodeszwik/mifos,vorburger/mifos-head,AArhin/head
/* * Copyright (c) 2005-2009 Grameen Foundation USA * All rights reserved. * * 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. * * See also http://www.apache.org/licenses/LICENSE-2.0.html for an * explanation of the license and how it is applied. */ package org.mifos.application.accounts.loan.struts.actionforms; import static org.apache.commons.lang.StringUtils.isBlank; import java.sql.Date; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; import javax.servlet.http.HttpServletRequest; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.Predicate; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.mifos.application.accounts.exceptions.AccountException; import org.mifos.application.accounts.loan.business.LoanBO; import org.mifos.application.accounts.loan.struts.uihelpers.PaymentDataHtmlBean; import org.mifos.application.accounts.loan.util.helpers.LoanAccountDetailsViewHelper; import org.mifos.application.accounts.loan.util.helpers.LoanConstants; import org.mifos.application.accounts.loan.util.helpers.LoanExceptionConstants; import org.mifos.application.accounts.loan.util.helpers.RepaymentScheduleInstallment; import org.mifos.application.accounts.util.helpers.AccountState; import org.mifos.application.accounts.util.helpers.PaymentDataTemplate; import org.mifos.application.configuration.business.service.ConfigurationBusinessService; import org.mifos.application.configuration.util.helpers.ConfigurationConstants; import org.mifos.application.customer.business.CustomerBO; import org.mifos.application.customer.business.service.CustomerBusinessService; import org.mifos.application.fees.business.FeeView; import org.mifos.application.master.business.CustomFieldDefinitionEntity; import org.mifos.application.master.business.CustomFieldView; import org.mifos.application.meeting.exceptions.MeetingException; import org.mifos.application.meeting.util.helpers.RecurrenceType; import org.mifos.application.personnel.business.PersonnelBO; import org.mifos.application.personnel.persistence.PersonnelPersistence; import org.mifos.application.productdefinition.business.AmountRange; import org.mifos.application.productdefinition.business.InstallmentRange; import org.mifos.application.productdefinition.business.LoanOfferingBO; import org.mifos.application.util.helpers.EntityType; import org.mifos.application.util.helpers.Methods; import org.mifos.application.util.helpers.YesNoFlag; import org.mifos.framework.components.configuration.persistence.ConfigurationPersistence; import org.mifos.framework.components.fieldConfiguration.business.FieldConfigurationEntity; import org.mifos.framework.exceptions.ApplicationException; import org.mifos.framework.exceptions.InvalidDateException; import org.mifos.framework.exceptions.PageExpiredException; import org.mifos.framework.exceptions.PersistenceException; import org.mifos.framework.exceptions.PropertyNotFoundException; import org.mifos.framework.exceptions.ServiceException; import org.mifos.framework.security.util.UserContext; import org.mifos.framework.struts.actionforms.BaseActionForm; import org.mifos.framework.util.helpers.Constants; import org.mifos.framework.util.helpers.DateUtils; import org.mifos.framework.util.helpers.ExceptionConstants; import org.mifos.framework.util.helpers.FilePaths; import org.mifos.framework.util.helpers.Money; import org.mifos.framework.util.helpers.SessionUtils; import org.mifos.framework.util.helpers.StringUtils; public class LoanAccountActionForm extends BaseActionForm { public LoanAccountActionForm() { super(); defaultFees = new ArrayList<FeeView>(); additionalFees = new ArrayList<FeeView>(); customFields = new ArrayList<CustomFieldView>(); clients = new ArrayList<String>(); clientDetails = new ArrayList<LoanAccountDetailsViewHelper>(); configService = new ConfigurationBusinessService(); } // For individual monitoring private List<String> clients; private List<LoanAccountDetailsViewHelper> clientDetails; private String perspective; private String accountId; private String globalAccountNum; private String prdOfferingName; private String accountName; private String accountTypeId; private String customerId; private String prdOfferingId; private String loanAmount; private String interestRate; private String noOfInstallments; private String disbursementDate; private String intDedDisbursement; private String loanOfferingFund; private String gracePeriodDuration; private String externalId; private String businessActivityId; private String collateralTypeId; private String collateralNote; private List<FeeView> defaultFees; private List<FeeView> additionalFees; private String stateSelected; private String gracePeriod; private List<CustomFieldView> customFields; private List<PaymentDataHtmlBean> paymentDataBeans = new ArrayList(); // For Repayment day private String monthRank; private String weekRank; private String monthWeek; private String monthType; private String monthDay; private String dayRecurMonth; private String weekDay; private String recurMonth; private String recurWeek; private String frequency; private String firstRepaymentDay; private String recurrenceId; private AmountRange amountRange; private InstallmentRange installmentRange; private String dayNumber; private ConfigurationBusinessService configService; public String getDayNumber() { return dayNumber; } public void setDayNumber(String dayNumber) { this.dayNumber = dayNumber; } public String getMonthRank() { return monthRank; } public void setMonthRank(String monthRank) { this.monthRank = monthRank; } public String getMonthWeek() { return monthWeek; } public void setMonthWeek(String monthWeek) { this.monthWeek = monthWeek; } public String getMonthType() { return monthType; } public void setMonthType(String monthType) { this.monthType = monthType; } public String getMonthDay() { return monthDay; } public void setMonthDay(String monthDay) { this.monthDay = monthDay; } public String getDayRecurMonth() { return dayRecurMonth; } public void setDayRecurMonth(String dayRecurMonth) { this.dayRecurMonth = dayRecurMonth; } public String getRecurMonth() { return recurMonth; } public void setRecurMonth(String recurMonth) { this.recurMonth = recurMonth; } public String getRecurWeek() { return recurWeek; } public void setRecurWeek(String recurWeek) { this.recurWeek = recurWeek; } public String getFrequency() { return frequency; } public void setFrequency(String frequency) { this.frequency = frequency; } public String getWeekDay() { return weekDay; } public void setWeekDay(String weekDay) { this.weekDay = weekDay; } public String getWeekRank() { return weekRank; } public void setWeekRank(String weekRank) { this.weekRank = weekRank; } public String getRecurrenceId() { return recurrenceId; } public void setRecurrenceId(String recurrenceId) { this.recurrenceId = recurrenceId; } public List<PaymentDataHtmlBean> getPaymentDataBeans() { return this.paymentDataBeans; } public String getGracePeriod() { return gracePeriod; } public void setGracePeriod(String gracePeriod) { this.gracePeriod = gracePeriod; } public String getExternalId() { return this.externalId; } public void setExternalId(String externalId) { this.externalId = externalId; } public String getAccountId() { return accountId; } public void setAccountId(String accountId) { this.accountId = accountId; } public String getAccountName() { return accountName; } public void setAccountName(String accountName) { this.accountName = accountName; } public String getAccountTypeId() { return accountTypeId; } public void setAccountTypeId(String accountTypeId) { this.accountTypeId = accountTypeId; } public String getCustomerId() { return customerId; } public void setCustomerId(String customerId) { this.customerId = customerId; } public String getGlobalAccountNum() { return globalAccountNum; } public void setGlobalAccountNum(String globalAccountNum) { this.globalAccountNum = globalAccountNum; } public String getPrdOfferingName() { return prdOfferingName; } public void setPrdOfferingName(String prdOfferingName) { this.prdOfferingName = prdOfferingName; } public String getPrdOfferingId() { return prdOfferingId; } public void setPrdOfferingId(String prdOfferingId) { this.prdOfferingId = prdOfferingId; } public String getBusinessActivityId() { return businessActivityId; } public void setBusinessActivityId(String businessActivityId) { this.businessActivityId = businessActivityId; } public String getCollateralNote() { return collateralNote; } public void setCollateralNote(String collateralNote) { this.collateralNote = collateralNote; } public String getCollateralTypeId() { return collateralTypeId; } public void setCollateralTypeId(String collateralTypeId) { this.collateralTypeId = collateralTypeId; } public String getDisbursementDate() { return disbursementDate; } public void setDisbursementDate(String disbursementDate) { this.disbursementDate = disbursementDate; } public String getGracePeriodDuration() { return gracePeriodDuration; } public void setGracePeriodDuration(String gracePeriodDuration) { this.gracePeriodDuration = gracePeriodDuration; } public String getIntDedDisbursement() { return intDedDisbursement; } public void setIntDedDisbursement(String intDedDisbursement) { this.intDedDisbursement = intDedDisbursement; } public String getInterestRate() { return interestRate; } public void setInterestRate(String interestRate) { this.interestRate = interestRate; } public String getLoanAmount() { return loanAmount; } public void setLoanAmount(String loanAmount) { this.loanAmount = loanAmount; } public String getLoanOfferingFund() { return loanOfferingFund; } public void setLoanOfferingFund(String loanOfferingFund) { this.loanOfferingFund = loanOfferingFund; } public String getNoOfInstallments() { return noOfInstallments; } public void setNoOfInstallments(String noOfInstallments) { this.noOfInstallments = noOfInstallments; } public List<CustomFieldView> getCustomFields() { return customFields; } public void setCustomFields(List<CustomFieldView> customFields) { this.customFields = customFields; } public CustomFieldView getCustomField(int i) { while (i >= customFields.size()) { customFields.add(new CustomFieldView()); } return customFields.get(i); } public List<FeeView> getAdditionalFees() { return additionalFees; } public void setAdditionalFees(List<FeeView> additionalFees) { this.additionalFees = additionalFees; } public List<FeeView> getDefaultFees() { return defaultFees; } public void setDefaultFees(List<FeeView> defaultFees) { this.defaultFees = defaultFees; } public String getStateSelected() { return stateSelected; } public void setStateSelected(String stateSelected) { this.stateSelected = stateSelected; } public AccountState getState() throws PropertyNotFoundException { return AccountState.fromShort(getShortValue(getStateSelected())); } public Integer getCustomerIdValue() { return getIntegerValue(getCustomerId()); } public Short getPrdOfferingIdValue() { return getShortValue(getPrdOfferingId()); } public Short getGracePeriodDurationValue() { return getShortValue(getGracePeriodDuration()); } public Money loanAmountValue() { return getMoney(getLoanAmount()); } public Short getNoOfInstallmentsValue() { return getShortValue(getNoOfInstallments()); } public Date getDisbursementDateValue(Locale locale) throws InvalidDateException { return DateUtils.getLocaleDate(locale, getDisbursementDate()); } public Date getFirstRepaymentDayValue(Locale locale) throws InvalidDateException { return DateUtils.getLocaleDate(locale, getFirstRepaymentDay()); } public boolean isInterestDedAtDisbValue() { return getBooleanValue(getIntDedDisbursement()); } public Double getInterestDoubleValue() { return getDoubleValue(getInterestRate()); } public Short getLoanOfferingFundValue() { return getShortValue(getLoanOfferingFund()); } public Integer getBusinessActivityIdValue() { return getIntegerValue(getBusinessActivityId()); } public Integer getCollateralTypeIdValue() { return getIntegerValue(getCollateralTypeId()); } public Money getLoanAmountValue() { return getMoney(loanAmount); } public Double getInterestRateValue() { return getDoubleValue(interestRate); } public FeeView getDefaultFee(int i) { while (i >= defaultFees.size()) { defaultFees.add(new FeeView()); } return defaultFees.get(i); } public Boolean isInterestDeductedAtDisbursment() { if (getIntDedDisbursement().equals("1")) return true; return false; } public void initializeTransactionFields(UserContext userContext, List<RepaymentScheduleInstallment> installments) { this.paymentDataBeans = new ArrayList(installments.size()); PersonnelBO personnel; try { personnel = new PersonnelPersistence().getPersonnel(userContext.getId()); } catch (PersistenceException e) { throw new IllegalArgumentException("bad UserContext id"); } for (Iterator<RepaymentScheduleInstallment> iter = installments.iterator(); iter.hasNext();) { this.paymentDataBeans .add(new PaymentDataHtmlBean(userContext.getPreferredLocale(), personnel, iter.next())); } } public List<FeeView> getFeesToApply() { List<FeeView> feesToApply = new ArrayList<FeeView>(); for (FeeView fee : getAdditionalFees()) if (fee.getFeeIdValue() != null) feesToApply.add(fee); for (FeeView fee : getDefaultFees()) if (!fee.isRemoved()) feesToApply.add(fee); return feesToApply; } public FeeView getSelectedFee(int index) { while (index >= additionalFees.size()) additionalFees.add(new FeeView()); return additionalFees.get(index); } @Override public void reset(ActionMapping mapping, HttpServletRequest request) { super.reset(mapping, request); String method = request.getParameter(Methods.method.toString()); if (method.equals(Methods.schedulePreview.toString())) { intDedDisbursement = null; for (int i = 0; i < defaultFees.size(); i++) { // if an already checked fee is unchecked then the value set to // 0 if (request.getParameter("defaultFee[" + i + "].feeRemoved") == null) { defaultFees.get(i).setFeeRemoved(YesNoFlag.NO.getValue()); } } } else if (method.equals(Methods.load.toString())) { clients = new ArrayList<String>(); } else if (method.equals(Methods.managePreview.toString())) { intDedDisbursement = "0"; } } @Override public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { String method = request.getParameter(Methods.method.toString()); ActionErrors errors = new ActionErrors(); UserContext userContext = getUserContext(request); if (null == request.getAttribute(Constants.CURRENTFLOWKEY)) request.setAttribute(Constants.CURRENTFLOWKEY, request.getParameter(Constants.CURRENTFLOWKEY)); try { if (method.equals(Methods.getPrdOfferings.toString())) checkValidationForGetPrdOfferings(errors, userContext); else if (method.equals(Methods.load.toString())) checkValidationForLoad(errors, userContext); else if (method.equals(Methods.schedulePreview.toString())) checkValidationForSchedulePreview(errors, request); else if (method.equals(Methods.managePreview.toString())) checkValidationForManagePreview(errors, request); else if (method.equals(Methods.preview.toString())) checkValidationForPreview(errors, request); } catch (ApplicationException ae) { // Discard other errors (is that right?) ae.printStackTrace(); errors = new ActionErrors(); errors.add(ae.getKey(), new ActionMessage(ae.getKey(), ae.getValues())); } if (!errors.isEmpty()) { request.setAttribute(LoanConstants.METHODCALLED, method); } return errors; } // TODO: use localized strings for error messages rather than hardcoded private void checkValidationForGetPrdOfferings(ActionErrors errors, UserContext userContext) { if (StringUtils.isNullOrEmpty(getCustomerId())) { addError(errors, LoanConstants.CUSTOMER, LoanConstants.CUSTOMERNOTSELECTEDERROR, getLabel( ConfigurationConstants.CLIENT, userContext), getLabel(ConfigurationConstants.GROUP, userContext)); } } // TODO: use localized strings for error messages rather than hardcoded private void checkValidationForLoad(ActionErrors errors, UserContext userContext) { checkValidationForGetPrdOfferings(errors, userContext); if (StringUtils.isNullOrEmpty(getPrdOfferingId())) { Locale locale = userContext.getCurrentLocale(); ResourceBundle resources = ResourceBundle.getBundle(FilePaths.LOAN_UI_RESOURCE_PROPERTYFILE, locale); String instanceName = resources.getString("loan.instanceName"); addError(errors, LoanConstants.PRDOFFERINGID, LoanConstants.LOANOFFERINGNOTSELECTEDERROR, getLabel( ConfigurationConstants.LOAN, userContext), instanceName); } } private void checkValidationForSchedulePreview(ActionErrors errors, HttpServletRequest request) throws ApplicationException { checkValidationForPreviewBefore(errors, request); validateFees(request, errors); validateCustomFields(request, errors); performGlimSpecificValidations(errors, request); validateRepaymentDayRequired(request, errors); validatePurposeOfLoanFields(errors, getMandatoryFields(request)); } private void performGlimSpecificValidations(ActionErrors errors, HttpServletRequest request) throws PageExpiredException, ServiceException { if (configService.isGlimEnabled() && getCustomer(request).isGroup()) { removeClientsNotCheckedInForm(request); validateIndividualLoanFieldsForGlim(request, errors); validateSelectedClients(errors); validateSumOfTheAmountsSpecified(errors); validatePurposeOfLoanForGlim(errors); } } // Since this Struts form is set up as "session" scope, we need to clear // the form fields in cases where they are used across pages. // Currently we do that in the following case: When old values of clientId // are // retained from the account creation page, form validation // on submission from the Edit Account Information page is messed up. // Calling // this method fixes that problem private void removeClientsNotCheckedInForm(HttpServletRequest request) { List<String> clientIds = getSelectedClientIdsFromRequest(request); setClientsNotPresentInInputToEmptyString(clientIds); } void setClientsNotPresentInInputToEmptyString(List<String> clientIds) { for (int i = 0; i < clients.size(); i++) { if (!clientIds.contains(clients.get(i))) { clients.set(i, ""); } } } List<String> getSelectedClientIdsFromRequest(HttpServletRequest request) { Collection paramsStartingWithClients = CollectionUtils.select(convertEnumerationToList(request .getParameterNames()), new Predicate() { public boolean evaluate(Object object) { return ((String) object).startsWith("clients"); } }); List<String> indices = extractClientIdsFromRequest(request, paramsStartingWithClients); return indices; } private List<String> extractClientIdsFromRequest(HttpServletRequest request, Collection paramsStartingWithClients) { List<String> clientIds = new ArrayList<String>(); for (Iterator iter = paramsStartingWithClients.iterator(); iter.hasNext();) { String element = (String) iter.next(); clientIds.add(request.getParameter(element)); } return clientIds; } private List<String> convertEnumerationToList(Enumeration parameterNames) { List<String> params = new ArrayList<String>(); while (parameterNames.hasMoreElements()) { params.add((String) parameterNames.nextElement()); } return params; } void validatePurposeOfLoanForGlim(ActionErrors errors) { List<String> ids_clients_selected = getClients(); List<LoanAccountDetailsViewHelper> listdetail = getClientDetails(); for (LoanAccountDetailsViewHelper loanAccount : listdetail) { if (ids_clients_selected.contains(loanAccount.getClientId())) { if (StringUtils.isNullOrEmpty(loanAccount.getBusinessActivity())) { addErrorInvalidPurpose(errors); return; } } } } private void addErrorInvalidPurpose(ActionErrors errors) { addError(errors, LoanExceptionConstants.CUSTOMER_PURPOSE_OF_LOAN_FIELD); } private void validatePurposeOfLoanFields(ActionErrors errors, List<FieldConfigurationEntity> mandatoryFields) { if (isPurposeOfLoanMandatory(mandatoryFields) && StringUtils.isNullOrEmpty(getBusinessActivityId())) { addErrorInvalidPurpose(errors); } } private void checkValidationForPreview(ActionErrors errors, HttpServletRequest request) throws ApplicationException { validateRedoLoanPayments(request, errors); } private void checkValidationForManagePreview(ActionErrors errors, HttpServletRequest request) throws ApplicationException { if (getState().equals(AccountState.LOAN_PARTIAL_APPLICATION) || getState().equals(AccountState.LOAN_PENDING_APPROVAL)) { checkValidationForPreview(errors, request); // Only validate the disbursement date before a loan has been approved. After // approval, it cannot be edited. try { validateDisbursementDate(errors, getCustomer(request), getDisbursementDateValue(getUserContext(request) .getPreferredLocale())); } catch (InvalidDateException dateException) { addError(errors, LoanExceptionConstants.ERROR_INVALIDDISBURSEMENTDATE); } } performGlimSpecificValidations(errors, request); validateCustomFields(request, errors); validateRepaymentDayRequired(request, errors); } private void validateDisbursementDate(ActionErrors errors, CustomerBO customer, java.sql.Date disbursementDateValue) throws AccountException, ServiceException { if (!configService.isRepaymentIndepOfMeetingEnabled() && !LoanBO.isDisbursementDateValid(customer, disbursementDateValue)) { addError(errors, LoanExceptionConstants.INVALIDDISBURSEMENTDATE); } } private void checkValidationForPreviewBefore(ActionErrors errors, HttpServletRequest request) throws ApplicationException { Locale locale = getUserContext(request).getPreferredLocale(); ResourceBundle resources = ResourceBundle.getBundle(FilePaths.LOAN_UI_RESOURCE_PROPERTYFILE, locale); LoanOfferingBO loanOffering = (LoanOfferingBO) SessionUtils.getAttribute(LoanConstants.LOANOFFERING, request); if (!new ConfigurationBusinessService().isGlimEnabled()) { checkForMinMax(errors, loanAmount, amountRange, resources.getString("loan.amount")); } checkForMinMax(errors, interestRate, loanOffering.getMaxInterestRate(), loanOffering.getMinInterestRate(), resources.getString("loan.noOfInstallments")); checkForMinMax(errors, noOfInstallments, installmentRange, resources.getString("loan.noOfInstallments")); if (StringUtils.isNullOrEmpty(getDisbursementDate())) { addError(errors, "Proposed/Actual disbursal date", "errors.validandmandatory", resources .getString("loan.disbursalDate")); } if (isInterestDedAtDisbValue()) { setGracePeriodDuration("0"); } if (((!isInterestDedAtDisbValue()) && StringUtils.isNullOrEmpty(getGracePeriodDuration())) || (getDoubleValue(getGracePeriodDuration()) != null && getDoubleValue(getNoOfInstallments()) != null && getDoubleValue(getGracePeriodDuration()) >= getDoubleValue(getNoOfInstallments()))) { String gracePeriodForRepayments = resources.getString("loan.gracePeriodForRepayments"); String noInst = StringUtils.isNullOrEmpty(getNoOfInstallments()) ? getStringValue(installmentRange .getMaxNoOfInstall()) : getNoOfInstallments(); addError(errors, LoanConstants.GRACEPERIODDURATION, LoanConstants.GRACEPERIODERROR, gracePeriodForRepayments, noInst); } } void checkForMinMax(ActionErrors errors, String currentValue, AmountRange amountRange, String field) { if (isBlank(currentValue) || !amountRange.isInRange(getDoubleValue(currentValue))) { addError(errors, field, LoanExceptionConstants.INVALIDMINMAX, field, getStringValue(amountRange .getMinLoanAmount()), getStringValue(amountRange.getMaxLoanAmount())); } } void checkForMinMax(ActionErrors errors, String currentValue, InstallmentRange installmentRange, String field) { if (StringUtils.isNullOrEmpty(currentValue) || !installmentRange.isInRange(getShortValue(currentValue))) { addError(errors, field, LoanExceptionConstants.INVALIDMINMAX, field, getStringValue(installmentRange .getMinNoOfInstall()), getStringValue(installmentRange.getMaxNoOfInstall())); } } private void checkForMinMax(ActionErrors errors, String currentValue, Double maxValue, Double minValue, String field) { if (StringUtils.isNullOrEmpty(currentValue) || getDoubleValue(currentValue).doubleValue() > maxValue.doubleValue() || getDoubleValue(currentValue).doubleValue() < minValue.doubleValue()) { addError(errors, field, LoanExceptionConstants.INVALIDMINMAX, field, getStringValue(minValue), getStringValue(maxValue)); } } protected void validateFees(HttpServletRequest request, ActionErrors errors) throws ApplicationException { validateForFeeAmount(errors); validateForDuplicatePeriodicFee(request, errors); } protected void validateForFeeAmount(ActionErrors errors) { List<FeeView> feeList = getFeesToApply(); for (FeeView fee : feeList) { if (StringUtils.isNullOrEmpty(fee.getAmount())) errors.add(LoanConstants.FEE, new ActionMessage(LoanConstants.ERRORS_SPECIFY_FEE_AMOUNT)); } } protected void validateForDuplicatePeriodicFee(HttpServletRequest request, ActionErrors errors) throws ApplicationException { List<FeeView> additionalFeeList = (List<FeeView>) SessionUtils.getAttribute(LoanConstants.ADDITIONAL_FEES_LIST, request); for (FeeView selectedFee : getAdditionalFees()) { int count = 0; for (FeeView duplicateSelectedfee : getAdditionalFees()) { if (selectedFee.getFeeIdValue() != null && selectedFee.getFeeId().equals(duplicateSelectedfee.getFeeId())) { if (isSelectedFeePeriodic(selectedFee, additionalFeeList)) count++; } } if (count > 1) { errors.add(LoanConstants.FEE, new ActionMessage(LoanConstants.ERRORS_DUPLICATE_PERIODIC_FEE)); break; } } } private boolean isSelectedFeePeriodic(FeeView selectedFee, List<FeeView> additionalFeeList) { for (FeeView fee : additionalFeeList) if (fee.getFeeId().equals(selectedFee.getFeeId())) return fee.isPeriodic(); return false; } private void validateCustomFields(HttpServletRequest request, ActionErrors errors) { try { List<CustomFieldDefinitionEntity> customFieldDefs = (List<CustomFieldDefinitionEntity>) SessionUtils .getAttribute(LoanConstants.CUSTOM_FIELDS, request); for (CustomFieldView customField : customFields) { boolean isErrorFound = false; for (CustomFieldDefinitionEntity customFieldDef : customFieldDefs) { if (customField.getFieldId().equals(customFieldDef.getFieldId()) && customFieldDef.isMandatory()) { if (StringUtils.isNullOrEmpty(customField.getFieldValue())) { errors.add(LoanConstants.CUSTOM_FIELDS, new ActionMessage( LoanConstants.ERRORS_SPECIFY_CUSTOM_FIELD_VALUE)); isErrorFound = true; break; } } } if (isErrorFound) break; } } catch (PageExpiredException pee) { errors.add(ExceptionConstants.PAGEEXPIREDEXCEPTION, new ActionMessage( ExceptionConstants.PAGEEXPIREDEXCEPTION)); } } void validateSelectedClients(ActionErrors errors) { List<String> selectedClients = new ArrayList(); for (String id : getClients()) { if (!StringUtils.isNullOrEmpty(id)) { selectedClients.add(id); } } if (selectedClients.size() < LoanConstants.MINIMUM_NUMBER_OF_CLIENTS_IN_GROUP_LOAN) { addError(errors, "", LoanExceptionConstants.NUMBER_OF_SELECTED_MEMBERS_IS_LESS_THAN_TWO, ""); } } void validateSumOfTheAmountsSpecified(ActionErrors errors) { List<String> ids_clients_selected = getClients(); double totalAmount = new Double(0); boolean foundInvalidAmount = false; for (LoanAccountDetailsViewHelper loanDetail : getClientDetails()) { if (!foundInvalidAmount) { if (ids_clients_selected.contains(loanDetail.getClientId())) { if (loanDetail.isAmountZeroOrNull()) { addError(errors, LoanExceptionConstants.CUSTOMER_LOAN_AMOUNT_FIELD); foundInvalidAmount = true; } else { totalAmount = totalAmount + loanDetail.getLoanAmount().doubleValue(); } } } } if (!foundInvalidAmount && (StringUtils.isNullOrEmpty(Double.valueOf(totalAmount).toString()) || !amountRange .isInRange(totalAmount))) { addError(errors, LoanConstants.LOANAMOUNT, LoanExceptionConstants.SUM_OF_INDIVIDUAL_AMOUNTS_IS_NOT_IN_THE_RANGE_OF_ALLOWED_AMOUNTS, getStringValue(amountRange.getMinLoanAmount()), getStringValue(amountRange.getMaxLoanAmount())); } } private void addError(ActionErrors errors, String errorCode) { errors.add(errorCode, new ActionMessage(errorCode)); } private void validateRepaymentDayRequired(HttpServletRequest request, ActionErrors errors) { try { // Default Short recurrenceId = RecurrenceType.WEEKLY.getValue(); if (null != this.getRecurrenceId()) { recurrenceId = new Short(this.getRecurrenceId()); } if (new ConfigurationPersistence().isRepaymentIndepOfMeetingEnabled()) { if (StringUtils.isNullOrEmpty(this.getFrequency())) { addError(errors, "", LoanExceptionConstants.REPAYMENTDAYISREQUIRED, ""); } else if (RecurrenceType.WEEKLY.getValue().equals(recurrenceId)) { if (StringUtils.isNullOrEmpty(this.getRecurWeek()) || StringUtils.isNullOrEmpty(this.getWeekDay())) { addError(errors, "", LoanExceptionConstants.REPAYMENTDAYISREQUIRED, ""); } } else { if (monthType.equals("1")) { if (StringUtils.isNullOrEmpty(this.getMonthDay()) || StringUtils.isNullOrEmpty(this.getDayRecurMonth())) { addError(errors, "", LoanExceptionConstants.REPAYMENTDAYISREQUIRED, ""); } } else { if (StringUtils.isNullOrEmpty(this.getMonthRank()) || StringUtils.isNullOrEmpty(this.getMonthWeek()) || StringUtils.isNullOrEmpty(this.getRecurMonth())) { addError(errors, "", LoanExceptionConstants.REPAYMENTDAYISREQUIRED, ""); } } } } } catch (PersistenceException e) { throw new IllegalStateException(e); } } private void validateIndividualLoanFieldsForGlim(HttpServletRequest request, ActionErrors errors) { for (LoanAccountDetailsViewHelper listDetail : clientDetails) { if (!listDetail.isEmpty()) { if (!getClients().contains(listDetail.getClientId())) { addError(errors, "", LoanExceptionConstants.LOAN_DETAILS_ENTERED_WITHOUT_SELECTING_INDIVIDUAL, ""); break; } } } } private List<FieldConfigurationEntity> getMandatoryFields(HttpServletRequest request) { Map<Short, List<FieldConfigurationEntity>> entityMandatoryFieldMap = (Map<Short, List<FieldConfigurationEntity>>) request .getSession().getServletContext().getAttribute(Constants.FIELD_CONFIGURATION); List<FieldConfigurationEntity> mandatoryfieldList = entityMandatoryFieldMap.get(EntityType.LOAN.getValue()); return mandatoryfieldList; } private boolean isPurposeOfLoanMandatory(List<FieldConfigurationEntity> mandatoryfieldList) { boolean isMandatory = false; for (FieldConfigurationEntity entity : mandatoryfieldList) { if (entity.getFieldName().equalsIgnoreCase(LoanConstants.PURPOSE_OF_LOAN)) { isMandatory = true; break; } } return isMandatory; } private void validateRedoLoanPayments(HttpServletRequest request, ActionErrors errors) { try { if (paymentDataBeans == null || paymentDataBeans.size() <= 0) return; CustomerBO customer = getCustomer(request); for (PaymentDataTemplate template : paymentDataBeans) { // No data for amount and transaction date, validation not // applicable if (template.getTotalAmount() == null || template.getTransactionDate() == null) continue; // Meeting date is invalid if (!customer.getCustomerMeeting().getMeeting().isValidMeetingDate(template.getTransactionDate(), DateUtils.getLastDayOfNextYear())) { errors.add(LoanExceptionConstants.INVALIDTRANSACTIONDATE, new ActionMessage( LoanExceptionConstants.INVALIDTRANSACTIONDATE)); continue; } // User has enter a payment for future date validateTransactionDate(errors, template, getDisbursementDateValue(getUserContext(request) .getPreferredLocale())); } } catch (InvalidDateException invalidDate) { errors.add(LoanExceptionConstants.INVALIDTRANSACTIONDATE, new ActionMessage( LoanExceptionConstants.INVALIDTRANSACTIONDATE)); } catch (MeetingException e) { errors.add(ExceptionConstants.FRAMEWORKRUNTIMEEXCEPTION, new ActionMessage( ExceptionConstants.FRAMEWORKRUNTIMEEXCEPTION)); } catch (PageExpiredException e) { errors.add(ExceptionConstants.PAGEEXPIREDEXCEPTION, new ActionMessage( ExceptionConstants.PAGEEXPIREDEXCEPTION)); } catch (ServiceException e) { errors.add(ExceptionConstants.FRAMEWORKRUNTIMEEXCEPTION, new ActionMessage( ExceptionConstants.FRAMEWORKRUNTIMEEXCEPTION)); } } void validateTransactionDate(ActionErrors errors, PaymentDataTemplate template, java.util.Date disbursementDate) { if (template.getTotalAmount() == null) return; try { if (!DateUtils.dateFallsOnOrBeforeDate(template.getTransactionDate(), DateUtils.currentDate())) { errors.add(LoanExceptionConstants.INVALIDTRANSACTIONDATEFORPAYMENT, new ActionMessage( LoanExceptionConstants.INVALIDTRANSACTIONDATEFORPAYMENT)); } else if (!DateUtils.dateFallsBeforeDate(disbursementDate, template.getTransactionDate())) { errors.add(LoanExceptionConstants.INVALIDTRANSACTIONDATE, new ActionMessage( LoanExceptionConstants.INVALIDTRANSACTIONDATE)); } } catch (InvalidDateException ide) { errors.add(LoanExceptionConstants.INVALIDTRANSACTIONDATEFORPAYMENT, new ActionMessage( LoanExceptionConstants.INVALIDTRANSACTIONDATEFORPAYMENT)); } } protected CustomerBO getCustomer(Integer customerId) throws ServiceException { return getCustomerBusinessService().getCustomer(customerId); } protected CustomerBusinessService getCustomerBusinessService() { return new CustomerBusinessService(); } private CustomerBO getCustomer(HttpServletRequest request) throws PageExpiredException, ServiceException { CustomerBO oldCustomer = (CustomerBO) SessionUtils.getAttribute(LoanConstants.LOANACCOUNTOWNER, request); Integer oldCustomerId; if (oldCustomer == null) { oldCustomerId = Integer.parseInt(getCustomerId()); } else { oldCustomerId = oldCustomer.getCustomerId(); } CustomerBO customer = getCustomer(oldCustomerId); customer.getPersonnel().getDisplayName(); customer.getOffice().getOfficeName(); // TODO: I'm not sure why we're resetting version number - need to // investigate this if (oldCustomer != null) { customer.setVersionNo(oldCustomer.getVersionNo()); } return customer; } public String getPerspective() { return perspective; } public void setPerspective(String perspective) { this.perspective = perspective; } public List<String> getClients() { return clients; } public void setClients(List<String> clients) { this.clients = clients; } public String getClients(int i) { while (i >= clients.size()) clients.add(""); return clients.get(i).toString(); } public void setClients(int i, String string) { while (this.clients.size() <= i) this.clients.add(new String()); this.clients.set(i, string); } public List<LoanAccountDetailsViewHelper> getClientDetails() { return clientDetails; } public void setClientDetails(List<LoanAccountDetailsViewHelper> clientDetails) { this.clientDetails = clientDetails; } public String getFirstRepaymentDay() { return firstRepaymentDay; } public void setFirstRepaymentDay(String firstRepaymentDay) { this.firstRepaymentDay = firstRepaymentDay; } public void setLoanAmountRange(AmountRange amountRange) { this.amountRange = amountRange; } public void setInstallmentRange(InstallmentRange installmentRange) { this.installmentRange = installmentRange; } public String getMinLoanAmount() { return getMinLoanAmountValue().toString(); } public Double getMinLoanAmountValue() { return amountRange.getMinLoanAmount(); } public String getMaxLoanAmount() { return getMaxLoanAmountValue().toString(); } public Double getMaxLoanAmountValue() { return amountRange.getMaxLoanAmount(); } public String getMinNoInstallments() { return getMinNoInstallmentsValue().toString(); } public Short getMinNoInstallmentsValue() { return installmentRange.getMinNoOfInstall(); } public String getMaxNoInstallments() { return getMaxNoInstallmentsValue().toString(); } public Short getMaxNoInstallmentsValue() { return installmentRange.getMaxNoOfInstall(); } public void removeClientDetailsWithNoMatchingClients() { List<LoanAccountDetailsViewHelper> clientDetailsCopy = new ArrayList<LoanAccountDetailsViewHelper>( clientDetails); CollectionUtils.filter(clientDetailsCopy, new RemoveEmptyClientDetailsForUncheckedClients(getClients())); clientDetails = new ArrayList<LoanAccountDetailsViewHelper>(clientDetailsCopy); } private static class RemoveEmptyClientDetailsForUncheckedClients implements Predicate { private final List<String> clients2; RemoveEmptyClientDetailsForUncheckedClients(List<String> clients) { clients2 = clients; } public boolean evaluate(Object object) { LoanAccountDetailsViewHelper loanDetail = ((LoanAccountDetailsViewHelper) object); return !(!clients2.contains(loanDetail.getClientId()) && (loanDetail.isEmpty())); } } }
application/src/main/java/org/mifos/application/accounts/loan/struts/actionforms/LoanAccountActionForm.java
/* * Copyright (c) 2005-2009 Grameen Foundation USA * All rights reserved. * * 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. * * See also http://www.apache.org/licenses/LICENSE-2.0.html for an * explanation of the license and how it is applied. */ package org.mifos.application.accounts.loan.struts.actionforms; import static org.apache.commons.lang.StringUtils.isBlank; import java.sql.Date; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; import javax.servlet.http.HttpServletRequest; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.Predicate; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.mifos.application.accounts.exceptions.AccountException; import org.mifos.application.accounts.loan.business.LoanBO; import org.mifos.application.accounts.loan.struts.uihelpers.PaymentDataHtmlBean; import org.mifos.application.accounts.loan.util.helpers.LoanAccountDetailsViewHelper; import org.mifos.application.accounts.loan.util.helpers.LoanConstants; import org.mifos.application.accounts.loan.util.helpers.LoanExceptionConstants; import org.mifos.application.accounts.loan.util.helpers.RepaymentScheduleInstallment; import org.mifos.application.accounts.util.helpers.AccountState; import org.mifos.application.accounts.util.helpers.PaymentDataTemplate; import org.mifos.application.configuration.business.service.ConfigurationBusinessService; import org.mifos.application.configuration.util.helpers.ConfigurationConstants; import org.mifos.application.customer.business.CustomerBO; import org.mifos.application.customer.business.service.CustomerBusinessService; import org.mifos.application.fees.business.FeeView; import org.mifos.application.master.business.CustomFieldDefinitionEntity; import org.mifos.application.master.business.CustomFieldView; import org.mifos.application.meeting.exceptions.MeetingException; import org.mifos.application.meeting.util.helpers.RecurrenceType; import org.mifos.application.personnel.business.PersonnelBO; import org.mifos.application.personnel.persistence.PersonnelPersistence; import org.mifos.application.productdefinition.business.AmountRange; import org.mifos.application.productdefinition.business.InstallmentRange; import org.mifos.application.productdefinition.business.LoanOfferingBO; import org.mifos.application.util.helpers.EntityType; import org.mifos.application.util.helpers.Methods; import org.mifos.application.util.helpers.YesNoFlag; import org.mifos.framework.components.configuration.persistence.ConfigurationPersistence; import org.mifos.framework.components.fieldConfiguration.business.FieldConfigurationEntity; import org.mifos.framework.exceptions.ApplicationException; import org.mifos.framework.exceptions.InvalidDateException; import org.mifos.framework.exceptions.PageExpiredException; import org.mifos.framework.exceptions.PersistenceException; import org.mifos.framework.exceptions.PropertyNotFoundException; import org.mifos.framework.exceptions.ServiceException; import org.mifos.framework.security.util.UserContext; import org.mifos.framework.struts.actionforms.BaseActionForm; import org.mifos.framework.util.helpers.Constants; import org.mifos.framework.util.helpers.DateUtils; import org.mifos.framework.util.helpers.ExceptionConstants; import org.mifos.framework.util.helpers.FilePaths; import org.mifos.framework.util.helpers.Money; import org.mifos.framework.util.helpers.SessionUtils; import org.mifos.framework.util.helpers.StringUtils; public class LoanAccountActionForm extends BaseActionForm { public LoanAccountActionForm() { super(); defaultFees = new ArrayList<FeeView>(); additionalFees = new ArrayList<FeeView>(); customFields = new ArrayList<CustomFieldView>(); clients = new ArrayList<String>(); clientDetails = new ArrayList<LoanAccountDetailsViewHelper>(); configService = new ConfigurationBusinessService(); } // For individual monitoring private List<String> clients; private List<LoanAccountDetailsViewHelper> clientDetails; private String perspective; private String accountId; private String globalAccountNum; private String prdOfferingName; private String accountName; private String accountTypeId; private String customerId; private String prdOfferingId; private String loanAmount; private String interestRate; private String noOfInstallments; private String disbursementDate; private String intDedDisbursement; private String loanOfferingFund; private String gracePeriodDuration; private String externalId; private String businessActivityId; private String collateralTypeId; private String collateralNote; private List<FeeView> defaultFees; private List<FeeView> additionalFees; private String stateSelected; private String gracePeriod; private List<CustomFieldView> customFields; private List<PaymentDataHtmlBean> paymentDataBeans = new ArrayList(); // For Repayment day private String monthRank; private String weekRank; private String monthWeek; private String monthType; private String monthDay; private String dayRecurMonth; private String weekDay; private String recurMonth; private String recurWeek; private String frequency; private String firstRepaymentDay; private String recurrenceId; private AmountRange amountRange; private InstallmentRange installmentRange; private String dayNumber; private ConfigurationBusinessService configService; public String getDayNumber() { return dayNumber; } public void setDayNumber(String dayNumber) { this.dayNumber = dayNumber; } public String getMonthRank() { return monthRank; } public void setMonthRank(String monthRank) { this.monthRank = monthRank; } public String getMonthWeek() { return monthWeek; } public void setMonthWeek(String monthWeek) { this.monthWeek = monthWeek; } public String getMonthType() { return monthType; } public void setMonthType(String monthType) { this.monthType = monthType; } public String getMonthDay() { return monthDay; } public void setMonthDay(String monthDay) { this.monthDay = monthDay; } public String getDayRecurMonth() { return dayRecurMonth; } public void setDayRecurMonth(String dayRecurMonth) { this.dayRecurMonth = dayRecurMonth; } public String getRecurMonth() { return recurMonth; } public void setRecurMonth(String recurMonth) { this.recurMonth = recurMonth; } public String getRecurWeek() { return recurWeek; } public void setRecurWeek(String recurWeek) { this.recurWeek = recurWeek; } public String getFrequency() { return frequency; } public void setFrequency(String frequency) { this.frequency = frequency; } public String getWeekDay() { return weekDay; } public void setWeekDay(String weekDay) { this.weekDay = weekDay; } public String getWeekRank() { return weekRank; } public void setWeekRank(String weekRank) { this.weekRank = weekRank; } public String getRecurrenceId() { return recurrenceId; } public void setRecurrenceId(String recurrenceId) { this.recurrenceId = recurrenceId; } public List<PaymentDataHtmlBean> getPaymentDataBeans() { return this.paymentDataBeans; } public String getGracePeriod() { return gracePeriod; } public void setGracePeriod(String gracePeriod) { this.gracePeriod = gracePeriod; } public String getExternalId() { return this.externalId; } public void setExternalId(String externalId) { this.externalId = externalId; } public String getAccountId() { return accountId; } public void setAccountId(String accountId) { this.accountId = accountId; } public String getAccountName() { return accountName; } public void setAccountName(String accountName) { this.accountName = accountName; } public String getAccountTypeId() { return accountTypeId; } public void setAccountTypeId(String accountTypeId) { this.accountTypeId = accountTypeId; } public String getCustomerId() { return customerId; } public void setCustomerId(String customerId) { this.customerId = customerId; } public String getGlobalAccountNum() { return globalAccountNum; } public void setGlobalAccountNum(String globalAccountNum) { this.globalAccountNum = globalAccountNum; } public String getPrdOfferingName() { return prdOfferingName; } public void setPrdOfferingName(String prdOfferingName) { this.prdOfferingName = prdOfferingName; } public String getPrdOfferingId() { return prdOfferingId; } public void setPrdOfferingId(String prdOfferingId) { this.prdOfferingId = prdOfferingId; } public String getBusinessActivityId() { return businessActivityId; } public void setBusinessActivityId(String businessActivityId) { this.businessActivityId = businessActivityId; } public String getCollateralNote() { return collateralNote; } public void setCollateralNote(String collateralNote) { this.collateralNote = collateralNote; } public String getCollateralTypeId() { return collateralTypeId; } public void setCollateralTypeId(String collateralTypeId) { this.collateralTypeId = collateralTypeId; } public String getDisbursementDate() { return disbursementDate; } public void setDisbursementDate(String disbursementDate) { this.disbursementDate = disbursementDate; } public String getGracePeriodDuration() { return gracePeriodDuration; } public void setGracePeriodDuration(String gracePeriodDuration) { this.gracePeriodDuration = gracePeriodDuration; } public String getIntDedDisbursement() { return intDedDisbursement; } public void setIntDedDisbursement(String intDedDisbursement) { this.intDedDisbursement = intDedDisbursement; } public String getInterestRate() { return interestRate; } public void setInterestRate(String interestRate) { this.interestRate = interestRate; } public String getLoanAmount() { return loanAmount; } public void setLoanAmount(String loanAmount) { this.loanAmount = loanAmount; } public String getLoanOfferingFund() { return loanOfferingFund; } public void setLoanOfferingFund(String loanOfferingFund) { this.loanOfferingFund = loanOfferingFund; } public String getNoOfInstallments() { return noOfInstallments; } public void setNoOfInstallments(String noOfInstallments) { this.noOfInstallments = noOfInstallments; } public List<CustomFieldView> getCustomFields() { return customFields; } public void setCustomFields(List<CustomFieldView> customFields) { this.customFields = customFields; } public CustomFieldView getCustomField(int i) { while (i >= customFields.size()) { customFields.add(new CustomFieldView()); } return customFields.get(i); } public List<FeeView> getAdditionalFees() { return additionalFees; } public void setAdditionalFees(List<FeeView> additionalFees) { this.additionalFees = additionalFees; } public List<FeeView> getDefaultFees() { return defaultFees; } public void setDefaultFees(List<FeeView> defaultFees) { this.defaultFees = defaultFees; } public String getStateSelected() { return stateSelected; } public void setStateSelected(String stateSelected) { this.stateSelected = stateSelected; } public AccountState getState() throws PropertyNotFoundException { return AccountState.fromShort(getShortValue(getStateSelected())); } public Integer getCustomerIdValue() { return getIntegerValue(getCustomerId()); } public Short getPrdOfferingIdValue() { return getShortValue(getPrdOfferingId()); } public Short getGracePeriodDurationValue() { return getShortValue(getGracePeriodDuration()); } public Money loanAmountValue() { return getMoney(getLoanAmount()); } public Short getNoOfInstallmentsValue() { return getShortValue(getNoOfInstallments()); } public Date getDisbursementDateValue(Locale locale) throws InvalidDateException { return DateUtils.getLocaleDate(locale, getDisbursementDate()); } public Date getFirstRepaymentDayValue(Locale locale) throws InvalidDateException { return DateUtils.getLocaleDate(locale, getFirstRepaymentDay()); } public boolean isInterestDedAtDisbValue() { return getBooleanValue(getIntDedDisbursement()); } public Double getInterestDoubleValue() { return getDoubleValue(getInterestRate()); } public Short getLoanOfferingFundValue() { return getShortValue(getLoanOfferingFund()); } public Integer getBusinessActivityIdValue() { return getIntegerValue(getBusinessActivityId()); } public Integer getCollateralTypeIdValue() { return getIntegerValue(getCollateralTypeId()); } public Money getLoanAmountValue() { return getMoney(loanAmount); } public Double getInterestRateValue() { return getDoubleValue(interestRate); } public FeeView getDefaultFee(int i) { while (i >= defaultFees.size()) { defaultFees.add(new FeeView()); } return defaultFees.get(i); } public Boolean isInterestDeductedAtDisbursment() { if (getIntDedDisbursement().equals("1")) return true; return false; } public void initializeTransactionFields(UserContext userContext, List<RepaymentScheduleInstallment> installments) { this.paymentDataBeans = new ArrayList(installments.size()); PersonnelBO personnel; try { personnel = new PersonnelPersistence().getPersonnel(userContext.getId()); } catch (PersistenceException e) { throw new IllegalArgumentException("bad UserContext id"); } for (Iterator<RepaymentScheduleInstallment> iter = installments.iterator(); iter.hasNext();) { this.paymentDataBeans .add(new PaymentDataHtmlBean(userContext.getPreferredLocale(), personnel, iter.next())); } } public List<FeeView> getFeesToApply() { List<FeeView> feesToApply = new ArrayList<FeeView>(); for (FeeView fee : getAdditionalFees()) if (fee.getFeeIdValue() != null) feesToApply.add(fee); for (FeeView fee : getDefaultFees()) if (!fee.isRemoved()) feesToApply.add(fee); return feesToApply; } public FeeView getSelectedFee(int index) { while (index >= additionalFees.size()) additionalFees.add(new FeeView()); return additionalFees.get(index); } @Override public void reset(ActionMapping mapping, HttpServletRequest request) { super.reset(mapping, request); String method = request.getParameter(Methods.method.toString()); if (method.equals(Methods.schedulePreview.toString())) { intDedDisbursement = null; for (int i = 0; i < defaultFees.size(); i++) { // if an already checked fee is unchecked then the value set to // 0 if (request.getParameter("defaultFee[" + i + "].feeRemoved") == null) { defaultFees.get(i).setFeeRemoved(YesNoFlag.NO.getValue()); } } } else if (method.equals(Methods.load.toString())) { clients = new ArrayList<String>(); } else if (method.equals(Methods.managePreview.toString())) { intDedDisbursement = "0"; } } @Override public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { String method = request.getParameter(Methods.method.toString()); ActionErrors errors = new ActionErrors(); UserContext userContext = getUserContext(request); if (null == request.getAttribute(Constants.CURRENTFLOWKEY)) request.setAttribute(Constants.CURRENTFLOWKEY, request.getParameter(Constants.CURRENTFLOWKEY)); try { if (method.equals(Methods.getPrdOfferings.toString())) checkValidationForGetPrdOfferings(errors, userContext); else if (method.equals(Methods.load.toString())) checkValidationForLoad(errors, userContext); else if (method.equals(Methods.schedulePreview.toString())) checkValidationForSchedulePreview(errors, request); else if (method.equals(Methods.managePreview.toString())) checkValidationForManagePreview(errors, request); else if (method.equals(Methods.preview.toString())) checkValidationForPreview(errors, request); } catch (ApplicationException ae) { // Discard other errors (is that right?) ae.printStackTrace(); errors = new ActionErrors(); errors.add(ae.getKey(), new ActionMessage(ae.getKey(), ae.getValues())); } if (!errors.isEmpty()) { request.setAttribute(LoanConstants.METHODCALLED, method); } return errors; } // TODO: use localized strings for error messages rather than hardcoded private void checkValidationForGetPrdOfferings(ActionErrors errors, UserContext userContext) { if (StringUtils.isNullOrEmpty(getCustomerId())) { addError(errors, LoanConstants.CUSTOMER, LoanConstants.CUSTOMERNOTSELECTEDERROR, getLabel( ConfigurationConstants.CLIENT, userContext), getLabel(ConfigurationConstants.GROUP, userContext)); } } // TODO: use localized strings for error messages rather than hardcoded private void checkValidationForLoad(ActionErrors errors, UserContext userContext) { checkValidationForGetPrdOfferings(errors, userContext); if (StringUtils.isNullOrEmpty(getPrdOfferingId())) { Locale locale = userContext.getCurrentLocale(); ResourceBundle resources = ResourceBundle.getBundle(FilePaths.LOAN_UI_RESOURCE_PROPERTYFILE, locale); String instanceName = resources.getString("loan.instanceName"); addError(errors, LoanConstants.PRDOFFERINGID, LoanConstants.LOANOFFERINGNOTSELECTEDERROR, getLabel( ConfigurationConstants.LOAN, userContext), instanceName); } } private void checkValidationForSchedulePreview(ActionErrors errors, HttpServletRequest request) throws ApplicationException { checkValidationForPreviewBefore(errors, request); validateFees(request, errors); validateCustomFields(request, errors); performGlimSpecificValidations(errors, request); validateRepaymentDayRequired(request, errors); validatePurposeOfLoanFields(errors, getMandatoryFields(request)); } private void performGlimSpecificValidations(ActionErrors errors, HttpServletRequest request) throws PageExpiredException, ServiceException { if (configService.isGlimEnabled() && getCustomer(request).isGroup()) { removeClientsNotCheckedInForm(request); validateIndividualLoanFieldsForGlim(request, errors); validateSelectedClients(errors); validateSumOfTheAmountsSpecified(errors); validatePurposeOfLoanForGlim(errors); } } // Since this Struts form is set up as "session" scope, we need to clear // the form fields in cases where they are used across pages. // Currently we do that in the following case: When old values of clientId // are // retained from the account creation page, form validation // on submission from the Edit Account Information page is messed up. // Calling // this method fixes that problem private void removeClientsNotCheckedInForm(HttpServletRequest request) { List<String> clientIds = getSelectedClientIdsFromRequest(request); setClientsNotPresentInInputToEmptyString(clientIds); } void setClientsNotPresentInInputToEmptyString(List<String> clientIds) { for (int i = 0; i < clients.size(); i++) { if (!clientIds.contains(clients.get(i))) { clients.set(i, ""); } } } List<String> getSelectedClientIdsFromRequest(HttpServletRequest request) { Collection paramsStartingWithClients = CollectionUtils.select(convertEnumerationToList(request .getParameterNames()), new Predicate() { public boolean evaluate(Object object) { return ((String) object).startsWith("clients"); } }); List<String> indices = extractClientIdsFromRequest(request, paramsStartingWithClients); return indices; } private List<String> extractClientIdsFromRequest(HttpServletRequest request, Collection paramsStartingWithClients) { List<String> clientIds = new ArrayList<String>(); for (Iterator iter = paramsStartingWithClients.iterator(); iter.hasNext();) { String element = (String) iter.next(); clientIds.add(request.getParameter(element)); } return clientIds; } private List<String> convertEnumerationToList(Enumeration parameterNames) { List<String> params = new ArrayList<String>(); while (parameterNames.hasMoreElements()) { params.add((String) parameterNames.nextElement()); } return params; } void validatePurposeOfLoanForGlim(ActionErrors errors) { List<String> ids_clients_selected = getClients(); List<LoanAccountDetailsViewHelper> listdetail = getClientDetails(); for (LoanAccountDetailsViewHelper loanAccount : listdetail) { if (ids_clients_selected.contains(loanAccount.getClientId())) { if (StringUtils.isNullOrEmpty(loanAccount.getBusinessActivity())) { addErrorInvalidPurpose(errors); return; } } } } private void addErrorInvalidPurpose(ActionErrors errors) { addError(errors, LoanExceptionConstants.CUSTOMER_PURPOSE_OF_LOAN_FIELD); } private void validatePurposeOfLoanFields(ActionErrors errors, List<FieldConfigurationEntity> mandatoryFields) { if (isPurposeOfLoanMandatory(mandatoryFields) && StringUtils.isNullOrEmpty(getBusinessActivityId())) { addErrorInvalidPurpose(errors); } } private void checkValidationForPreview(ActionErrors errors, HttpServletRequest request) throws ApplicationException { validateRedoLoanPayments(request, errors); } private void checkValidationForManagePreview(ActionErrors errors, HttpServletRequest request) throws ApplicationException { if (getState().equals(AccountState.LOAN_PARTIAL_APPLICATION) || getState().equals(AccountState.LOAN_PENDING_APPROVAL)) checkValidationForPreview(errors, request); performGlimSpecificValidations(errors, request); validateCustomFields(request, errors); validateRepaymentDayRequired(request, errors); try { validateDisbursementDate(errors, getCustomer(request), getDisbursementDateValue(getUserContext(request) .getPreferredLocale())); } catch (InvalidDateException dateException) { addError(errors, LoanExceptionConstants.ERROR_INVALIDDISBURSEMENTDATE); } } private void validateDisbursementDate(ActionErrors errors, CustomerBO customer, java.sql.Date disbursementDateValue) throws AccountException, ServiceException { if (!configService.isRepaymentIndepOfMeetingEnabled() && !LoanBO.isDisbursementDateValid(customer, disbursementDateValue)) { addError(errors, LoanExceptionConstants.INVALIDDISBURSEMENTDATE); } } private void checkValidationForPreviewBefore(ActionErrors errors, HttpServletRequest request) throws ApplicationException { Locale locale = getUserContext(request).getPreferredLocale(); ResourceBundle resources = ResourceBundle.getBundle(FilePaths.LOAN_UI_RESOURCE_PROPERTYFILE, locale); LoanOfferingBO loanOffering = (LoanOfferingBO) SessionUtils.getAttribute(LoanConstants.LOANOFFERING, request); if (!new ConfigurationBusinessService().isGlimEnabled()) { checkForMinMax(errors, loanAmount, amountRange, resources.getString("loan.amount")); } checkForMinMax(errors, interestRate, loanOffering.getMaxInterestRate(), loanOffering.getMinInterestRate(), resources.getString("loan.noOfInstallments")); checkForMinMax(errors, noOfInstallments, installmentRange, resources.getString("loan.noOfInstallments")); if (StringUtils.isNullOrEmpty(getDisbursementDate())) { addError(errors, "Proposed/Actual disbursal date", "errors.validandmandatory", resources .getString("loan.disbursalDate")); } if (isInterestDedAtDisbValue()) { setGracePeriodDuration("0"); } if (((!isInterestDedAtDisbValue()) && StringUtils.isNullOrEmpty(getGracePeriodDuration())) || (getDoubleValue(getGracePeriodDuration()) != null && getDoubleValue(getNoOfInstallments()) != null && getDoubleValue(getGracePeriodDuration()) >= getDoubleValue(getNoOfInstallments()))) { String gracePeriodForRepayments = resources.getString("loan.gracePeriodForRepayments"); String noInst = StringUtils.isNullOrEmpty(getNoOfInstallments()) ? getStringValue(installmentRange .getMaxNoOfInstall()) : getNoOfInstallments(); addError(errors, LoanConstants.GRACEPERIODDURATION, LoanConstants.GRACEPERIODERROR, gracePeriodForRepayments, noInst); } } void checkForMinMax(ActionErrors errors, String currentValue, AmountRange amountRange, String field) { if (isBlank(currentValue) || !amountRange.isInRange(getDoubleValue(currentValue))) { addError(errors, field, LoanExceptionConstants.INVALIDMINMAX, field, getStringValue(amountRange .getMinLoanAmount()), getStringValue(amountRange.getMaxLoanAmount())); } } void checkForMinMax(ActionErrors errors, String currentValue, InstallmentRange installmentRange, String field) { if (StringUtils.isNullOrEmpty(currentValue) || !installmentRange.isInRange(getShortValue(currentValue))) { addError(errors, field, LoanExceptionConstants.INVALIDMINMAX, field, getStringValue(installmentRange .getMinNoOfInstall()), getStringValue(installmentRange.getMaxNoOfInstall())); } } private void checkForMinMax(ActionErrors errors, String currentValue, Double maxValue, Double minValue, String field) { if (StringUtils.isNullOrEmpty(currentValue) || getDoubleValue(currentValue).doubleValue() > maxValue.doubleValue() || getDoubleValue(currentValue).doubleValue() < minValue.doubleValue()) { addError(errors, field, LoanExceptionConstants.INVALIDMINMAX, field, getStringValue(minValue), getStringValue(maxValue)); } } protected void validateFees(HttpServletRequest request, ActionErrors errors) throws ApplicationException { validateForFeeAmount(errors); validateForDuplicatePeriodicFee(request, errors); } protected void validateForFeeAmount(ActionErrors errors) { List<FeeView> feeList = getFeesToApply(); for (FeeView fee : feeList) { if (StringUtils.isNullOrEmpty(fee.getAmount())) errors.add(LoanConstants.FEE, new ActionMessage(LoanConstants.ERRORS_SPECIFY_FEE_AMOUNT)); } } protected void validateForDuplicatePeriodicFee(HttpServletRequest request, ActionErrors errors) throws ApplicationException { List<FeeView> additionalFeeList = (List<FeeView>) SessionUtils.getAttribute(LoanConstants.ADDITIONAL_FEES_LIST, request); for (FeeView selectedFee : getAdditionalFees()) { int count = 0; for (FeeView duplicateSelectedfee : getAdditionalFees()) { if (selectedFee.getFeeIdValue() != null && selectedFee.getFeeId().equals(duplicateSelectedfee.getFeeId())) { if (isSelectedFeePeriodic(selectedFee, additionalFeeList)) count++; } } if (count > 1) { errors.add(LoanConstants.FEE, new ActionMessage(LoanConstants.ERRORS_DUPLICATE_PERIODIC_FEE)); break; } } } private boolean isSelectedFeePeriodic(FeeView selectedFee, List<FeeView> additionalFeeList) { for (FeeView fee : additionalFeeList) if (fee.getFeeId().equals(selectedFee.getFeeId())) return fee.isPeriodic(); return false; } private void validateCustomFields(HttpServletRequest request, ActionErrors errors) { try { List<CustomFieldDefinitionEntity> customFieldDefs = (List<CustomFieldDefinitionEntity>) SessionUtils .getAttribute(LoanConstants.CUSTOM_FIELDS, request); for (CustomFieldView customField : customFields) { boolean isErrorFound = false; for (CustomFieldDefinitionEntity customFieldDef : customFieldDefs) { if (customField.getFieldId().equals(customFieldDef.getFieldId()) && customFieldDef.isMandatory()) { if (StringUtils.isNullOrEmpty(customField.getFieldValue())) { errors.add(LoanConstants.CUSTOM_FIELDS, new ActionMessage( LoanConstants.ERRORS_SPECIFY_CUSTOM_FIELD_VALUE)); isErrorFound = true; break; } } } if (isErrorFound) break; } } catch (PageExpiredException pee) { errors.add(ExceptionConstants.PAGEEXPIREDEXCEPTION, new ActionMessage( ExceptionConstants.PAGEEXPIREDEXCEPTION)); } } void validateSelectedClients(ActionErrors errors) { List<String> selectedClients = new ArrayList(); for (String id : getClients()) { if (!StringUtils.isNullOrEmpty(id)) { selectedClients.add(id); } } if (selectedClients.size() < LoanConstants.MINIMUM_NUMBER_OF_CLIENTS_IN_GROUP_LOAN) { addError(errors, "", LoanExceptionConstants.NUMBER_OF_SELECTED_MEMBERS_IS_LESS_THAN_TWO, ""); } } void validateSumOfTheAmountsSpecified(ActionErrors errors) { List<String> ids_clients_selected = getClients(); double totalAmount = new Double(0); boolean foundInvalidAmount = false; for (LoanAccountDetailsViewHelper loanDetail : getClientDetails()) { if (!foundInvalidAmount) { if (ids_clients_selected.contains(loanDetail.getClientId())) { if (loanDetail.isAmountZeroOrNull()) { addError(errors, LoanExceptionConstants.CUSTOMER_LOAN_AMOUNT_FIELD); foundInvalidAmount = true; } else { totalAmount = totalAmount + loanDetail.getLoanAmount().doubleValue(); } } } } if (!foundInvalidAmount && (StringUtils.isNullOrEmpty(Double.valueOf(totalAmount).toString()) || !amountRange .isInRange(totalAmount))) { addError(errors, LoanConstants.LOANAMOUNT, LoanExceptionConstants.SUM_OF_INDIVIDUAL_AMOUNTS_IS_NOT_IN_THE_RANGE_OF_ALLOWED_AMOUNTS, getStringValue(amountRange.getMinLoanAmount()), getStringValue(amountRange.getMaxLoanAmount())); } } private void addError(ActionErrors errors, String errorCode) { errors.add(errorCode, new ActionMessage(errorCode)); } private void validateRepaymentDayRequired(HttpServletRequest request, ActionErrors errors) { try { // Default Short recurrenceId = RecurrenceType.WEEKLY.getValue(); if (null != this.getRecurrenceId()) { recurrenceId = new Short(this.getRecurrenceId()); } if (new ConfigurationPersistence().isRepaymentIndepOfMeetingEnabled()) { if (StringUtils.isNullOrEmpty(this.getFrequency())) { addError(errors, "", LoanExceptionConstants.REPAYMENTDAYISREQUIRED, ""); } else if (RecurrenceType.WEEKLY.getValue().equals(recurrenceId)) { if (StringUtils.isNullOrEmpty(this.getRecurWeek()) || StringUtils.isNullOrEmpty(this.getWeekDay())) { addError(errors, "", LoanExceptionConstants.REPAYMENTDAYISREQUIRED, ""); } } else { if (monthType.equals("1")) { if (StringUtils.isNullOrEmpty(this.getMonthDay()) || StringUtils.isNullOrEmpty(this.getDayRecurMonth())) { addError(errors, "", LoanExceptionConstants.REPAYMENTDAYISREQUIRED, ""); } } else { if (StringUtils.isNullOrEmpty(this.getMonthRank()) || StringUtils.isNullOrEmpty(this.getMonthWeek()) || StringUtils.isNullOrEmpty(this.getRecurMonth())) { addError(errors, "", LoanExceptionConstants.REPAYMENTDAYISREQUIRED, ""); } } } } } catch (PersistenceException e) { throw new IllegalStateException(e); } } private void validateIndividualLoanFieldsForGlim(HttpServletRequest request, ActionErrors errors) { for (LoanAccountDetailsViewHelper listDetail : clientDetails) { if (!listDetail.isEmpty()) { if (!getClients().contains(listDetail.getClientId())) { addError(errors, "", LoanExceptionConstants.LOAN_DETAILS_ENTERED_WITHOUT_SELECTING_INDIVIDUAL, ""); break; } } } } private List<FieldConfigurationEntity> getMandatoryFields(HttpServletRequest request) { Map<Short, List<FieldConfigurationEntity>> entityMandatoryFieldMap = (Map<Short, List<FieldConfigurationEntity>>) request .getSession().getServletContext().getAttribute(Constants.FIELD_CONFIGURATION); List<FieldConfigurationEntity> mandatoryfieldList = entityMandatoryFieldMap.get(EntityType.LOAN.getValue()); return mandatoryfieldList; } private boolean isPurposeOfLoanMandatory(List<FieldConfigurationEntity> mandatoryfieldList) { boolean isMandatory = false; for (FieldConfigurationEntity entity : mandatoryfieldList) { if (entity.getFieldName().equalsIgnoreCase(LoanConstants.PURPOSE_OF_LOAN)) { isMandatory = true; break; } } return isMandatory; } private void validateRedoLoanPayments(HttpServletRequest request, ActionErrors errors) { try { if (paymentDataBeans == null || paymentDataBeans.size() <= 0) return; CustomerBO customer = getCustomer(request); for (PaymentDataTemplate template : paymentDataBeans) { // No data for amount and transaction date, validation not // applicable if (template.getTotalAmount() == null || template.getTransactionDate() == null) continue; // Meeting date is invalid if (!customer.getCustomerMeeting().getMeeting().isValidMeetingDate(template.getTransactionDate(), DateUtils.getLastDayOfNextYear())) { errors.add(LoanExceptionConstants.INVALIDTRANSACTIONDATE, new ActionMessage( LoanExceptionConstants.INVALIDTRANSACTIONDATE)); continue; } // User has enter a payment for future date validateTransactionDate(errors, template, getDisbursementDateValue(getUserContext(request) .getPreferredLocale())); } } catch (InvalidDateException invalidDate) { errors.add(LoanExceptionConstants.INVALIDTRANSACTIONDATE, new ActionMessage( LoanExceptionConstants.INVALIDTRANSACTIONDATE)); } catch (MeetingException e) { errors.add(ExceptionConstants.FRAMEWORKRUNTIMEEXCEPTION, new ActionMessage( ExceptionConstants.FRAMEWORKRUNTIMEEXCEPTION)); } catch (PageExpiredException e) { errors.add(ExceptionConstants.PAGEEXPIREDEXCEPTION, new ActionMessage( ExceptionConstants.PAGEEXPIREDEXCEPTION)); } catch (ServiceException e) { errors.add(ExceptionConstants.FRAMEWORKRUNTIMEEXCEPTION, new ActionMessage( ExceptionConstants.FRAMEWORKRUNTIMEEXCEPTION)); } } void validateTransactionDate(ActionErrors errors, PaymentDataTemplate template, java.util.Date disbursementDate) { if (template.getTotalAmount() == null) return; try { if (!DateUtils.dateFallsOnOrBeforeDate(template.getTransactionDate(), DateUtils.currentDate())) { errors.add(LoanExceptionConstants.INVALIDTRANSACTIONDATEFORPAYMENT, new ActionMessage( LoanExceptionConstants.INVALIDTRANSACTIONDATEFORPAYMENT)); } else if (!DateUtils.dateFallsBeforeDate(disbursementDate, template.getTransactionDate())) { errors.add(LoanExceptionConstants.INVALIDTRANSACTIONDATE, new ActionMessage( LoanExceptionConstants.INVALIDTRANSACTIONDATE)); } } catch (InvalidDateException ide) { errors.add(LoanExceptionConstants.INVALIDTRANSACTIONDATEFORPAYMENT, new ActionMessage( LoanExceptionConstants.INVALIDTRANSACTIONDATEFORPAYMENT)); } } protected CustomerBO getCustomer(Integer customerId) throws ServiceException { return getCustomerBusinessService().getCustomer(customerId); } protected CustomerBusinessService getCustomerBusinessService() { return new CustomerBusinessService(); } private CustomerBO getCustomer(HttpServletRequest request) throws PageExpiredException, ServiceException { CustomerBO oldCustomer = (CustomerBO) SessionUtils.getAttribute(LoanConstants.LOANACCOUNTOWNER, request); Integer oldCustomerId; if (oldCustomer == null) { oldCustomerId = Integer.parseInt(getCustomerId()); } else { oldCustomerId = oldCustomer.getCustomerId(); } CustomerBO customer = getCustomer(oldCustomerId); customer.getPersonnel().getDisplayName(); customer.getOffice().getOfficeName(); // TODO: I'm not sure why we're resetting version number - need to // investigate this if (oldCustomer != null) { customer.setVersionNo(oldCustomer.getVersionNo()); } return customer; } public String getPerspective() { return perspective; } public void setPerspective(String perspective) { this.perspective = perspective; } public List<String> getClients() { return clients; } public void setClients(List<String> clients) { this.clients = clients; } public String getClients(int i) { while (i >= clients.size()) clients.add(""); return clients.get(i).toString(); } public void setClients(int i, String string) { while (this.clients.size() <= i) this.clients.add(new String()); this.clients.set(i, string); } public List<LoanAccountDetailsViewHelper> getClientDetails() { return clientDetails; } public void setClientDetails(List<LoanAccountDetailsViewHelper> clientDetails) { this.clientDetails = clientDetails; } public String getFirstRepaymentDay() { return firstRepaymentDay; } public void setFirstRepaymentDay(String firstRepaymentDay) { this.firstRepaymentDay = firstRepaymentDay; } public void setLoanAmountRange(AmountRange amountRange) { this.amountRange = amountRange; } public void setInstallmentRange(InstallmentRange installmentRange) { this.installmentRange = installmentRange; } public String getMinLoanAmount() { return getMinLoanAmountValue().toString(); } public Double getMinLoanAmountValue() { return amountRange.getMinLoanAmount(); } public String getMaxLoanAmount() { return getMaxLoanAmountValue().toString(); } public Double getMaxLoanAmountValue() { return amountRange.getMaxLoanAmount(); } public String getMinNoInstallments() { return getMinNoInstallmentsValue().toString(); } public Short getMinNoInstallmentsValue() { return installmentRange.getMinNoOfInstall(); } public String getMaxNoInstallments() { return getMaxNoInstallmentsValue().toString(); } public Short getMaxNoInstallmentsValue() { return installmentRange.getMaxNoOfInstall(); } public void removeClientDetailsWithNoMatchingClients() { List<LoanAccountDetailsViewHelper> clientDetailsCopy = new ArrayList<LoanAccountDetailsViewHelper>( clientDetails); CollectionUtils.filter(clientDetailsCopy, new RemoveEmptyClientDetailsForUncheckedClients(getClients())); clientDetails = new ArrayList<LoanAccountDetailsViewHelper>(clientDetailsCopy); } private static class RemoveEmptyClientDetailsForUncheckedClients implements Predicate { private final List<String> clients2; RemoveEmptyClientDetailsForUncheckedClients(List<String> clients) { clients2 = clients; } public boolean evaluate(Object object) { LoanAccountDetailsViewHelper loanDetail = ((LoanAccountDetailsViewHelper) object); return !(!clients2.contains(loanDetail.getClientId()) && (loanDetail.isEmpty())); } } }
Work on story 2258, issue 2123 - Edit of active loan produces invalid Disbursement date message. * made disbursement date check conditional. git-svn-id: 6bd94cac40bd5c1df74b384d972046d926de6ffa@16131 a8845c50-7012-0410-95d3-8e1449b9b1e4
application/src/main/java/org/mifos/application/accounts/loan/struts/actionforms/LoanAccountActionForm.java
Work on story 2258, issue 2123 - Edit of active loan produces invalid Disbursement date message. * made disbursement date check conditional.
<ide><path>pplication/src/main/java/org/mifos/application/accounts/loan/struts/actionforms/LoanAccountActionForm.java <ide> private void checkValidationForManagePreview(ActionErrors errors, HttpServletRequest request) <ide> throws ApplicationException { <ide> if (getState().equals(AccountState.LOAN_PARTIAL_APPLICATION) <del> || getState().equals(AccountState.LOAN_PENDING_APPROVAL)) <add> || getState().equals(AccountState.LOAN_PENDING_APPROVAL)) { <ide> checkValidationForPreview(errors, request); <add> // Only validate the disbursement date before a loan has been approved. After <add> // approval, it cannot be edited. <add> try { <add> validateDisbursementDate(errors, getCustomer(request), getDisbursementDateValue(getUserContext(request) <add> .getPreferredLocale())); <add> } catch (InvalidDateException dateException) { <add> addError(errors, LoanExceptionConstants.ERROR_INVALIDDISBURSEMENTDATE); <add> } <add> } <ide> performGlimSpecificValidations(errors, request); <ide> validateCustomFields(request, errors); <del> validateRepaymentDayRequired(request, errors); <del> try { <del> validateDisbursementDate(errors, getCustomer(request), getDisbursementDateValue(getUserContext(request) <del> .getPreferredLocale())); <del> } catch (InvalidDateException dateException) { <del> addError(errors, LoanExceptionConstants.ERROR_INVALIDDISBURSEMENTDATE); <del> } <add> validateRepaymentDayRequired(request, errors); <ide> } <ide> <ide> private void validateDisbursementDate(ActionErrors errors, CustomerBO customer, java.sql.Date disbursementDateValue)
Java
mit
7bbc07cdf8be3ec7b866caedbfa02b1faa85e8d0
0
pawellinkshell/Supermarket,pawellinkshell/Supermarket
package pl.koszela.jan.domain; import java.util.Objects; /** * Created on 12.08.2017. * * @author Jan Koszela */ public class Order { private String productName; private int quantity; public Order(String productName, int quantity) { this.productName = productName; this.quantity = quantity; } public String getProductName() { return this.productName; } public int getQuantity() { return this.quantity; } public void setProductName(String productName) { this.productName = productName; } public void setQuantity(int quantity) { this.quantity = quantity; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Order order = (Order) o; return Objects.equals(productName, order.productName); } @Override public int hashCode() { return Objects.hash(productName, quantity); } }
src/main/java/pl/koszela/jan/domain/Order.java
package pl.koszela.jan.domain; /** * Created on 12.08.2017. * * @author Jan Koszela */ public class Order { private String productName; private String quantity; @java.beans.ConstructorProperties({"productName", "quantity"}) Order(String productName, String quantity) { this.productName = productName; this.quantity = quantity; } public static OrderBuilder builder() { return new OrderBuilder(); } public String getProductName() { return this.productName; } public String getQuantity() { return this.quantity; } public void setProductName(String productName) { this.productName = productName; } public void setQuantity(String quantity) { this.quantity = quantity; } public static class OrderBuilder { private String productName; private String quantity; OrderBuilder() { } public Order.OrderBuilder productName(String productName) { this.productName = productName; return this; } public Order.OrderBuilder quantity(String quantity) { this.quantity = quantity; return this; } public Order build() { return new Order(productName, quantity); } public String toString() { return "pl.koszela.jan.domain.Order.OrderBuilder(productName=" + this.productName + ", quantity=" + this.quantity + ")"; } } }
Remove builder pattern
src/main/java/pl/koszela/jan/domain/Order.java
Remove builder pattern
<ide><path>rc/main/java/pl/koszela/jan/domain/Order.java <ide> package pl.koszela.jan.domain; <add> <add>import java.util.Objects; <ide> <ide> /** <ide> * Created on 12.08.2017. <ide> public class Order { <ide> <ide> private String productName; <del> private String quantity; <add> private int quantity; <ide> <del> @java.beans.ConstructorProperties({"productName", "quantity"}) <del> Order(String productName, String quantity) { <add> public Order(String productName, int quantity) { <ide> this.productName = productName; <ide> this.quantity = quantity; <ide> } <ide> <del> public static OrderBuilder builder() { <del> return new OrderBuilder(); <del> } <ide> <ide> public String getProductName() { <ide> return this.productName; <ide> } <ide> <del> public String getQuantity() { <add> public int getQuantity() { <ide> return this.quantity; <ide> } <ide> <ide> this.productName = productName; <ide> } <ide> <del> public void setQuantity(String quantity) { <add> public void setQuantity(int quantity) { <ide> this.quantity = quantity; <ide> } <ide> <del> public static class OrderBuilder { <add> @Override <add> public boolean equals(Object o) { <add> if (this == o) { <add> return true; <add> } <add> if (o == null || getClass() != o.getClass()) { <add> return false; <add> } <add> Order order = (Order) o; <add> return Objects.equals(productName, order.productName); <add> } <ide> <del> private String productName; <del> private String quantity; <del> <del> OrderBuilder() { <del> } <del> <del> public Order.OrderBuilder productName(String productName) { <del> this.productName = productName; <del> return this; <del> } <del> <del> public Order.OrderBuilder quantity(String quantity) { <del> this.quantity = quantity; <del> return this; <del> } <del> <del> public Order build() { <del> return new Order(productName, quantity); <del> } <del> <del> public String toString() { <del> return "pl.koszela.jan.domain.Order.OrderBuilder(productName=" + this.productName <del> + ", quantity=" + this.quantity + ")"; <del> } <add> @Override <add> public int hashCode() { <add> return Objects.hash(productName, quantity); <ide> } <ide> }
Java
apache-2.0
d2a202f1448ff4b91e768f8752388ee1de9bbcdf
0
yeeunshim/tajo_test,hyunsik/incubator-tajo,gruter/tajo-cdh,hyunsik/incubator-tajo,yeeunshim/tajo_test,gruter/tajo-cdh,yeeunshim/tajo_test,apache/incubator-tajo,apache/incubator-tajo,apache/incubator-tajo,hyunsik/incubator-tajo,hyunsik/incubator-tajo,gruter/tajo-cdh,yeeunshim/tajo_test,gruter/tajo-cdh,apache/incubator-tajo
package nta.engine.planner.physical; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import nta.catalog.CatalogService; import nta.catalog.Schema; import nta.catalog.TCatUtil; import nta.catalog.TableDesc; import nta.catalog.TableMeta; import nta.catalog.proto.CatalogProtos.DataType; import nta.catalog.proto.CatalogProtos.StoreType; import nta.datum.Datum; import nta.datum.DatumFactory; import nta.engine.NtaTestingUtility; import nta.engine.QueryIdFactory; import nta.engine.SubqueryContext; import nta.engine.ipc.protocolrecords.Fragment; import nta.engine.parser.QueryAnalyzer; import nta.engine.parser.QueryBlock; import nta.engine.planner.LogicalPlanner; import nta.engine.planner.PhysicalPlanner; import nta.engine.planner.logical.LogicalNode; import nta.engine.utils.TUtil; import nta.storage.Appender; import nta.storage.StorageManager; import nta.storage.Tuple; import nta.storage.VTuple; import org.apache.hadoop.conf.Configuration; import org.junit.After; import org.junit.Before; import org.junit.Test; public class TestHashJoinExec { private Configuration conf; private final String TEST_PATH = "target/test-data/TestHashJoinExec"; private NtaTestingUtility util; private CatalogService catalog; private QueryAnalyzer analyzer; private SubqueryContext.Factory factory; private StorageManager sm; @Before public void setUp() throws Exception { util = new NtaTestingUtility(); util.initTestDir(); util.startMiniZKCluster(); catalog = util.startCatalogCluster().getCatalog(); File testDir = NtaTestingUtility.getTestDir(TEST_PATH); conf = util.getConfiguration(); sm = StorageManager.get(conf, testDir.getAbsolutePath()); Schema employeeSchema = new Schema(); employeeSchema.addColumn("managerId", DataType.INT); employeeSchema.addColumn("empId", DataType.INT); employeeSchema.addColumn("memId", DataType.INT); employeeSchema.addColumn("deptName", DataType.STRING); TableMeta employeeMeta = TCatUtil.newTableMeta(employeeSchema, StoreType.CSV); sm.initTableBase(employeeMeta, "employee"); Appender appender = sm.getAppender(employeeMeta, "employee", "employee"); Tuple tuple = new VTuple(employeeMeta.getSchema().getColumnNum()); for (int i = 0; i < 10; i++) { tuple.put(new Datum[] { DatumFactory.createInt(i), DatumFactory.createInt(i), DatumFactory.createInt(10 + i), DatumFactory.createString("dept_" + i) }); appender.addTuple(tuple); } appender.flush(); appender.close(); TableDesc employee = TCatUtil.newTableDesc("employee", employeeMeta, sm.getTablePath("people")); catalog.addTable(employee); Schema peopleSchema = new Schema(); peopleSchema.addColumn("empId", DataType.INT); peopleSchema.addColumn("fk_memId", DataType.INT); peopleSchema.addColumn("name", DataType.STRING); peopleSchema.addColumn("age", DataType.INT); TableMeta peopleMeta = TCatUtil.newTableMeta(peopleSchema, StoreType.CSV); sm.initTableBase(peopleMeta, "people"); appender = sm.getAppender(peopleMeta, "people", "people"); tuple = new VTuple(peopleMeta.getSchema().getColumnNum()); for (int i = 1; i < 10; i += 2) { tuple.put(new Datum[] { DatumFactory.createInt(i), DatumFactory.createInt(10 + i), DatumFactory.createString("name_" + i), DatumFactory.createInt(30 + i) }); appender.addTuple(tuple); } appender.flush(); appender.close(); TableDesc people = TCatUtil.newTableDesc("people", peopleMeta, sm.getTablePath("people")); catalog.addTable(people); analyzer = new QueryAnalyzer(catalog); } @After public void tearDown() throws Exception { util.shutdownCatalogCluster(); util.shutdownMiniZKCluster(); } String[] QUERIES = { "select managerId, e.empId, deptName, e.memId from employee as e inner join people as p on e.empId = p.empId and e.memId = p.fk_memId" }; @Test public final void testInnerJoin() throws IOException { Fragment[] empFrags = sm.split("employee"); Fragment[] peopleFrags = sm.split("people"); Fragment[] merged = TUtil.concat(empFrags, peopleFrags); factory = new SubqueryContext.Factory(catalog); File workDir = NtaTestingUtility.getTestDir("InnerJoin"); SubqueryContext ctx = factory.create(QueryIdFactory .newQueryUnitId(QueryIdFactory.newScheduleUnitId(QueryIdFactory .newSubQueryId(QueryIdFactory.newQueryId()))), merged, workDir); QueryBlock query = (QueryBlock) analyzer.parse(ctx, QUERIES[0]); LogicalNode plan = LogicalPlanner.createPlan(ctx, query); PhysicalPlanner phyPlanner = new PhysicalPlanner(sm); PhysicalExec exec = phyPlanner.createPlan(ctx, plan); ProjectionExec proj = (ProjectionExec) exec; MergeJoinExec join = (MergeJoinExec) proj.getChild(); ExternalSortExec sortout = (ExternalSortExec) join.getOuter(); ExternalSortExec sortin = (ExternalSortExec) join.getInner(); SeqScanExec scanout = (SeqScanExec) sortout.getSubOp(); SeqScanExec scanin = (SeqScanExec) sortin.getSubOp(); HashJoinExec hashjoin = new HashJoinExec(ctx, join.getJoinNode(), scanout, scanin); proj.setChild(hashjoin); exec = proj; Tuple tuple; int count = 0; int i = 1; while ((tuple = exec.next()) != null) { count++; assertTrue(i == tuple.getInt(0).asInt()); assertTrue(i == tuple.getInt(1).asInt()); assertTrue(("dept_" + i).equals(tuple.getString(2).asChars())); assertTrue(10 + i == tuple.getInt(3).asInt()); i += 2; } assertEquals(10 / 2, count); } }
engine/src/test/java/nta/engine/planner/physical/TestHashJoinExec.java
package nta.engine.planner.physical; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import nta.catalog.CatalogService; import nta.catalog.Schema; import nta.catalog.TCatUtil; import nta.catalog.TableDesc; import nta.catalog.TableMeta; import nta.catalog.proto.CatalogProtos.DataType; import nta.catalog.proto.CatalogProtos.StoreType; import nta.datum.Datum; import nta.datum.DatumFactory; import nta.engine.NtaTestingUtility; import nta.engine.QueryIdFactory; import nta.engine.SubqueryContext; import nta.engine.ipc.protocolrecords.Fragment; import nta.engine.parser.QueryAnalyzer; import nta.engine.parser.QueryBlock; import nta.engine.planner.LogicalPlanner; import nta.engine.planner.PhysicalPlanner; import nta.engine.planner.logical.LogicalNode; import nta.engine.utils.TUtil; import nta.storage.Appender; import nta.storage.StorageManager; import nta.storage.Tuple; import nta.storage.VTuple; import org.apache.hadoop.conf.Configuration; import org.junit.After; import org.junit.Before; import org.junit.Test; public class TestHashJoinExec { private Configuration conf; private final String TEST_PATH = "target/test-data/TestHashJoinExec"; private NtaTestingUtility util; private CatalogService catalog; private QueryAnalyzer analyzer; private SubqueryContext.Factory factory; private StorageManager sm; @Before public void setUp() throws Exception { util = new NtaTestingUtility(); util.initTestDir(); util.startMiniZKCluster(); catalog = util.startCatalogCluster().getCatalog(); File testDir = NtaTestingUtility.getTestDir(TEST_PATH); conf = util.getConfiguration(); sm = StorageManager.get(conf, testDir.getAbsolutePath()); Schema employeeSchema = new Schema(); employeeSchema.addColumn("managerId", DataType.INT); employeeSchema.addColumn("empId", DataType.INT); employeeSchema.addColumn("memId", DataType.INT); employeeSchema.addColumn("deptName", DataType.STRING); TableMeta employeeMeta = TCatUtil.newTableMeta(employeeSchema, StoreType.CSV); sm.initTableBase(employeeMeta, "employee"); Appender appender = sm.getAppender(employeeMeta, "employee", "employee"); Tuple tuple = new VTuple(employeeMeta.getSchema().getColumnNum()); for (int i = 0; i < 10; i++) { tuple.put(new Datum[] { DatumFactory.createInt(i), DatumFactory.createInt(i), DatumFactory.createInt(10 + i), DatumFactory.createString("dept_" + i) }); appender.addTuple(tuple); } appender.flush(); appender.close(); TableDesc employee = TCatUtil.newTableDesc("employee", employeeMeta, sm.getTablePath("people")); catalog.addTable(employee); Schema peopleSchema = new Schema(); peopleSchema.addColumn("empId", DataType.INT); peopleSchema.addColumn("fk_memId", DataType.INT); peopleSchema.addColumn("name", DataType.STRING); peopleSchema.addColumn("age", DataType.INT); TableMeta peopleMeta = TCatUtil.newTableMeta(peopleSchema, StoreType.CSV); sm.initTableBase(peopleMeta, "people"); appender = sm.getAppender(peopleMeta, "people", "people"); tuple = new VTuple(peopleMeta.getSchema().getColumnNum()); for (int i = 1; i < 10; i += 2) { tuple.put(new Datum[] { DatumFactory.createInt(i), DatumFactory.createInt(10 + i), DatumFactory.createString("name_" + i), DatumFactory.createInt(30 + i) }); appender.addTuple(tuple); } appender.flush(); appender.close(); TableDesc people = TCatUtil.newTableDesc("people", peopleMeta, sm.getTablePath("people")); catalog.addTable(people); analyzer = new QueryAnalyzer(catalog); } @After public void tearDown() throws Exception { util.shutdownCatalogCluster(); util.shutdownMiniZKCluster(); } String[] QUERIES = { "select managerId, e.empId, deptName, e.memId from employee as e inner join people as p on e.empId = p.empId and e.memId = p.fk_memId" }; @Test public final void testInnerJoin() throws IOException { Fragment[] empFrags = sm.split("employee"); Fragment[] peopleFrags = sm.split("people"); Fragment[] merged = TUtil.concat(empFrags, peopleFrags); factory = new SubqueryContext.Factory(catalog); File workDir = NtaTestingUtility.getTestDir("InnerJoin"); SubqueryContext ctx = factory.create(QueryIdFactory .newQueryUnitId(QueryIdFactory.newScheduleUnitId(QueryIdFactory .newSubQueryId(QueryIdFactory.newQueryId()))), merged, workDir); QueryBlock query = (QueryBlock) analyzer.parse(ctx, QUERIES[0]); LogicalNode plan = LogicalPlanner.createPlan(ctx, query); PhysicalPlanner phyPlanner = new PhysicalPlanner(sm); PhysicalExec exec = phyPlanner.createPlan(ctx, plan); ProjectionExec proj = (ProjectionExec) exec; MergeJoinExec join = (MergeJoinExec) proj.getsubOp(); ExternalSortExec sortout = (ExternalSortExec) join.getouter(); ExternalSortExec sortin = (ExternalSortExec) join.getinner(); SeqScanExec scanout = (SeqScanExec) sortout.getsubOp(); SeqScanExec scanin = (SeqScanExec) sortin.getsubOp(); HashJoinExec hashjoin = new HashJoinExec(ctx, join.getJoinNode(), scanout, scanin); proj.setsubOp(hashjoin); exec = proj; Tuple tuple; int count = 0; int i = 1; while ((tuple = exec.next()) != null) { count++; assertTrue(i == tuple.getInt(0).asInt()); assertTrue(i == tuple.getInt(1).asInt()); assertTrue(("dept_" + i).equals(tuple.getString(2).asChars())); assertTrue(10 + i == tuple.getInt(3).asInt()); i += 2; } assertEquals(10 / 2, count); } }
TAJO-593: local hash join 구현 (fixed unittest errta) Change-Id: I1cb8633c0e4a682f412d51ed2ece927ad349c455 Reviewed-on: https://dbserver.korea.ac.kr/reviews/221 Tested-by: Jenkins <[email protected]> Reviewed-by: Hyunsik Choi <[email protected]>
engine/src/test/java/nta/engine/planner/physical/TestHashJoinExec.java
TAJO-593: local hash join 구현 (fixed unittest errta)
<ide><path>ngine/src/test/java/nta/engine/planner/physical/TestHashJoinExec.java <ide> <ide> <ide> ProjectionExec proj = (ProjectionExec) exec; <del> MergeJoinExec join = (MergeJoinExec) proj.getsubOp(); <del> ExternalSortExec sortout = (ExternalSortExec) join.getouter(); <del> ExternalSortExec sortin = (ExternalSortExec) join.getinner(); <del> SeqScanExec scanout = (SeqScanExec) sortout.getsubOp(); <del> SeqScanExec scanin = (SeqScanExec) sortin.getsubOp(); <add> MergeJoinExec join = (MergeJoinExec) proj.getChild(); <add> ExternalSortExec sortout = (ExternalSortExec) join.getOuter(); <add> ExternalSortExec sortin = (ExternalSortExec) join.getInner(); <add> SeqScanExec scanout = (SeqScanExec) sortout.getSubOp(); <add> SeqScanExec scanin = (SeqScanExec) sortin.getSubOp(); <ide> <ide> HashJoinExec hashjoin = new HashJoinExec(ctx, join.getJoinNode(), scanout, scanin); <del> proj.setsubOp(hashjoin); <add> proj.setChild(hashjoin); <ide> <ide> exec = proj; <ide>
Java
mit
840c28355a11452a4d32a5731f0df3e10c47621f
0
dapperstout/pulse-java
package syncthing.bep.util; public class Bytes { public static boolean[] bits(byte eightBits) { boolean[] result = new boolean[8]; byte mask = (byte) 0b10000000; for (int i = 0; i < result.length; i++) { result[i] = (eightBits & mask) != 0; eightBits <<= 1; } return result; } public static byte[] nibbles(byte twoNibbles) { byte[] result = new byte[2]; result[0] = (byte) ((twoNibbles >>> 4) & (byte) 0x0F); result[1] = (byte) (twoNibbles & 0x0F); return result; } public static byte[] bytes(short twoBytes) { byte[] result = new byte[2]; result[0] = (byte) ((twoBytes >>> 8) & 0xFF); result[1] = (byte) (twoBytes & 0xFF); return result; } public static byte[] bytes(int fourBytes) { byte[] result = new byte[4]; result[0] = (byte) ((fourBytes >>> 24) & 0xFF); result[1] = (byte) ((fourBytes >>> 16) & 0xFF); result[2] = (byte) ((fourBytes >>> 8) & 0xFF); result[3] = (byte) (fourBytes & 0xFF); return result; } public static byte concatenateBits(boolean... bits) { byte result = 0; for (boolean bit : bits) { result <<= 1; if (bit) { result = (byte) (result | 1); } } return result; } public static byte concatenateNibbles(byte leftNibble, byte rightNibble) { return (byte) (leftNibble << 4 | rightNibble); } public static short concatenateBytes(byte left, byte right) { return (short) ((unsigned(left) << 8) | unsigned(right)); } public static int concatenateBytes(byte b0, byte b1, byte b2, byte b3) { return (unsigned(b0) << 24) | (unsigned(b1) << 16) | (unsigned(b2) << 8) | unsigned(b3); } public static int unsigned(byte b) { return b & 0xFF; } public static long unsigned(int i) { return i & 0xFFFFFFFFL; } }
src/main/java/syncthing/bep/util/Bytes.java
package syncthing.bep.util; public class Bytes { public static boolean[] bits(byte eightBits) { boolean[] result = new boolean[8]; byte mask = (byte) 0b10000000; for (int i = 0; i < result.length; i++) { result[i] = (eightBits & mask) != 0; eightBits <<= 1; } return result; } public static byte[] nibbles(byte twoNibbles) { byte[] result = new byte[2]; result[0] = (byte) ((twoNibbles >>> 4) & (byte) 0x0F); result[1] = (byte) (twoNibbles & 0x0F); return result; } public static byte[] bytes(short twoBytes) { byte[] result = new byte[2]; result[0] = (byte) ((twoBytes >>> 8) & 0xFF); result[1] = (byte) (twoBytes & 0xFF); return result; } public static byte[] bytes(int fourBytes) { byte[] result = new byte[4]; result[0] = (byte) ((fourBytes >>> 24) & 0xFF); result[1] = (byte) ((fourBytes >>> 16) & 0xFF); result[2] = (byte) ((fourBytes >>> 8) & 0xFF); result[3] = (byte) (fourBytes & 0xFF); return result; } public static byte concatenateBits(boolean... bits) { byte result = 0; for (boolean bit : bits) { if (result != 0) { result <<= 1; } if (bit) { result = (byte) (result | 1); } } return result; } public static byte concatenateNibbles(byte leftNibble, byte rightNibble) { return (byte) (leftNibble << 4 | rightNibble); } public static short concatenateBytes(byte left, byte right) { return (short) ((unsigned(left) << 8) | unsigned(right)); } public static int concatenateBytes(byte b0, byte b1, byte b2, byte b3) { return (unsigned(b0) << 24) | (unsigned(b1) << 16) | (unsigned(b2) << 8) | unsigned(b3); } public static int unsigned(byte b) { return b & 0xFF; } public static long unsigned(int i) { return i & 0xFFFFFFFFL; } }
Simplify.
src/main/java/syncthing/bep/util/Bytes.java
Simplify.
<ide><path>rc/main/java/syncthing/bep/util/Bytes.java <ide> public static byte concatenateBits(boolean... bits) { <ide> byte result = 0; <ide> for (boolean bit : bits) { <del> if (result != 0) { <del> result <<= 1; <del> } <add> result <<= 1; <ide> if (bit) { <ide> result = (byte) (result | 1); <ide> }
Java
lgpl-2.1
b87fe88de8e19e2952d6253b70490ca81c53e72a
0
brltty/brltty,brltty/brltty,brltty/brltty,brltty/brltty,brltty/brltty,brltty/brltty
/* * libbrlapi - A library providing access to braille terminals for applications. * * Copyright (C) 2006-2020 by * Samuel Thibault <[email protected]> * Sébastien Hinderer <[email protected]> * * libbrlapi comes with ABSOLUTELY NO WARRANTY. * * This is free software, placed 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. Please see the file LICENSE-LGPL for details. * * Web Page: http://brltty.app/ * * This software is maintained by Dave Mielke <[email protected]>. */ package org.a11y.brlapi.clients; import org.a11y.brlapi.*; import java.io.InterruptedIOException; import java.util.concurrent.TimeoutException; public class ApiExceptionClient extends PauseClient { public ApiExceptionClient (String... arguments) { super(arguments); } @Override protected final void runClient (Connection connection) throws ProgramException { ttyMode( connection, false, (tty) -> { WriteArguments arguments = new WriteArguments() .setRegion(1, (tty.getCellCount() + 1)) .setText("This should fail because the region size is too big."); tty.write(arguments); String label = "API exception"; String result = null; try { if (pause(tty)) { result = String.format("wait for %s timed out", label); } else { result = String.format("wait for %s interrupted", label); } } catch (APIException exception) { result = String.format("%s received", label); } printf("%s\n", result); } ); } }
Bindings/Java/clients/ApiExceptionClient.java
/* * libbrlapi - A library providing access to braille terminals for applications. * * Copyright (C) 2006-2020 by * Samuel Thibault <[email protected]> * Sébastien Hinderer <[email protected]> * * libbrlapi comes with ABSOLUTELY NO WARRANTY. * * This is free software, placed 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. Please see the file LICENSE-LGPL for details. * * Web Page: http://brltty.app/ * * This software is maintained by Dave Mielke <[email protected]>. */ package org.a11y.brlapi.clients; import org.a11y.brlapi.*; import java.io.InterruptedIOException; import java.util.concurrent.TimeoutException; public class ApiExceptionClient extends PauseClient { public ApiExceptionClient (String... arguments) { super(arguments); } @Override protected final void runClient (Connection connection) throws ProgramException { ttyMode( connection, false, (tty) -> { WriteArguments arguments = new WriteArguments() .setRegion(1, (tty.getCellCount() + 1)) .setText("This should fail because the region size is too big."); tty.write(arguments); String label = "API exception"; String result = null; try { tty.readKeyWithTimeout(getWaitTime()); result = String.format("%s not thrown", label); } catch (APIException exception) { result = String.format("%s received", label); } catch (InterruptedIOException exception) { result = String.format("wait for %s interrupted", label); } catch (TimeoutException exception) { result = String.format("wait for %s timed out", label); } printf("%s\n", result); } ); } }
Java bindings: The Pause client can use pause (instead of readKeyWithTimeout). (dm)
Bindings/Java/clients/ApiExceptionClient.java
Java bindings: The Pause client can use pause (instead of readKeyWithTimeout). (dm)
<ide><path>indings/Java/clients/ApiExceptionClient.java <ide> String result = null; <ide> <ide> try { <del> tty.readKeyWithTimeout(getWaitTime()); <del> result = String.format("%s not thrown", label); <add> if (pause(tty)) { <add> result = String.format("wait for %s timed out", label); <add> } else { <add> result = String.format("wait for %s interrupted", label); <add> } <ide> } catch (APIException exception) { <ide> result = String.format("%s received", label); <del> } catch (InterruptedIOException exception) { <del> result = String.format("wait for %s interrupted", label); <del> } catch (TimeoutException exception) { <del> result = String.format("wait for %s timed out", label); <ide> } <ide> <ide> printf("%s\n", result);
Java
epl-1.0
77b795654fad5f4c0e9e1068426920b9f3ca83df
0
abstratt/textuml,abstratt/textuml,abstratt/textuml
/******************************************************************************* * Copyright (c) 2006, 2009 Abstratt Technologies * 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: * Rafael Chaves (Abstratt Technologies) - initial API and implementation *******************************************************************************/ package com.abstratt.modelrenderer; import java.util.Map; import java.util.Stack; import java.util.WeakHashMap; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; public class RenderingSession implements IRenderingSession { private IRendererSelector<EObject> selector; private IndentedPrintWriter writer; private Map<EObject, Object> rendered = new WeakHashMap<EObject, Object>(); private Stack<EObject> stack = new Stack<EObject>(); private boolean shallow = false; private IRenderingSettings settings; public RenderingSession(IRendererSelector<EObject> selector, IRenderingSettings settings, IndentedPrintWriter writer) { this.selector = selector; this.writer = writer; this.settings = settings; } @Override public IRenderingSettings getSettings() { return settings; } public boolean render(EObject toRender) { return render(toRender, false); } public boolean render(EObject toRender, boolean newShallow) { // if (this.shallow) // return; if (rendered.put(toRender, "") != null) // already rendered return false; stack.push(toRender); boolean originalShallow = this.shallow; this.shallow = newShallow; try { boolean actuallyRendered = false; IRenderer<EObject> renderer = selector.select(toRender); if (renderer != null) { actuallyRendered = renderer.renderObject(toRender, writer, this); if (!actuallyRendered) rendered.remove(toRender); } return actuallyRendered; } finally { this.shallow = originalShallow; stack.pop(); } } public boolean isShallow() { return shallow; } public EObject getRoot() { return stack.isEmpty() ? null : stack.get(0); } public EObject getCurrent() { return stack.isEmpty() ? null : stack.peek(); } public EObject getPrevious(EClass eClass) { if (stack.size() <= 1) return null; int start = stack.size() - 2; for (int i = start; i >= 0; i--) { EObject current = stack.get(i); if (eClass.isInstance(current)) return current; } return null; } }
plugins/com.abstratt.modelrenderer/src/com/abstratt/modelrenderer/RenderingSession.java
/******************************************************************************* * Copyright (c) 2006, 2009 Abstratt Technologies * 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: * Rafael Chaves (Abstratt Technologies) - initial API and implementation *******************************************************************************/ package com.abstratt.modelrenderer; import java.util.Collection; import java.util.Map; import java.util.Stack; import java.util.WeakHashMap; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; @SuppressWarnings("unchecked") public class RenderingSession implements IRenderingSession { private IRendererSelector selector; private IndentedPrintWriter writer; private Map<EObject, Object> rendered = new WeakHashMap<EObject, Object>(); private Stack<EObject> stack = new Stack<EObject>(); private boolean shallow = false; private IRenderingSettings settings; public RenderingSession(IRendererSelector selector, IRenderingSettings settings, IndentedPrintWriter writer) { this.selector = selector; this.writer = writer; this.settings = settings; } @Override public IRenderingSettings getSettings() { return settings; } public boolean render(EObject toRender) { return render(toRender, false); } public boolean render(EObject toRender, boolean newShallow) { // if (this.shallow) // return; if (rendered.put(toRender, "") != null) // already rendered return false; stack.push(toRender); boolean originalShallow = this.shallow; this.shallow = newShallow; try { boolean actuallyRendered = false; IRenderer renderer = selector.select(toRender); if (renderer != null) { actuallyRendered = renderer.renderObject(toRender, writer, this); if (!actuallyRendered) rendered.remove(toRender); } return actuallyRendered; } finally { this.shallow = originalShallow; stack.pop(); } } public boolean isShallow() { return shallow; } public EObject getRoot() { return stack.isEmpty() ? null : stack.get(0); } public EObject getCurrent() { return stack.isEmpty() ? null : stack.peek(); } public EObject getPrevious(EClass eClass) { if (stack.size() <= 1) return null; int start = stack.size() - 2; for (int i = start; i >= 0; i--) { EObject current = stack.get(i); if (eClass.isInstance(current)) return current; } return null; } }
cleaned up some compiler warnings
plugins/com.abstratt.modelrenderer/src/com/abstratt/modelrenderer/RenderingSession.java
cleaned up some compiler warnings
<ide><path>lugins/com.abstratt.modelrenderer/src/com/abstratt/modelrenderer/RenderingSession.java <ide> *******************************************************************************/ <ide> package com.abstratt.modelrenderer; <ide> <del>import java.util.Collection; <ide> import java.util.Map; <ide> import java.util.Stack; <ide> import java.util.WeakHashMap; <ide> import org.eclipse.emf.ecore.EClass; <ide> import org.eclipse.emf.ecore.EObject; <ide> <del>@SuppressWarnings("unchecked") <ide> public class RenderingSession implements IRenderingSession { <del> private IRendererSelector selector; <add> private IRendererSelector<EObject> selector; <ide> private IndentedPrintWriter writer; <ide> private Map<EObject, Object> rendered = new WeakHashMap<EObject, Object>(); <ide> private Stack<EObject> stack = new Stack<EObject>(); <ide> private boolean shallow = false; <ide> private IRenderingSettings settings; <ide> <del> public RenderingSession(IRendererSelector selector, IRenderingSettings settings, IndentedPrintWriter writer) { <add> public RenderingSession(IRendererSelector<EObject> selector, IRenderingSettings settings, IndentedPrintWriter writer) { <ide> this.selector = selector; <ide> this.writer = writer; <ide> this.settings = settings; <ide> this.shallow = newShallow; <ide> try { <ide> boolean actuallyRendered = false; <del> IRenderer renderer = selector.select(toRender); <add> IRenderer<EObject> renderer = selector.select(toRender); <ide> if (renderer != null) { <ide> actuallyRendered = renderer.renderObject(toRender, writer, this); <ide> if (!actuallyRendered)
Java
apache-2.0
0fb1eaec7820dcd717d8336e84747b0472a71a80
0
bia-code/jcronofy
package org.biacode.jcronofy.api.model; import com.fasterxml.jackson.annotation.JsonProperty; /** * User: Arthur Asatryan * Company: SFL LLC * Date: 10/5/16 * Time: 3:25 PM */ public enum ScopeModel { @JsonProperty("read_events") READ_EVENTS("read_events"), @JsonProperty("create_event") CREATE_EVENT("create_event"), @JsonProperty("delete_event") DELETE_EVENT("delete_event"), @JsonProperty("read_free_busy") READ_FREE_BUSY("read_free_busy"), @JsonProperty("create_calendar") CREATE_CALENDAR("create_calendar"), @JsonProperty("event_reminders") EVENT_REMINDERS("event_reminders"), @JsonProperty("change_participation_status") CHANGE_PARTICIPATION_STATUS("change_participation_status"); final String scope; ScopeModel(final String scope) { this.scope = scope; } public String getScope() { return scope; } }
src/main/java/org/biacode/jcronofy/api/model/ScopeModel.java
package org.biacode.jcronofy.api.model; import com.fasterxml.jackson.annotation.JsonProperty; /** * User: Arthur Asatryan * Company: SFL LLC * Date: 10/5/16 * Time: 3:25 PM */ public enum ScopeModel { @JsonProperty("read_events") READ_EVENTS("read_events"), @JsonProperty("create_event") CREATE_EVENT("create_event"), @JsonProperty("delete_event") DELETE_EVENT("delete_event"), READ_FREE_BUSY("read_free_busy"); final String scope; ScopeModel(final String scope) { this.scope = scope; } public String getScope() { return scope; } }
[#2] added missing scope values
src/main/java/org/biacode/jcronofy/api/model/ScopeModel.java
[#2] added missing scope values
<ide><path>rc/main/java/org/biacode/jcronofy/api/model/ScopeModel.java <ide> CREATE_EVENT("create_event"), <ide> @JsonProperty("delete_event") <ide> DELETE_EVENT("delete_event"), <del> READ_FREE_BUSY("read_free_busy"); <add> @JsonProperty("read_free_busy") <add> READ_FREE_BUSY("read_free_busy"), <add> @JsonProperty("create_calendar") <add> CREATE_CALENDAR("create_calendar"), <add> @JsonProperty("event_reminders") <add> EVENT_REMINDERS("event_reminders"), <add> @JsonProperty("change_participation_status") <add> CHANGE_PARTICIPATION_STATUS("change_participation_status"); <ide> <ide> final String scope; <ide>
JavaScript
bsd-3-clause
57db0b254fd554e03d107b1e6c55287f5aaa225c
0
digitalbazaar/payswarm.js
/** * A JavaScript implementation of the PaySwarm API. * * @author Dave Longley * * Copyright (c) 2011-2013, Digital Bazaar, Inc. * 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 Digital Bazaar, Inc. nor the names of its 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 HOLDER 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. */ 'use strict'; var async = require('async'); var crypto = require('crypto'); var fs = require('fs'); var jsonld = require('jsonld')(); // get localized jsonld API var mkdirp = require('mkdirp'); var path = require('path'); var URL = require('url'); var ursa = require('ursa'); var util = require('util'); jsonld.use('request'); var api = {}; module.exports = api; /* PAYSWARM CLIENT API ------------------- The PaySwarm Client API allows vendors to register with a PaySwarm Authority, sign listings for the items they wish to sell, and receive payments from their customers. INSTRUCTIONS ------------ First, implement all of the required hooks. Various hooks will be triggered when making calls to the API. Most of the hooks involve providing the API with a custom mechanism for doing HTTP GET/POST and storing/retrieving data from a database. It is also highly recommended that the optional cache hooks be implemented to prevent excessive network traffic when looking up PaySwarm Authority configurations and public keys. To implement a hook, simply write a function that takes the appropriate parameters and returns the appropriate values. Then pass the hook name and the name of the custom function to 'payswarm.addHook'. Look below for the specific hooks that must be implemented. Next, use the API to register as a vendor on the PaySwarm Authority of choice, sign listings, and accept payments via customers' chosen PaySwarm Authorities. First, require this module: var payswarm = require('payswarm'); Then: 1. Add the PaySwarm Authorities that should be trusted by calling: payswarm.addTrustedAuthority('trustedauthority:port'); In this version of the API, any customer's PaySwarm Authority that the vendor would like to do business with must be manually added. The vendor's chosen PaySwarm Authority will be automatically added during the registration step. 2. Register as a vendor by calling: var url = payswarm.getRegisterVendorUrl( 'myauthority:port', 'http://myserver/myregistercallbackurl', callback); The first parameter is the host and port of the PaySwarm Authority to register with. The second is a callback URL that will receive the result of the registration as POST data. Direct the vendor to the URL so that they can complete the registration process. Once the registration process is complete, the vendor's browser will POST the registration result to the callback URL provided. 3. On the callback page, get the POST value 'encrypted-message' and pass it to register the vendor: payswarm.registerVendor( req.body['encrypted-message'], { privateKey: 'your private key in PEM format', }, callback); If no error is given to the callback, registration is complete. The second callback parameter is the PaySwarm Vendor's Preferences, including the Financial Account ID to use in Listings. 5. Create a JSON-LD PaySwarm Asset and Listing. When listing an Asset, its unique hash must be in the Listing. To generate an asset hash call: payswarm.hash(asset, callback); 4. Sign a listing. Create a JSON-LD PaySwarm Listing and then sign it: payswarm.sign(listing, callback); Display the listing information; the use of RDFa is recommended. Depending on the application's needs, it is sometimes a good idea (or a requirement) to regenerate signatures when the vendor's public key is changed. Note: A Listing also contains a License for the Asset. If the application knows the ID (IRI) of the License to use but not the License hash, and it does not have the necessary parser to obtain the License information from its ID, it may use the PaySwarm Authority's license service to cache and retrieve the License by its ID. Then payswarm.hash(license, callback) can be called on the result to produce its hash. 5. When a customer indicates that they want to purchase the Asset in a Listing, call: var url = payswarm.getPurchaseUrl( 'customersauthority:port', listingId, listingHash, 'https://myserver/mypurchasecallbackurl', callback); To get a URL to redirect the customer to their PaySwarm Authority to complete the purchase. The last parameter is a callback URL that will receive the result of the purchase as POST data. If the customer has previously completed a purchase and the response indicated that they set up a budget to handle automated purchases in the future, then an automated purchase can be attempted by calling: payswarm.purchase( 'customersauthority:port', 'https://customersauthority:port/i/customer', listingId, listingHash, callback); In this version of the API, it is the responsibility of the application to determine the customer's PaySwarm Authority (usually by asking). A listing hash can be generated by calling: payswarm.hash(listing, callback); To get the JSON-LD receipt from a purchase, call: payswarm.getReceipt(encryptedMessage, { privateKey: 'your private key in PEM format', }, callback); Where encryptedMessage is either the result of a POST to the purchase callback or the result of the payswarm.purchase() call. The receipt will indicate the ID and hash of the Asset purchased as well as the ID and hash of the License for the Asset. */ // FIXME: ported from PHP, use more nodejs-like idioms, pass 'cache' or // 'store' objects that have interfaces to be implemented, etc. // hook API var hooks = {}; /** * Adds a hook. To add a hook, pass the name of the hook (eg: createNonce) and * the user-defined function name to be called. Hooks are permitted to throw * exceptions as are any PaySwarm client API calls. API calls should be * wrapped in try/catch blocks as appropriate. * * Required protocol hooks: * * createNonce(): Creates and stores a nonce that is to be given to a * PaySwarm Authority so it can be returned in a signed and encrypted * message. * * checkNonce(nonce, callback(err, valid)): Checks a nonce previously created * by createNonce and removes it from storage. Passes true in the callback * if the nonce is valid, false if not. * * Required storage hooks: * * getPublicKey(callback(err, key)): Passes the vendor's public key in PEM * format to the callback. * * getPublicKeyId(callback(err, id)): Passes the ID (IRI) for the vendor's * public key to the callback. * * getPrivateKey(callback(err, key)): Passes the vendor's private key in * PEM format to the callback. * * isTrustedAuthority(id, callback(err, trusted)): Passes true to the * callback if the given identity (IRI) is a trusted PaySwarm Authority, * false if not. * * storeKeyPair(publicPem, privatePem, callback(err)): Stores the vendor's * key pair. * * storePublicKeyId(id, callback(err)): Stores the vendor's public key ID * (IRI). * * storeTrustedAuthority(id, callback(err)): Stores the ID (IRI) of a trusted * PaySwarm Authority. * * Optional retrieval hooks: * * getJsonLd(url, [options,] callback(err, result)): Performs a HTTP GET and * calls a callback with the parsed JSON-LD result object using the * jsonld.request function and options. * * postJsonLd(url, data, [options,] callback(err, result)): Performs a HTTP * POST of the given JSON-LD data and calls a callback with the parsed * JSON-LD result object (if any) using the jsonld.request function and * options. * * Optional cache hooks: * * cacheJsonLd(id, obj, secs, callback(err)): Caches a JSON-LD object. The * ID (IRI) for the object is given and the maxmimum number of seconds to * cache. * * getCachedJsonLd(id, callback(err, result)): Gets a JSON-LD object from * cache. Passes the object or null to the callback. * * @param hook the name of the hook. * @param func the name of the function to call. */ api.addHook = function(hook, func) { hooks[hook] = func; }; /** * Versioned PaySwarm JSON-LD context URLs. */ api.CONTEXT_V1_URL = "https://w3id.org/payswarm/v1"; /** * Default PaySwarm JSON-LD context URL. */ api.CONTEXT_URL = api.CONTEXT_V1_URL; /** * Supported PaySwarm JSON-LD contexts. */ api.CONTEXTS = {}; /** * V1 PaySwarm JSON-LD context. */ api.CONTEXTS[api.CONTEXT_V1_URL] = { // aliases 'id': '@id', 'type': '@type', // prefixes 'ccard': 'https://w3id.org/commerce/creditcard#', 'com': 'https://w3id.org/commerce#', 'dc': 'http://purl.org/dc/terms/', 'foaf': 'http://xmlns.com/foaf/0.1/', 'gr': 'http://purl.org/goodrelations/v1#', 'pto': 'http://www.productontology.org/id/', 'ps': 'https://w3id.org/payswarm#', 'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'rdfs': 'http://www.w3.org/2000/01/rdf-schema#', 'sec': 'https://w3id.org/security#', 'vcard': 'http://www.w3.org/2006/vcard/ns#', 'xsd': 'http://www.w3.org/2001/XMLSchema#', // general 'address': {'@id': 'vcard:adr', '@type': '@id'}, 'comment': 'rdfs:comment', 'countryName': 'vcard:country-name', 'created': {'@id': 'dc:created', '@type': 'xsd:dateTime'}, 'creator': {'@id': 'dc:creator', '@type': '@id'}, 'depiction': {'@id': 'foaf:depiction', '@type': '@id'}, 'description': 'dc:description', 'email': 'foaf:mbox', 'fullName': 'vcard:fn', 'label': 'rdfs:label', 'locality': 'vcard:locality', 'postalCode': 'vcard:postal-code', 'region': 'vcard:region', 'streetAddress': 'vcard:street-address', 'title': 'dc:title', 'website': {'@id': 'foaf:homepage', '@type': '@id'}, 'Address': 'vcard:Address', // bank 'bankAccount': 'bank:account', 'bankAccountType': {'@id': 'bank:accountType', '@type': '@vocab'}, 'bankRoutingNumber': 'bank:routing', 'BankAccount': 'bank:BankAccount', 'Checking': 'bank:Checking', 'Savings': 'bank:Savings', // credit card 'cardBrand': {'@id': 'ccard:brand', '@type': '@vocab'}, 'cardCvm': 'ccard:cvm', 'cardExpMonth': {'@id': 'ccard:expMonth', '@type': 'xsd:integer'}, 'cardExpYear': {'@id': 'ccard:expYear', '@type': 'xsd:integer'}, 'cardNumber': 'ccard:number', 'AmericanExpress': 'ccard:AmericanExpress', 'ChinaUnionPay': 'ccard:ChinaUnionPay', 'CreditCard': 'ccard:CreditCard', 'Discover': 'ccard:Discover', 'Visa': 'ccard:Visa', 'MasterCard': 'ccard:MasterCard', // commerce 'account': {'@id': 'com:account', '@type': '@id'}, 'amount': 'com:amount', 'authorized': {'@id': 'com:authorized', '@type': 'xsd:dateTime'}, 'balance': 'com:balance', 'currency': {'@id': 'com:currency', '@type': '@vocab'}, 'destination': {'@id': 'com:destination', '@type': '@id'}, 'maximumAmount': 'com:maximumAmount', 'maximumPayeeRate': 'com:maximumPayeeRate', 'minimumPayeeRate': 'com:minimumPayeeRate', 'minimumAmount': 'com:minimumAmount', 'payee': {'@id': 'com:payee', '@type': '@id', '@container': '@set'}, 'payeeApplyAfter': {'@id': 'com:payeeApplyAfter', '@container': '@set'}, 'payeeApplyGroup': {'@id': 'com:payeeApplyGroup', '@container': '@set'}, 'payeeApplyType': {'@id': 'com:payeeApplyType', '@type': '@vocab'}, 'payeeGroup': {'@id': 'com:payeeGroup', '@container': '@set'}, 'payeeGroupPrefix': {'@id': 'com:payeeGroupPrefix', '@container': '@set'}, 'payeeExemptGroup': {'@id': 'com:payeeExemptGroup', '@container': '@set'}, 'payeeLimitation': {'@id': 'com:payeeLimitation', '@type': '@vocab'}, 'payeeRate': 'com:payeeRate', 'payeeRateType': {'@id': 'com:payeeRateType', '@type': '@vocab'}, 'payeeRule': {'@id': 'com:payeeRule', '@type': '@id', '@container': '@set'}, 'paymentGateway': 'com:paymentGateway', 'paymentMethod': {'@id': 'com:paymentMethod', '@type': '@vocab'}, 'paymentToken': 'com:paymentToken', 'referenceId': 'com:referenceId', 'settled': {'@id': 'com:settled', '@type': 'xsd:dateTime'}, 'source': {'@id': 'com:source', '@type': '@id'}, 'transfer': {'@id': 'com:transfer', '@type': '@id', '@container': '@set'}, 'vendor': {'@id': 'com:vendor', '@type': '@id'}, 'voided': {'@id': 'com:voided', '@type': 'xsd:dateTime'}, 'ApplyExclusively': 'com:ApplyExclusively', 'ApplyInclusively': 'com:ApplyInclusively', 'FinancialAccount': 'com:Account', 'FlatAmount': 'com:FlatAmount', 'Deposit': 'com:Deposit', 'NoAdditionalPayeesLimitation': 'com:NoAdditionalPayeesLimitation', 'Payee': 'com:Payee', 'PayeeRule': 'com:PayeeRule', 'PayeeScheme': 'com:PayeeScheme', 'PaymentToken': 'com:PaymentToken', 'Percentage': 'com:Percentage', 'Transaction': 'com:Transaction', 'Transfer': 'com:Transfer', 'Withdrawal': 'com:Withdrawal', // currencies 'USD': 'https://w3id.org/currencies/USD', // error // FIXME: add error terms // 'errorMessage': 'err:message' // payswarm 'asset': {'@id': 'ps:asset', '@type': '@id'}, 'assetAcquirer': {'@id': 'ps:assetAcquirer', '@type': '@id'}, // FIXME: support inline content 'assetContent': {'@id': 'ps:assetContent', '@type': '@id'}, 'assetHash': 'ps:assetHash', 'assetProvider': {'@id': 'ps:assetProvider', '@type': '@id'}, 'authority': {'@id': 'ps:authority', '@type': '@id'}, 'contract': {'@id': 'ps:contract', '@type': '@id'}, 'identityHash': 'ps:identityHash', // FIXME: move? 'ipv4Address': 'ps:ipv4Address', 'license': {'@id': 'ps:license', '@type': '@id'}, 'licenseHash': 'ps:licenseHash', 'licenseTemplate': 'ps:licenseTemplate', 'licenseTerms': {'@id': 'ps:licenseTerms', '@type': '@id'}, 'listing': {'@id': 'ps:listing', '@type': '@id'}, 'listingHash': 'ps:listingHash', 'listingRestrictions': {'@id': 'ps:listingRestrictions', '@type': '@id'}, 'preferences': {'@id': 'ps:preferences', '@type': '@vocab'}, 'validFrom': {'@id': 'ps:validFrom', '@type': 'xsd:dateTime'}, 'validUntil': {'@id': 'ps:validUntil', '@type': 'xsd:dateTime'}, 'Asset': 'ps:Asset', 'Budget': 'ps:Budget', 'Contract': 'ps:Contract', 'License': 'ps:License', 'Listing': 'ps:Listing', 'PersonalIdentity': 'ps:PersonalIdentity', 'IdentityPreferences': 'ps:IdentityPreferences', 'Profile': 'ps:Profile', 'PurchaseRequest': 'ps:PurchaseRequest', 'PreAuthorization': 'ps:PreAuthorization', 'Receipt': 'ps:Receipt', 'VendorIdentity': 'ps:VendorIdentity', // security 'cipherAlgorithm': 'sec:cipherAlgorithm', 'cipherData': 'sec:cipherData', 'cipherKey': 'sec:cipherKey', 'digestAlgorithm': 'sec:digestAlgorithm', 'digestValue': 'sec:digestValue', 'expiration': {'@id': 'sec:expiration', '@type': 'xsd:dateTime'}, 'initializationVector': 'sec:initializationVector', 'nonce': 'sec:nonce', 'normalizationAlgorithm': 'sec:normalizationAlgorithm', 'owner': {'@id': 'sec:owner', '@type': '@id'}, 'password': 'sec:password', 'privateKey': {'@id': 'sec:privateKey', '@type': '@id'}, 'privateKeyPem': 'sec:privateKeyPem', 'publicKey': {'@id': 'sec:publicKey', '@type': '@id'}, 'publicKeyPem': 'sec:publicKeyPem', 'publicKeyService': {'@id': 'sec:publicKeyService', '@type': '@id'}, 'revoked': {'@id': 'sec:revoked', '@type': 'xsd:dateTime'}, 'signature': 'sec:signature', 'signatureAlgorithm': 'sec:signatureAlgorithm', 'signatureValue': 'sec:signatureValue', 'EncryptedMessage': 'sec:EncryptedMessage', 'CryptographicKey': 'sec:Key', 'GraphSignature2012': 'sec:GraphSignature2012' }; /** * Default PaySwarm JSON-LD context. */ api.CONTEXT = api.CONTEXTS[api.CONTEXT_URL]; /** * PaySwarm JSON-LD frames. */ api.FRAMES = {}; /** PaySwarm JSON-LD frame for an Asset. */ api.FRAMES.Asset = { '@context': api.CONTEXT_URL, type: 'Asset', creator: {}, signature: {'@embed': true}, assetProvider: {'@embed': false} }; /** PaySwarm JSON-LD frame for a License. */ api.FRAMES.License = { '@context': api.CONTEXT_URL, type: 'License' }; /** PaySwarm JSON-LD frame for a Listing. */ api.FRAMES.Listing = { '@context': api.CONTEXT_URL, type: 'Listing', asset: {'@embed': false}, license: {'@embed': false}, vendor: {'@embed': false}, signature: {'@embed': true} }; /** * Determines the configuration filename based on the given name and * PaySwarm-specific defaults. This method will always return a filename. * * @param configName the name of the config file, which can be null * (the default config), a pathname, or a nickname for a * previously saved configuration file. * @param callback(err, filename) called when the config has been read. */ api.getConfigFilename = function(configName, callback) { if(configName) { // TODO: check if it's a dir (not a file) and error out early? // if configName is an absolute path use it var normalized = path.normalize(configName); if(path.resolve(normalized) === normalized) { return callback(null, configName); } } // establish base config directory var baseConfigDir = path.resolve(process.env.HOME); if(process.env.XDG_CONFIG_HOME) { baseConfigDir = path.resolve(process.env.XDG_CONFIG_HOME); } // if a config name was not given, use the default if(!configName) { var configFilename = path.join( baseConfigDir, '.config', 'payswarm1', 'default'); return callback(null, configFilename); } // if a valid relative file name was given, use that var relativeFile = path.resolve(configName); fs.exists(relativeFile, function(exists) { if(exists) { return callback(null, relativeFile); } // if a config name was given, use that var configFilename = path.join( baseConfigDir, '.config', 'payswarm1', configName); callback(null, configFilename); }); }; /** * Reads configuration information from a file if the file exists, or just * returns an empty configuration object if it doesn't. * * @param configName the name of the config file, which can be a pathname * or a nickname for a saved configuration file. * @param callback(err, config) called when the config has been read. */ api.readConfig = function(configName, callback) { var cfg = {}; async.waterfall([ function(callback) { api.getConfigFilename(configName, callback); }, function(configFilename, callback) { // attempt to read data from the config file fs.exists(configFilename, function(exists) { if(exists) { return fs.readFile(configFilename, 'utf8', callback); } callback(new Error('Config file does not exist: '+ configFilename)); }); }, function(data, callback) { cfg = JSON.parse(data); // add the default context to the object callback(null, cfg); }], function(err) { cfg['@context'] = 'https://w3id.org/payswarm/v1'; callback(err, cfg); }); }; /** * Writes a configuration out to disk. * * @param configName the name of the config file. * @param cfg the configuration object to write. * @param callback(err, configFilename) the callback called when the file is * written to disk. */ api.writeConfig = function(configName, cfg, callback) { async.waterfall([ function(callback) { api.getConfigFilename(configName, callback); }, function(configFilename, callback) { var configDir = path.dirname(configFilename); // if the directory for the config file doesn't exist, create it fs.exists(configDir, function(exists) { if(exists) { callback(null, configFilename); } else { mkdirp(configDir, parseInt(700, 8), function(err) { if(err) { return callback(err); } callback(null, configFilename); }); } }); }, function(configFilename, callback) { // write the data to disk var data = JSON.stringify(cfg, null, 2); fs.writeFile( configFilename, data, {encoding: 'utf8', mode: parseInt(600, 8)}, function(err) { if(err) { return callback(err); } callback(null, configFilename); }); }], callback); }; /** * Retrieves a JSON-LD object over HTTP. * * @param url the URL to HTTP GET. * @param options: (optional) * cache: true to cache the response. [false] (optional) * request: options for the request. (optional) * @param callback(err, result) called once the operation completes. */ api.getJsonLd = function(url, options, callback) { if(typeof options === 'function') { callback = options; options = {}; } options.request = options.request || {}; async.waterfall([ function(callback) { // use cache if available api.getCachedJsonLd(url, callback); }, function(result, callback) { if(result) { return callback(null, result); } // retrieve JSON-LD hooks.getJsonLd(url, options.request, callback); }, function(result, callback) { if(!result) { return callback(new Error('[payswarm.getJsonLd] ' + 'No JSON-LD found at "' + url + '".')); } // FIXME: take into consideration response cache info // cache JSON-LD if(options.cache) { return api.cacheJsonLd(url, result, function(err) { callback(err, result); }); } callback(null, result); } ], callback); }; /** * HTTP POSTs a JSON-LD object. * * @param url the URL to HTTP POST to. * @param obj the JSON-LD object. * @param options: (optional) * request: options for the request. (optional) * @param callback(err, result) called once the operation completes. */ api.postJsonLd = function(url, obj, options, callback) { if(typeof options === 'function') { callback = options; options = {}; } options.request = options.request || {}; async.waterfall([ function(callback) { hooks.postJsonLd(url, obj, options.request, callback); }, function(result, callback) { try { // parse response // FIXME move callback outside of try/catch callback(null, result); } catch(ex) { callback(new Error('[payswarm.postJsonLd] ' + 'Invalid response from "' + url + '"; malformed JSON - ' + ex.toString() + ': ' + JSON.stringify(result, null, 2))); } } ], callback); }; /** * Caches a JSON-LD object if a cache is available. * * @param id the ID of the JSON-LD object. * @param obj the JSON-LD object to cache. * @param callback(err) called once the operation completes. */ api.cacheJsonLd = function(id, obj, callback) { if('cacheJsonLd' in hooks) { return hooks.cacheJsonLd(id, obj, 60*5, callback); } // no cache callback(); }; /** * Gets a cached JSON-LD object if available. * * @param id the ID of the JSON-LD object. * @param callback(err, result) called once the operation completes. */ api.getCachedJsonLd = function(id, callback) { if('getCachedJsonLd' in hooks) { return hooks.getCachedJsonLd(id, callback); } callback(null, null); }; /** * Gets a remote public key. * * @param id the ID for the public key. * @param options: (optional) * cache: true to cache the response. [false] (optional) * request: options for the request. (optional) * @param callback(err, key) called once the operation completes. */ api.getPublicKey = function(id, options, callback) { if(typeof options === 'function') { callback = options; options = {}; } // retrieve public key api.getJsonLd(id, options, function(err, key) { if(err) { return callback(err); } // FIXME: improve validation if(!('publicKeyPem' in key)) { return callback(new Error('[payswarm.getPublicKey] ' + 'Could not get public key. Unknown format.')); } callback(null, key); }); }; /** * Creates a nonce for a secure message. * * @param callback(err, nonce) called once the operation completes. */ api.createNonce = function(callback) { hooks.createNonce(callback); }; /** * Checks the nonce from a secure message. * * @param nonce the nonce. * @param callback(err, valid) called once the operation completes. */ api.checkNonce = function(nonce, callback) { hooks.checkNonce(nonce, callback); }; /** * Generates a hash of the JSON-LD encoded data. * * @param obj the JSON-LD object to hash. * @param callback(err, hash) called once the operation completes. */ api.hash = function(obj, callback) { // SHA-1 hash JSON jsonld.normalize( obj, { format: 'application/nquads' }, function(err, result) { if(err) { return callback(err); } if(result.length === 0) { return callback(new Error('[payswarm.hash] ' + 'The data to hash is empty. This error may be caused because ' + 'a "@context" was not supplied in the input which would cause ' + 'any terms or prefixes to be undefined. ' + 'Input:\n' + JSON.stringify(obj, null, 2))); } var md = crypto.createHash('sha256'); md.update(result, 'utf8'); callback(null, 'urn:sha256:' + md.digest('hex')); }); }; /** * Signs a JSON-LD object, adding a signature field to it. If a signature * date is not provided then the current date will be used. * * @param obj the JSON-LD object to sign. * @param options the signature options. * [nonce] the nonce to use. * [dateTime] the signature creation dateTime as either a W3C formatted * dateTime or a pure JavaScript date object. * publicKeyId URL to the public key that is associated with the * given private key. * privateKey the private key to use in PEM-encoded format. * @param callback(err, signed) called once the operation completes. */ api.sign = function(obj, options, callback) { var nonce = options.nonce || null; var dateTime = options.dateTime || new Date(); var publicKeyId = options.publicKeyId || null; var privateKeyPem = options.privateKeyPem || null; // get W3C-formatted date if(typeof dateTime !== 'string') { dateTime = api.w3cDate(dateTime); } async.auto({ normalize: function(callback) { jsonld.normalize( obj, { format: 'application/nquads' }, callback); }, sign: ['normalize', function(callback, results) { var normalized = results.normalize; if(normalized.length === 0) { return callback(new Error('[payswarm.sign] ' + 'The data to sign is empty. This error may be caused because ' + 'a "@context" was not supplied in the input which would cause ' + 'any terms or prefixes to be undefined. ' + 'Input:\n' + JSON.stringify(obj, null, 2))); } // generate base64-encoded signature var signer = crypto.createSign('RSA-SHA256'); if(nonce !== null) { signer.update(nonce); } signer.update(dateTime); signer.update(normalized); var signature = signer.sign(privateKeyPem, 'base64'); callback(null, signature); }] }, function(err, results) { if(err) { return callback(err); } // create signature info var signature = { type: 'GraphSignature2012', creator: publicKeyId, created: dateTime, signatureValue: results.sign }; if(nonce !== null) { signature.nonce = nonce; } // FIXME: support multiple signatures obj.signature = signature; jsonld.addValue(obj, '@context', api.CONTEXT_URL, {allowDuplicate: false}); callback(null, obj); }); }; /** * Verifies a JSON-LD digitally-signed object. * * @param obj the JSON-LD object to verify. * @param options: (optional) * request: options for the key request. (optional) * checkTimestamp: check signature timestamp [true] (optional) * maxTimestampDelta: signature must be created within a window of this * many seconds [15 minutes] (optional) * @param callback(err) called once the operation completes. */ api.verify = function(obj, options, callback) { if(typeof options === 'function') { callback = options; options = {}; } if(!('checkTimestamp' in options)) { options.checkTimestamp = true; } if(!('maxTimestampDelta' in options)) { options.maxTimestampDelta = 15 * 60; } async.auto({ // FIXME: add support for multiple signatures // : for many signers of an object, can just check all sigs // : for signed sigs, need to recurse? // FIXME: add support for different signature types // : frame with signatures to get types, then reframe to get // : correct structure for each type. frame: function(callback) { // frame message to retrieve signature var frame = { '@context': api.CONTEXT_URL, signature: { type: {}, created: {}, creator: {}, signatureValue: {}, // FIXME: improve handling signatures w/o nonces //nonce: {'@omitDefault': true} } }; jsonld.frame(obj, frame, function(err, framed) { if(err) { return callback(err); } var graphs = framed['@graph']; if(graphs.length === 0) { return callback(new Error('[payswarm.verify] ' + 'No signed data found.')); } if(graphs.length > 1) { return callback(new Error('[payswarm.verify] ' + 'More than one signed graph found.')); } var graph = graphs[0]; // copy the top level framed data context graph['@context'] = framed['@context']; var signature = graph.signature; if(!signature) { return callback(new Error('[payswarm.verify] ' + 'Valid signature not found.')); } if(signature.type !== 'GraphSignature2012') { return callback(new Error('[payswarm.verify] ' + 'Unknown signature type found.')); } callback(null, graph); }); }, checkNonce: ['frame', function(callback, results) { var signature = results.frame.signature; if('nonce' in signature) { return api.checkNonce(signature.nonce, function(err, valid) { if(err) { return callback(err); } if(!valid) { return callback(new Error('[payswarm.verify] ' + 'The message nonce is invalid.')); } callback(); }); } callback(); }], checkDate: ['frame', function(callback, results) { if(!options.checkTimestamp) { return callback(); } // ensure signature timestamp within a valid range var now = +new Date(); var delta = options.maxTimestampDelta * 1000; try { var signature = results.frame.signature; var created = +Date.parse(signature.created); if(created < (now - delta) || created > (now + delta)) { throw new Error('[payswarm.verify] ' + 'The message digital signature timestamp is out of range.'); } } catch(ex) { callback(ex); } }], getPublicKey: ['frame', function(callback, results) { var signature = results.frame.signature; api.getPublicKey(signature.creator, options, callback); }], verifyPublicKeyOwner: ['getPublicKey', function(callback, results) { if(!('isTrustedAuthority' in hooks)) { return callback(); } var key = results.getPublicKey; hooks.isTrustedAuthority(key.owner, function(err, trusted) { if(err) { return callback(err); } if(!trusted) { return callback(new Error('[payswarm.verify] ' + 'The message is not signed by a trusted public key.')); } callback(); }); }], normalize: ['checkNonce', 'checkDate', 'verifyPublicKeyOwner', function(callback, results) { // remove signature property from object var result = results.frame; var signature = result.signature; delete result.signature; jsonld.normalize( result, { format: 'application/nquads' }, function(err, normalized) { if(err) { return callback(err); } callback(null, {data: normalized, signature: signature}); }); }], verifySignature: ['normalize', function(callback, results) { // ensure key has not been revoked var key = results.getPublicKey; var signature = results.normalize.signature; if('revoked' in key) { return callback(new Error('[payswarm.verify] ' + 'The public key has been revoked.')); } var verifier = crypto.createVerify('RSA-SHA256'); if('nonce' in signature) { verifier.update(signature.nonce); } verifier.update(signature.created); verifier.update(results.normalize.data); var verified = verifier.verify( key.publicKeyPem, signature.signatureValue, 'base64'); if(!verified) { return callback(new Error('[payswarm.verify] ' + 'The digital signature on the message is invalid.')); } callback(); }] }, callback); }; /** * Decrypts an encrypted JSON-LD object. * * @param encrypted the message to decrypt. * @param options the options to use. * privateKey the private key to decrypt with, in PEM-encoded format. * @param callback(err, result) called once the operation completes. */ api.decrypt = function(encrypted, options, callback) { if(encrypted.cipherAlgorithm !== 'rsa-sha256-aes-128-cbc') { var algorithm = encrypted.cipherAlgorithm; return callback(new Error('[payswarm.decrypt] ' + 'Unknown encryption algorithm "' + algorithm + '"')); } try { // private key decrypt key and IV var pk = ursa.createPrivateKey(options.privateKey, 'utf8'); var key = pk.decrypt( encrypted.cipherKey, 'base64', 'binary', ursa.RSA_PKCS1_OAEP_PADDING); var iv = pk.decrypt( encrypted.initializationVector, 'base64', 'binary', ursa.RSA_PKCS1_OAEP_PADDING); // symmetric decrypt data var decipher = crypto.createDecipheriv('aes-128-cbc', key, iv); var decrypted = decipher.update(encrypted.cipherData, 'base64', 'utf8'); decrypted += decipher.final('utf8'); // return parsed result var result = JSON.parse(decrypted); callback(null, result); } catch(ex) { callback(new Error('[payswarm.decrypt] ' + 'Failed to decrypt the encrypted message: ' + ex.toString())); } }; /** * Decodes a JSON-encoded, encrypted, digitally-signed message from a * PaySwarm Authority. * * @param msg the json-encoded message to verify. * @param options the options to use. * privateKey the private key to decrypt with, in PEM-encoded format. * @param callback(err, result) called once the operation completes. */ api.decodeAuthorityMessage = function(msg, options, callback) { try { // convert message from json msg = JSON.parse(msg); } catch(ex) { return callback(new Error('[payswarm.decodeAuthorityMessage] ' + 'The message contains malformed JSON.')); } // decrypt and verify message async.waterfall([ function(callback) { api.decrypt(msg, options, callback); }, function(result, callback) { api.verify(result, function(err) { if(err) { return callback(err); } callback(null, result); }); } ], callback); }; /** * Gets a service config for a PaySwarm Authority. * * @param host the PaySwarm Authority host and port. * @param path path to the config. * @param options: (optional) * cache: true to cache the response. [true] (optional) * request: options for the request. (optional) * @param callback(err, config) called once the operation completes. */ var _getServiceConfig = function(host, path, options, callback) { if(typeof options === 'function') { callback = options; options = {}; } if(!('cache' in options)) { options.cache = true; } // get config var url = 'https://' + host + path; api.getJsonLd(url, options, callback); }; /** * Gets the service config for a PaySwarm Authority. * * @param host the PaySwarm Authority host and port. * @param options: (optional) * cache: true to cache the response. [true] (optional) * request: options for the request. (optional) * @param callback(err, config) called once the operation completes. */ api.getAuthorityConfig = function(host, options, callback) { return _getServiceConfig(host, '/.well-known/payswarm', options, callback); // TODO: validate result }; /** * Gets the service config for a Web Keys endpoint. * * @param host the Web Keys host and port. * @param options: (optional) * cache: true to cache the response. [true] (optional) * request: options for the request. (optional) * @param callback(err, config) called once the operation completes. */ api.getWebKeysConfig = function(host, options, callback) { return _getServiceConfig(host, '/.well-known/web-keys', options, callback); // TODO: validate result }; /** * Caches a license at the PaySwarm Authority and returns the result. * * @param host the PaySwarm Authority host and port. * @param id the ID of the license to cache. * @param callback(err, result) called once the operation completes. */ api.cacheLicenseAtAuthority = function(host, id, callback) { async.auto({ getConfig: function(callback) { api.getAuthorityConfig(host, callback); }, sign: function(callback) { var msg = { '@context': api.CONTEXT_URL, license: id }; api.sign(msg, callback); }, post: ['getConfig', 'sign', function(callback, results) { var url = results.getConfig.licensesService; var msg = results.sign; api.postJsonLd(url, msg, callback); }], checkLicense: ['post', function(callback, results) { var license = results.post; if(license === null || typeof license !== 'object') { return callback(new Error('[payswarm.cacheLicenseAtAuthority] ' + 'Invalid response when caching license.')); } // FIXME: use JSON-LD exceptions if('message' in license) { return callback(new Error('[payswarm.cacheLicenseAtAuthority] ' + 'Error while caching license: ' + license.message)); } callback(null, license); }] }, function(err, results) { callback(err, results.checkLicense); }); }; /** * Generates a PEM-encoded key pair and stores it by calling the * 'storeKeyPair' hook. * * @param options the options to use. (optional) * [keySize] the size of the key in bits (default: 2048). * @param callback(err, pair) called once the operation completes. */ api.createKeyPair = function(options, callback) { if(typeof options === 'function') { callback = options; options = {}; } var keySize = options.keySize || 2048; var keypair = ursa.generatePrivateKey(keySize, 65537); // get keys in PEM-format var privateKey = keypair.toPrivatePem('utf8'); var publicKey = keypair.toPublicPem('utf8'); if(!('storeKeyPair' in hooks)) { return callback(null, {privateKey: privateKey, publicKey: publicKey}); } // store key pair return hooks.storeKeyPair(publicKey, privateKey, function(err) { if(err) { return callback(err); } callback(null, {privateKey: privateKey, publicKey: publicKey}); }); }; /** * Adds a trusted PaySwarm Authority. Only trusted PaySwarm Authorities can * be used in financial transactions. * * @param host the PaySwarm Authority host and port. * @param callback(err) called once the operation completes. */ api.addTrustedAuthority = function(host, callback) { // get authority config api.getAuthorityConfig(host, function(err, config) { if(err) { return callback(err); } // store authority identity var id = config.authorityIdentity; hooks.storeTrustedAuthority(id, callback); }); }; /** * Get the PaySwarm Authority's vendor registration URL, including the * parameters required to register the vendor. If a key pair does not exist * it will be generated, otherwise the existing key pair will be used unless * overwriteKeyPair is set to true. * * @param host the PaySwarm Authority host and port. * @param registrationCallback the registrationCallback to use. * @param options the options to use: * overwriteKeyPair true to generate a new key-pair even if * there is an existing one. * @param callback(err, url) called once the operation completes. */ api.getRegisterVendorUrl = function( host, registrationCallback, options, callback) { async.auto({ trustedAuthority: function(callback) { // automatically trust given payswarm authority api.addTrustedAuthority(host, callback); }, getRegisterUrl: function(callback) { // get register URL from authority config api.getAuthorityConfig(host, function(err, config) { if(err) { return callback(err); } callback(null, config.vendorRegistrationService); }); }, getPublicKey: function(callback) { // use existing public key if overwrite is not specified if(!options.overwriteKeyPair) { return hooks.getPublicKey(callback); } // no public key available (or overwriting), generate new key pair api.createKeyPair(function(err, pair) { if(err) { return callback(err); } callback(null, pair.publicKey); }); }, createNonce: function(callback) { api.createNonce(callback); } }, function(err, results) { if(err) { return callback(err); } // add query parameters to the register URL var url = api.addQueryVars(results.getRegisterUrl, { 'public-key': results.getPublicKey, 'registration-callback': registrationCallback, 'response-nonce': results.createNonce }); callback(null, url); }); }; /** * Completes the vendor registration process by verifying the response * from the PaySwarm Authority. * * @param msg the JSON-encoded encrypted registration response message. * @param options the options to use. * privateKey the private key to decrypt with, in PEM-encoded format. * @param callback(err, prefs) called once the operation completes. */ api.registerVendor = function(msg, options, callback) { async.auto({ decode: function(callback) { api.decodeAuthorityMessage(msg, options, callback); }, checkMessage: ['decode', function(callback, results) { var prefs = results.decode; if(jsonld.hasValue(prefs, 'type', 'Error')) { return callback(new Error('[payswarm.registerVendor] ' + prefs.errorMessage)); } if(!jsonld.hasValue(prefs, 'type', 'IdentityPreferences')) { return callback(new Error('[payswarm.registerVendor] ' + 'Invalid registration response from PaySwarm Authority.')); } callback(); }], storePublicKeyId: ['checkMessage', function(callback, results) { var prefs = results.decode; hooks.storePublicKeyId(prefs.publicKey, callback); }] }, function(err, results) { if(err) { return callback(err); } callback(null, results.decode); }); }; /** * Get the PaySwarm Authority's purchase URL, including the parameters * identifying the Listing with the Asset to be purchased. * * @param host the PaySwarm Authority host and port. * @param listingId the ID (IRI) for the Listing. * @param listingHash the hash for the Listing. * @param purchaseCallback the callback URL for the purchase result. * @param callback(err, url) called once the operation completes. */ api.getPurchaseUrl = function( host, listingId, listingHash, purchaseCallback, callback) { async.auto({ getPurchaseUrl: function(callback) { // get purchase URL from authority config api.getAuthorityConfig(host, function(err, config) { if(err) { return callback(err); } callback(null, config.paymentService); }); }, createNonce: function(callback) { api.createNonce(callback); } }, function(err, results) { if(err) { return callback(err); } // add query parameters to the register URL var url = api.addQueryVars(results.getPurchaseUrl, { listing: listingId, 'listing-hash': listingHash, callback: purchaseCallback, 'response-nonce': results.createNonce }); callback(null, url); }); }; /** * Performs an automated purchase on behalf of a customer who has previously * authorized it. * * @param listing the listing object containing the asset to purchase. * @param options the options to use. * customer the URL for the identity that is purchasing the asset. * publicKey the URL for the public key associated with the private * key to use to sign the purchase request. * privateKeyPem the private key, in PEM-format, to use to sign * the purchase request. * FIXME: transactionService undocumented -- should this be passed * as an option or retrieved via the customer's PA config? * [source] the URL for the customer's financial account to use to * pay for the asset (this may be omitted if a customer has * previously associated a budget with the vendor that signed * the listing). * [verbose] true if debugging information should be printed to the * console. * [request] options for network requests. * @param callback(err, receipt) called once the operation completes. */ api.purchase = function(listing, options, callback) { // decrypt and verify message async.waterfall([ function(callback) { // frame the listing jsonld.frame(listing, api.FRAMES.Listing, callback); }, function(framedListing, callback) { if(framedListing['@graph'].length === 0) { return callback(new Error('[payswarm.purchase] ' + 'No Listings found.')); } if(framedListing['@graph'].length > 1) { return callback(new Error('[payswarm.purchase] ' + 'More than one Listing found.')); } // extract listing from JSON-LD graph and set @context listing = framedListing['@graph'][0]; // FIXME: validate listing listing['@context'] = api.CONTEXT_URL; callback(); }, function(callback) { api.hash(listing, function(err, hash) { callback(err, hash); }); }, function(hash, callback) { // generate the purchase request var purchaseRequest = { '@context': api.CONTEXT_URL, type: 'PurchaseRequest', identity: options.identity, listing: listing.id, listingHash: hash }; if(options.source) { purchaseRequest.source = options.source; } // sign the purchase request api.sign(purchaseRequest, { publicKeyId: options.publicKey, privateKeyPem: options.privateKeyPem }, callback); }, function(signedPurchaseRequest, callback) { if(options.verbose) { console.log('payswarm.purchase - POSTing purchase request to:', JSON.stringify(options.transactionService, null, 2)); console.log('payswarm.purchase - Purchase Request:', JSON.stringify(signedPurchaseRequest, null, 2)); } // post the purchase request to the transaction service api.postJsonLd( options.transactionService, signedPurchaseRequest, {request: options.request}, callback); } ], callback); }; /** * Completes the purchase process by verifying the response from the PaySwarm * Authority and returning the receipt. * * @param msg the JSON-encoded encrypted purchase response message. * @param options the options to use. * privateKey the private key to decrypt with, in PEM-encoded format. * @param callback(err, receipt) called once the operation completes. */ api.getReceipt = function(msg, options, callback) { async.auto({ decode: function(callback) { api.decodeAuthorityMessage(msg, options, callback); }, checkMessage: ['decode', function(callback, results) { var receipt = results.decode; if(jsonld.hasValue(receipt, 'type', 'Error')) { return callback(new Error('[payswarm.getReceipt] ' + receipt.errorMessage)); } if(!jsonld.hasValue(receipt, 'type', 'Receipt')) { return callback(new Error('[payswarm.getReceipt] ' + 'Invalid purchase response from PaySwarm Authority.')); } callback(); }], validate: ['checkMessage', function(callback, results) { var receipt = results.decode; if(!('contract' in receipt || (typeof receipt.contract !== 'object'))) { return callback(new Error('[payswarm.getReceipt] ' + 'Unknown Receipt format.')); } var contract = receipt.contract; if(!('assetAcquirer' in contract) || !('asset' in contract) || !('license' in contract)) { return callback(new Error('[payswarm.getReceipt] ' + 'Unknown Contract format.')); } callback(); }] }, function(err, results) { if(err) { return callback(err); } callback(null, results.decode); }); }; /** * Add query variables to an existing url. * * @param url the url to add the query vars to. * @param qvars the query variables to add, eg: {foo: 'bar'}. * * @return string the updated url. */ api.addQueryVars = function(url, qvars) { var parsed = URL.parse(url, true); for(var key in qvars) { parsed.query[key] = qvars[key]; } return URL.format(parsed); }; /** * Determines whether or not the given Listing's validity period has passed. * * @param listing the Listing to check. * * @return true if the validity period still applies, false if not. */ api.isListingValid = function(listing) { try { var now = new Date(); var validFrom = Date.parse(listing.validFrom); var validUntil = Date.parse(listing.validUntil); return (now >= validFrom && now <= validUntil); } catch(ex) { return false; } }; /** * Default GET JSON-LD hook. * * @param url The URL of the document to retrieve. * @param options options for request (optional). * @param callback(err, result) called once the operation completes. */ api.defaultGetJsonLd = function(url, options, callback) { if(typeof options === 'function') { callback = options; options = {}; } jsonld.request(url, options, function(err, res, data) { callback(err, data); }); }; /** * Default POST JSON-LD hook. * * @param url the URL. * @param obj the JSON-LD object. * @param options options for request (mutable, optional). * @param callback(err, result) called once the operation completes. */ api.defaultPostJsonLd = function(url, obj, options, callback) { if(typeof options === 'function') { callback = options; options = {}; } // setup options options = options || {}; options.method = 'POST'; options.headers = options.headers || {}; options.headers['Content-Type'] = 'application/ld+json'; options.body = JSON.stringify(obj); jsonld.request(url, options, function(err, res, data) { callback(err, data); }); }; /** * Gets the passed date in W3C format (eg: 2011-03-09T21:55:41Z). * * @param date the date. * * @return the date in W3C format. */ api.w3cDate = function(date) { if(date === undefined || date === null) { date = new Date(); } return util.format('%d-%s-%sT%s:%s:%sZ', date.getUTCFullYear(), _zeroFill2(date.getUTCMonth() + 1), _zeroFill2(date.getUTCDate()), _zeroFill2(date.getUTCHours()), _zeroFill2(date.getUTCMinutes()), _zeroFill2(date.getUTCSeconds())); }; function _zeroFill2(num) { return (num < 10) ? '0' + num : '' + num; } /** Default GET/POST JSON-LD hooks. */ api.addHook('getJsonLd', api.defaultGetJsonLd); api.addHook('postJsonLd', api.defaultPostJsonLd); // JSON-LD document loader var nodeDocumentLoader = jsonld.documentLoaders.node({secure: true}); api.jsonLdDocumentLoader = function(url, callback) { var context = api.CONTEXTS[url]; if(context) { return callback(null, { contextUrl: null, document: {'@context': context}, documentUrl: url }); } nodeDocumentLoader(url, callback); }; jsonld.documentLoader = api.jsonLdDocumentLoader;
lib/payswarm-client.js
/** * A JavaScript implementation of the PaySwarm API. * * @author Dave Longley * * Copyright (c) 2011-2013, Digital Bazaar, Inc. * 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 Digital Bazaar, Inc. nor the names of its 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 HOLDER 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. */ 'use strict'; var async = require('async'); var crypto = require('crypto'); var fs = require('fs'); var jsonld = require('jsonld')(); // get localized jsonld API var mkdirp = require('mkdirp'); var path = require('path'); var URL = require('url'); var ursa = require('ursa'); var util = require('util'); jsonld.use('request'); var api = {}; module.exports = api; /* PAYSWARM CLIENT API ------------------- The PaySwarm Client API allows vendors to register with a PaySwarm Authority, sign listings for the items they wish to sell, and receive payments from their customers. INSTRUCTIONS ------------ First, implement all of the required hooks. Various hooks will be triggered when making calls to the API. Most of the hooks involve providing the API with a custom mechanism for doing HTTP GET/POST and storing/retrieving data from a database. It is also highly recommended that the optional cache hooks be implemented to prevent excessive network traffic when looking up PaySwarm Authority configurations and public keys. To implement a hook, simply write a function that takes the appropriate parameters and returns the appropriate values. Then pass the hook name and the name of the custom function to 'payswarm.addHook'. Look below for the specific hooks that must be implemented. Next, use the API to register as a vendor on the PaySwarm Authority of choice, sign listings, and accept payments via customers' chosen PaySwarm Authorities. First, require this module: var payswarm = require('payswarm'); Then: 1. Add the PaySwarm Authorities that should be trusted by calling: payswarm.addTrustedAuthority('trustedauthority:port'); In this version of the API, any customer's PaySwarm Authority that the vendor would like to do business with must be manually added. The vendor's chosen PaySwarm Authority will be automatically added during the registration step. 2. Register as a vendor by calling: var url = payswarm.getRegisterVendorUrl( 'myauthority:port', 'http://myserver/myregistercallbackurl', callback); The first parameter is the host and port of the PaySwarm Authority to register with. The second is a callback URL that will receive the result of the registration as POST data. Direct the vendor to the URL so that they can complete the registration process. Once the registration process is complete, the vendor's browser will POST the registration result to the callback URL provided. 3. On the callback page, get the POST value 'encrypted-message' and pass it to register the vendor: payswarm.registerVendor( req.body['encrypted-message'], { privateKey: 'your private key in PEM format', }, callback); If no error is given to the callback, registration is complete. The second callback parameter is the PaySwarm Vendor's Preferences, including the Financial Account ID to use in Listings. 5. Create a JSON-LD PaySwarm Asset and Listing. When listing an Asset, its unique hash must be in the Listing. To generate an asset hash call: payswarm.hash(asset, callback); 4. Sign a listing. Create a JSON-LD PaySwarm Listing and then sign it: payswarm.sign(listing, callback); Display the listing information; the use of RDFa is recommended. Depending on the application's needs, it is sometimes a good idea (or a requirement) to regenerate signatures when the vendor's public key is changed. Note: A Listing also contains a License for the Asset. If the application knows the ID (IRI) of the License to use but not the License hash, and it does not have the necessary parser to obtain the License information from its ID, it may use the PaySwarm Authority's license service to cache and retrieve the License by its ID. Then payswarm.hash(license, callback) can be called on the result to produce its hash. 5. When a customer indicates that they want to purchase the Asset in a Listing, call: var url = payswarm.getPurchaseUrl( 'customersauthority:port', listingId, listingHash, 'https://myserver/mypurchasecallbackurl', callback); To get a URL to redirect the customer to their PaySwarm Authority to complete the purchase. The last parameter is a callback URL that will receive the result of the purchase as POST data. If the customer has previously completed a purchase and the response indicated that they set up a budget to handle automated purchases in the future, then an automated purchase can be attempted by calling: payswarm.purchase( 'customersauthority:port', 'https://customersauthority:port/i/customer', listingId, listingHash, callback); In this version of the API, it is the responsibility of the application to determine the customer's PaySwarm Authority (usually by asking). A listing hash can be generated by calling: payswarm.hash(listing, callback); To get the JSON-LD receipt from a purchase, call: payswarm.getReceipt(encryptedMessage, { privateKey: 'your private key in PEM format', }, callback); Where encryptedMessage is either the result of a POST to the purchase callback or the result of the payswarm.purchase() call. The receipt will indicate the ID and hash of the Asset purchased as well as the ID and hash of the License for the Asset. */ // FIXME: ported from PHP, use more nodejs-like idioms, pass 'cache' or // 'store' objects that have interfaces to be implemented, etc. // hook API var hooks = {}; /** * Adds a hook. To add a hook, pass the name of the hook (eg: createNonce) and * the user-defined function name to be called. Hooks are permitted to throw * exceptions as are any PaySwarm client API calls. API calls should be * wrapped in try/catch blocks as appropriate. * * Required protocol hooks: * * createNonce(): Creates and stores a nonce that is to be given to a * PaySwarm Authority so it can be returned in a signed and encrypted * message. * * checkNonce(nonce, callback(err, valid)): Checks a nonce previously created * by createNonce and removes it from storage. Passes true in the callback * if the nonce is valid, false if not. * * Required storage hooks: * * getPublicKey(callback(err, key)): Passes the vendor's public key in PEM * format to the callback. * * getPublicKeyId(callback(err, id)): Passes the ID (IRI) for the vendor's * public key to the callback. * * getPrivateKey(callback(err, key)): Passes the vendor's private key in * PEM format to the callback. * * isTrustedAuthority(id, callback(err, trusted)): Passes true to the * callback if the given identity (IRI) is a trusted PaySwarm Authority, * false if not. * * storeKeyPair(publicPem, privatePem, callback(err)): Stores the vendor's * key pair. * * storePublicKeyId(id, callback(err)): Stores the vendor's public key ID * (IRI). * * storeTrustedAuthority(id, callback(err)): Stores the ID (IRI) of a trusted * PaySwarm Authority. * * Optional retrieval hooks: * * getJsonLd(url, [options,] callback(err, result)): Performs a HTTP GET and * calls a callback with the parsed JSON-LD result object using the * jsonld.request function and options. * * postJsonLd(url, data, [options,] callback(err, result)): Performs a HTTP * POST of the given JSON-LD data and calls a callback with the parsed * JSON-LD result object (if any) using the jsonld.request function and * options. * * Optional cache hooks: * * cacheJsonLd(id, obj, secs, callback(err)): Caches a JSON-LD object. The * ID (IRI) for the object is given and the maxmimum number of seconds to * cache. * * getCachedJsonLd(id, callback(err, result)): Gets a JSON-LD object from * cache. Passes the object or null to the callback. * * @param hook the name of the hook. * @param func the name of the function to call. */ api.addHook = function(hook, func) { hooks[hook] = func; }; /** * Versioned PaySwarm JSON-LD context URLs. */ api.CONTEXT_V1_URL = "https://w3id.org/payswarm/v1"; /** * Default PaySwarm JSON-LD context URL. */ api.CONTEXT_URL = api.CONTEXT_V1_URL; /** * Supported PaySwarm JSON-LD contexts. */ api.CONTEXTS = {}; /** * V1 PaySwarm JSON-LD context. */ api.CONTEXTS[api.CONTEXT_V1_URL] = { // aliases 'id': '@id', 'type': '@type', // prefixes 'ccard': 'https://w3id.org/commerce/creditcard#', 'com': 'https://w3id.org/commerce#', 'dc': 'http://purl.org/dc/terms/', 'foaf': 'http://xmlns.com/foaf/0.1/', 'gr': 'http://purl.org/goodrelations/v1#', 'pto': 'http://www.productontology.org/id/', 'ps': 'https://w3id.org/payswarm#', 'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'rdfs': 'http://www.w3.org/2000/01/rdf-schema#', 'sec': 'https://w3id.org/security#', 'vcard': 'http://www.w3.org/2006/vcard/ns#', 'xsd': 'http://www.w3.org/2001/XMLSchema#', // general 'address': {'@id': 'vcard:adr', '@type': '@id'}, 'comment': 'rdfs:comment', 'countryName': 'vcard:country-name', 'created': {'@id': 'dc:created', '@type': 'xsd:dateTime'}, 'creator': {'@id': 'dc:creator', '@type': '@id'}, 'depiction': {'@id': 'foaf:depiction', '@type': '@id'}, 'description': 'dc:description', 'email': 'foaf:mbox', 'fullName': 'vcard:fn', 'label': 'rdfs:label', 'locality': 'vcard:locality', 'postalCode': 'vcard:postal-code', 'region': 'vcard:region', 'streetAddress': 'vcard:street-address', 'title': 'dc:title', 'website': {'@id': 'foaf:homepage', '@type': '@id'}, 'Address': 'vcard:Address', // bank 'bankAccount': 'bank:account', 'bankAccountType': {'@id': 'bank:accountType', '@type': '@vocab'}, 'bankRoutingNumber': 'bank:routing', 'BankAccount': 'bank:BankAccount', 'Checking': 'bank:Checking', 'Savings': 'bank:Savings', // credit card 'cardBrand': {'@id': 'ccard:brand', '@type': '@vocab'}, 'cardCvm': 'ccard:cvm', 'cardExpMonth': {'@id': 'ccard:expMonth', '@type': 'xsd:integer'}, 'cardExpYear': {'@id': 'ccard:expYear', '@type': 'xsd:integer'}, 'cardNumber': 'ccard:number', 'AmericanExpress': 'ccard:AmericanExpress', 'ChinaUnionPay': 'ccard:ChinaUnionPay', 'CreditCard': 'ccard:CreditCard', 'Discover': 'ccard:Discover', 'Visa': 'ccard:Visa', 'MasterCard': 'ccard:MasterCard', // commerce 'account': {'@id': 'com:account', '@type': '@id'}, 'amount': 'com:amount', 'authorized': {'@id': 'com:authorized', '@type': 'xsd:dateTime'}, 'balance': 'com:balance', 'currency': {'@id': 'com:currency', '@type': '@vocab'}, 'destination': {'@id': 'com:destination', '@type': '@id'}, 'maximumAmount': 'com:maximumAmount', 'maximumPayeeRate': 'com:maximumPayeeRate', 'minimumPayeeRate': 'com:minimumPayeeRate', 'minimumAmount': 'com:minimumAmount', 'payee': {'@id': 'com:payee', '@type': '@id', '@container': '@set'}, 'payeeApplyAfter': {'@id': 'com:payeeApplyAfter', '@container': '@set'}, 'payeeApplyGroup': {'@id': 'com:payeeApplyGroup', '@container': '@set'}, 'payeeApplyType': {'@id': 'com:payeeApplyType', '@type': '@vocab'}, 'payeeGroup': {'@id': 'com:payeeGroup', '@container': '@set'}, 'payeeGroupPrefix': {'@id': 'com:payeeGroupPrefix', '@container': '@set'}, 'payeeExemptGroup': {'@id': 'com:payeeExemptGroup', '@container': '@set'}, 'payeeLimitation': {'@id': 'com:payeeLimitation', '@type': '@vocab'}, 'payeeRate': 'com:payeeRate', 'payeeRateType': {'@id': 'com:payeeRateType', '@type': '@vocab'}, 'payeeRule': {'@id': 'com:payeeRule', '@type': '@id', '@container': '@set'}, 'paymentGateway': 'com:paymentGateway', 'paymentMethod': {'@id': 'com:paymentMethod', '@type': '@vocab'}, 'paymentToken': 'com:paymentToken', 'referenceId': 'com:referenceId', 'settled': {'@id': 'com:settled', '@type': 'xsd:dateTime'}, 'source': {'@id': 'com:source', '@type': '@id'}, 'transfer': {'@id': 'com:transfer', '@type': '@id', '@container': '@set'}, 'vendor': {'@id': 'com:vendor', '@type': '@id'}, 'voided': {'@id': 'com:voided', '@type': 'xsd:dateTime'}, 'ApplyExclusively': 'com:ApplyExclusively', 'ApplyInclusively': 'com:ApplyInclusively', 'FinancialAccount': 'com:Account', 'FlatAmount': 'com:FlatAmount', 'Deposit': 'com:Deposit', 'NoAdditionalPayeesLimitation': 'com:NoAdditionalPayeesLimitation', 'Payee': 'com:Payee', 'PayeeRule': 'com:PayeeRule', 'PayeeScheme': 'com:PayeeScheme', 'PaymentToken': 'com:PaymentToken', 'Percentage': 'com:Percentage', 'Transaction': 'com:Transaction', 'Transfer': 'com:Transfer', 'Withdrawal': 'com:Withdrawal', // currencies 'USD': 'https://w3id.org/currencies/USD', // error // FIXME: add error terms // 'errorMessage': 'err:message' // payswarm 'asset': {'@id': 'ps:asset', '@type': '@id'}, 'assetAcquirer': {'@id': 'ps:assetAcquirer', '@type': '@id'}, // FIXME: support inline content 'assetContent': {'@id': 'ps:assetContent', '@type': '@id'}, 'assetHash': 'ps:assetHash', 'assetProvider': {'@id': 'ps:assetProvider', '@type': '@id'}, 'authority': {'@id': 'ps:authority', '@type': '@id'}, 'contract': {'@id': 'ps:contract', '@type': '@id'}, 'identityHash': 'ps:identityHash', // FIXME: move? 'ipv4Address': 'ps:ipv4Address', 'license': {'@id': 'ps:license', '@type': '@id'}, 'licenseHash': 'ps:licenseHash', 'licenseTemplate': 'ps:licenseTemplate', 'licenseTerms': {'@id': 'ps:licenseTerms', '@type': '@id'}, 'listing': {'@id': 'ps:listing', '@type': '@id'}, 'listingHash': 'ps:listingHash', 'listingRestrictions': {'@id': 'ps:listingRestrictions', '@type': '@id'}, 'preferences': {'@id': 'ps:preferences', '@type': '@vocab'}, 'validFrom': {'@id': 'ps:validFrom', '@type': 'xsd:dateTime'}, 'validUntil': {'@id': 'ps:validUntil', '@type': 'xsd:dateTime'}, 'Asset': 'ps:Asset', 'Budget': 'ps:Budget', 'Contract': 'ps:Contract', 'License': 'ps:License', 'Listing': 'ps:Listing', 'PersonalIdentity': 'ps:PersonalIdentity', 'IdentityPreferences': 'ps:IdentityPreferences', 'Profile': 'ps:Profile', 'PurchaseRequest': 'ps:PurchaseRequest', 'PreAuthorization': 'ps:PreAuthorization', 'Receipt': 'ps:Receipt', 'VendorIdentity': 'ps:VendorIdentity', // security 'cipherAlgorithm': 'sec:cipherAlgorithm', 'cipherData': 'sec:cipherData', 'cipherKey': 'sec:cipherKey', 'digestAlgorithm': 'sec:digestAlgorithm', 'digestValue': 'sec:digestValue', 'expiration': {'@id': 'sec:expiration', '@type': 'xsd:dateTime'}, 'initializationVector': 'sec:initializationVector', 'nonce': 'sec:nonce', 'normalizationAlgorithm': 'sec:normalizationAlgorithm', 'owner': {'@id': 'sec:owner', '@type': '@id'}, 'password': 'sec:password', 'privateKey': {'@id': 'sec:privateKey', '@type': '@id'}, 'privateKeyPem': 'sec:privateKeyPem', 'publicKey': {'@id': 'sec:publicKey', '@type': '@id'}, 'publicKeyPem': 'sec:publicKeyPem', 'publicKeyService': {'@id': 'sec:publicKeyService', '@type': '@id'}, 'revoked': {'@id': 'sec:revoked', '@type': 'xsd:dateTime'}, 'signature': 'sec:signature', 'signatureAlgorithm': 'sec:signatureAlgorithm', 'signatureValue': 'sec:signatureValue', 'EncryptedMessage': 'sec:EncryptedMessage', 'CryptographicKey': 'sec:Key', 'GraphSignature2012': 'sec:GraphSignature2012' }; /** * Default PaySwarm JSON-LD context. */ api.CONTEXT = api.CONTEXTS[api.CONTEXT_URL]; /** * PaySwarm JSON-LD frames. */ api.FRAMES = {}; /** PaySwarm JSON-LD frame for an Asset. */ api.FRAMES.Asset = { '@context': api.CONTEXT_URL, type: 'Asset', creator: {}, signature: {'@embed': true}, assetProvider: {'@embed': false} }; /** PaySwarm JSON-LD frame for a License. */ api.FRAMES.License = { '@context': api.CONTEXT_URL, type: 'License' }; /** PaySwarm JSON-LD frame for a Listing. */ api.FRAMES.Listing = { '@context': api.CONTEXT_URL, type: 'Listing', asset: {'@embed': false}, license: {'@embed': false}, vendor: {'@embed': false}, signature: {'@embed': true} }; /** * Determines the configuration filename based on the given name and * PaySwarm-specific defaults. This method will always return a filename. * * @param configName the name of the config file, which can be null * (the default config), a pathname, or a nickname for a * previously saved configuration file. * @param callback(err, filename) called when the config has been read. */ api.getConfigFilename = function(configName, callback) { if(configName) { // TODO: check if it's a dir (not a file) and error out early? // if configName is an absolute path use it var normalized = path.normalize(configName); if(path.resolve(normalized) === normalized) { return callback(null, configName); } } // establish base config directory var baseConfigDir = path.resolve(process.env.HOME); if(process.env.XDG_CONFIG_HOME) { baseConfigDir = path.resolve(process.env.XDG_CONFIG_HOME); } // if a config name was not given, use the default if(!configName) { var configFilename = path.join( baseConfigDir, '.config', 'payswarm1', 'default'); return callback(null, configFilename); } // if a valid relative file name was given, use that var relativeFile = path.resolve(configName); fs.exists(relativeFile, function(exists) { if(exists) { return callback(null, relativeFile); } // if a config name was given, use that var configFilename = path.join( baseConfigDir, '.config', 'payswarm1', configName); callback(null, configFilename); }); }; /** * Reads configuration information from a file if the file exists, or just * returns an empty configuration object if it doesn't. * * @param configName the name of the config file, which can be a pathname * or a nickname for a saved configuration file. * @param callback(err, config) called when the config has been read. */ api.readConfig = function(configName, callback) { var cfg = {}; async.waterfall([ function(callback) { api.getConfigFilename(configName, callback); }, function(configFilename, callback) { // attempt to read data from the config file fs.exists(configFilename, function(exists) { if(exists) { return fs.readFile(configFilename, 'utf8', callback); } callback(new Error('Config file does not exist: '+ configFilename)); }); }, function(data, callback) { cfg = JSON.parse(data); // add the default context to the object callback(null, cfg); }], function(err) { cfg['@context'] = 'https://w3id.org/payswarm/v1'; callback(err, cfg); }); }; /** * Writes a configuration out to disk. * * @param configName the name of the config file. * @param cfg the configuration object to write. * @param callback(err, configFilename) the callback called when the file is * written to disk. */ api.writeConfig = function(configName, cfg, callback) { async.waterfall([ function(callback) { api.getConfigFilename(configName, callback); }, function(configFilename, callback) { var configDir = path.dirname(configFilename); // if the directory for the config file doesn't exist, create it fs.exists(configDir, function(exists) { if(exists) { callback(null, configFilename); } else { mkdirp(configDir, parseInt(700, 8), function(err) { if(err) { return callback(err); } callback(null, configFilename); }); } }); }, function(configFilename, callback) { // write the data to disk var data = JSON.stringify(cfg, null, 2); fs.writeFile( configFilename, data, {encoding: 'utf8', mode: parseInt(600, 8)}, function(err) { if(err) { return callback(err); } callback(null, configFilename); }); }], callback); }; /** * Retrieves a JSON-LD object over HTTP. * * @param url the URL to HTTP GET. * @param options: (optional) * cache: true to cache the response. [false] (optional) * request: options for the request. (optional) * @param callback(err, result) called once the operation completes. */ api.getJsonLd = function(url, options, callback) { if(typeof options === 'function') { callback = options; options = {}; } options.request = options.request || {}; async.waterfall([ function(callback) { // use cache if available api.getCachedJsonLd(url, callback); }, function(result, callback) { if(result) { return callback(null, result); } // retrieve JSON-LD hooks.getJsonLd(url, options.request, callback); }, function(result, callback) { if(!result) { return callback(new Error('[payswarm.getJsonLd] ' + 'No JSON-LD found at "' + url + '".')); } // FIXME: take into consideration response cache info // cache JSON-LD if(options.cache) { return api.cacheJsonLd(url, result, function(err) { callback(err, result); }); } callback(null, result); } ], callback); }; /** * HTTP POSTs a JSON-LD object. * * @param url the URL to HTTP POST to. * @param obj the JSON-LD object. * @param options: (optional) * request: options for the request. (optional) * @param callback(err, result) called once the operation completes. */ api.postJsonLd = function(url, obj, options, callback) { if(typeof options === 'function') { callback = options; options = {}; } options.request = options.request || {}; async.waterfall([ function(callback) { hooks.postJsonLd(url, obj, options.request, callback); }, function(result, callback) { try { // parse response // FIXME move callback outside of try/catch callback(null, result); } catch(ex) { callback(new Error('[payswarm.postJsonLd] ' + 'Invalid response from "' + url + '"; malformed JSON - ' + ex.toString() + ': ' + JSON.stringify(result, null, 2))); } } ], callback); }; /** * Caches a JSON-LD object if a cache is available. * * @param id the ID of the JSON-LD object. * @param obj the JSON-LD object to cache. * @param callback(err) called once the operation completes. */ api.cacheJsonLd = function(id, obj, callback) { if('cacheJsonLd' in hooks) { return hooks.cacheJsonLd(id, obj, 60*5, callback); } // no cache callback(); }; /** * Gets a cached JSON-LD object if available. * * @param id the ID of the JSON-LD object. * @param callback(err, result) called once the operation completes. */ api.getCachedJsonLd = function(id, callback) { if('getCachedJsonLd' in hooks) { return hooks.getCachedJsonLd(id, callback); } callback(null, null); }; /** * Gets a remote public key. * * @param id the ID for the public key. * @param options: (optional) * cache: true to cache the response. [false] (optional) * request: options for the request. (optional) * @param callback(err, key) called once the operation completes. */ api.getPublicKey = function(id, options, callback) { if(typeof options === 'function') { callback = options; options = {}; } // retrieve public key api.getJsonLd(id, options, function(err, key) { if(err) { return callback(err); } // FIXME: improve validation if(!('publicKeyPem' in key)) { return callback(new Error('[payswarm.getPublicKey] ' + 'Could not get public key. Unknown format.')); } callback(null, key); }); }; /** * Creates a nonce for a secure message. * * @param callback(err, nonce) called once the operation completes. */ api.createNonce = function(callback) { hooks.createNonce(callback); }; /** * Checks the nonce from a secure message. * * @param nonce the nonce. * @param callback(err, valid) called once the operation completes. */ api.checkNonce = function(nonce, callback) { hooks.checkNonce(nonce, callback); }; /** * Generates a hash of the JSON-LD encoded data. * * @param obj the JSON-LD object to hash. * @param callback(err, hash) called once the operation completes. */ api.hash = function(obj, callback) { // SHA-1 hash JSON jsonld.normalize( obj, { format: 'application/nquads' }, function(err, result) { if(err) { return callback(err); } if(result.length === 0) { return callback(new Error('[payswarm.hash] ' + 'The data to hash is empty. This error may be caused because ' + 'a "@context" was not supplied in the input which would cause ' + 'any terms or prefixes to be undefined. ' + 'Input:\n' + JSON.stringify(obj, null, 2))); } var md = crypto.createHash('sha256'); md.update(result, 'utf8'); callback(null, 'urn:sha256:' + md.digest('hex')); }); }; /** * Signs a JSON-LD object, adding a signature field to it. If a signature * date is not provided then the current date will be used. * * @param obj the JSON-LD object to sign. * @param options the signature options. * [nonce] the nonce to use. * [dateTime] the signature creation dateTime as either a W3C formatted * dateTime or a pure JavaScript date object. * publicKeyId URL to the public key that is associated with the * given private key. * privateKey the private key to use in PEM-encoded format. * @param callback(err, signed) called once the operation completes. */ api.sign = function(obj, options, callback) { var nonce = options.nonce || null; var dateTime = options.dateTime || new Date(); var publicKeyId = options.publicKeyId || null; var privateKeyPem = options.privateKeyPem || null; // get W3C-formatted date if(typeof dateTime !== 'string') { dateTime = api.w3cDate(dateTime); } async.auto({ normalize: function(callback) { jsonld.normalize( obj, { format: 'application/nquads' }, callback); }, sign: ['normalize', function(callback, results) { var normalized = results.normalize; if(normalized.length === 0) { return callback(new Error('[payswarm.sign] ' + 'The data to sign is empty. This error may be caused because ' + 'a "@context" was not supplied in the input which would cause ' + 'any terms or prefixes to be undefined. ' + 'Input:\n' + JSON.stringify(obj, null, 2))); } // generate base64-encoded signature var signer = crypto.createSign('RSA-SHA256'); if(nonce !== null) { signer.update(nonce); } signer.update(dateTime); signer.update(normalized); var signature = signer.sign(privateKeyPem, 'base64'); callback(null, signature); }] }, function(err, results) { if(err) { return callback(err); } // create signature info var signature = { type: 'GraphSignature2012', creator: publicKeyId, created: dateTime, signatureValue: results.sign }; if(nonce !== null) { signature.nonce = nonce; } // FIXME: support multiple signatures obj.signature = signature; jsonld.addValue(obj, '@context', api.CONTEXT_URL, {allowDuplicate: false}); callback(null, obj); }); }; /** * Verifies a JSON-LD digitally-signed object. * * @param obj the JSON-LD object to verify. * @param options: (optional) * request: options for the key request. (optional) * checkTimestamp: check signature timestamp [true] (optional) * maxTimestampDelta: signature must be created within a window of this * many seconds [15 minutes] (optional) * @param callback(err) called once the operation completes. */ api.verify = function(obj, options, callback) { if(typeof options === 'function') { callback = options; options = {}; } if(!('checkTimestamp' in options)) { options.checkTimestamp = true; } if(!('maxTimestampDelta' in options)) { options.maxTimestampDelta = 15 * 60; } async.auto({ // FIXME: add support for multiple signatures // : for many signers of an object, can just check all sigs // : for signed sigs, need to recurse? // FIXME: add support for different signature types // : frame with signatures to get types, then reframe to get // : correct structure for each type. frame: function(callback) { // frame message to retrieve signature var frame = { '@context': api.CONTEXT_URL, signature: { type: {}, created: {}, creator: {}, signatureValue: {}, // FIXME: improve handling signatures w/o nonces //nonce: {'@omitDefault': true} } }; jsonld.frame(obj, frame, function(err, framed) { if(err) { return callback(err); } var graphs = framed['@graph']; if(graphs.length === 0) { return callback(new Error('[payswarm.verify] ' + 'No signed data found.')); } if(graphs.length > 1) { return callback(new Error('[payswarm.verify] ' + 'More than one signed graph found.')); } var graph = graphs[0]; // copy the top level framed data context graph['@context'] = framed['@context']; var signature = graph.signature; if(!signature) { return callback(new Error('[payswarm.verify] ' + 'Valid signature not found.')); } if(signature.type !== 'GraphSignature2012') { return callback(new Error('[payswarm.verify] ' + 'Unknown signature type found.')); } callback(null, graph); }); }, checkNonce: ['frame', function(callback, results) { var signature = results.frame.signature; if('nonce' in signature) { return api.checkNonce(signature.nonce, function(err, valid) { if(err) { return callback(err); } if(!valid) { return callback(new Error('[payswarm.verify] ' + 'The message nonce is invalid.')); } callback(); }); } callback(); }], checkDate: ['frame', function(callback, results) { if(!options.checkTimestamp) { return callback(); } // ensure signature timestamp within a valid range var now = +new Date(); var delta = options.maxTimestampDelta * 1000; try { var signature = results.frame.signature; var created = +Date.parse(signature.created); if(created < (now - delta) || created > (now + delta)) { throw new Error('[payswarm.verify] ' + 'The message digital signature timestamp is out of range.'); } } catch(ex) { callback(ex); } }], getPublicKey: ['frame', function(callback, results) { var signature = results.frame.signature; api.getPublicKey(signature.creator, options, callback); }], verifyPublicKeyOwner: ['getPublicKey', function(callback, results) { if(!('isTrustedAuthority' in hooks)) { return callback(); } var key = results.getPublicKey; hooks.isTrustedAuthority(key.owner, function(err, trusted) { if(err) { return callback(err); } if(!trusted) { return callback(new Error('[payswarm.verify] ' + 'The message is not signed by a trusted public key.')); } callback(); }); }], normalize: ['checkNonce', 'checkDate', 'verifyPublicKeyOwner', function(callback, results) { // remove signature property from object var result = results.frame; var signature = result.signature; delete result.signature; jsonld.normalize( result, { format: 'application/nquads' }, function(err, normalized) { if(err) { return callback(err); } callback(null, {data: normalized, signature: signature}); }); }], verifySignature: ['normalize', function(callback, results) { // ensure key has not been revoked var key = results.getPublicKey; var signature = results.normalize.signature; if('revoked' in key) { return callback(new Error('[payswarm.verify] ' + 'The public key has been revoked.')); } var verifier = crypto.createVerify('RSA-SHA256'); if('nonce' in signature) { verifier.update(signature.nonce); } verifier.update(signature.created); verifier.update(results.normalize.data); var verified = verifier.verify( key.publicKeyPem, signature.signatureValue, 'base64'); if(!verified) { return callback(new Error('[payswarm.verify] ' + 'The digital signature on the message is invalid.')); } callback(); }] }, callback); }; /** * Decrypts an encrypted JSON-LD object. * * @param encrypted the message to decrypt. * @param options the options to use. * privateKey the private key to decrypt with, in PEM-encoded format. * @param callback(err, result) called once the operation completes. */ api.decrypt = function(encrypted, options, callback) { if(encrypted.cipherAlgorithm !== 'rsa-sha256-aes-128-cbc') { var algorithm = encrypted.cipherAlgorithm; return callback(new Error('[payswarm.decrypt] ' + 'Unknown encryption algorithm "' + algorithm + '"')); } try { // private key decrypt key and IV var pk = ursa.createPrivateKey(options.privateKey, 'utf8'); var key = pk.decrypt( encrypted.cipherKey, 'base64', 'binary', ursa.RSA_PKCS1_OAEP_PADDING); var iv = pk.decrypt( encrypted.initializationVector, 'base64', 'binary', ursa.RSA_PKCS1_OAEP_PADDING); // symmetric decrypt data var decipher = crypto.createDecipheriv('aes-128-cbc', key, iv); var decrypted = decipher.update(encrypted.cipherData, 'base64', 'utf8'); decrypted += decipher.final('utf8'); // return parsed result var result = JSON.parse(decrypted); callback(null, result); } catch(ex) { callback(new Error('[payswarm.decrypt] ' + 'Failed to decrypt the encrypted message: ' + ex.toString())); } }; /** * Decodes a JSON-encoded, encrypted, digitally-signed message from a * PaySwarm Authority. * * @param msg the json-encoded message to verify. * @param options the options to use. * privateKey the private key to decrypt with, in PEM-encoded format. * @param callback(err, result) called once the operation completes. */ api.decodeAuthorityMessage = function(msg, options, callback) { try { // convert message from json msg = JSON.parse(msg); } catch(ex) { return callback(new Error('[payswarm.decodeAuthorityMessage] ' + 'The message contains malformed JSON.')); } // decrypt and verify message async.waterfall([ function(callback) { api.decrypt(msg, options, callback); }, function(result, callback) { api.verify(result, function(err) { if(err) { return callback(err); } callback(null, result); }); } ], callback); }; /** * Gets a service config for a PaySwarm Authority. * * @param host the PaySwarm Authority host and port. * @param path path to the config. * @param options: (optional) * cache: true to cache the response. [true] (optional) * request: options for the request. (optional) * @param callback(err, config) called once the operation completes. */ var _getServiceConfig = function(host, path, options, callback) { if(typeof options === 'function') { callback = options; options = {}; } if(!('cache' in options)) { options.cache = true; } // get config var url = 'https://' + host + path; api.getJsonLd(url, options, callback); }; /** * Gets the service config for a PaySwarm Authority. * * @param host the PaySwarm Authority host and port. * @param options: (optional) * cache: true to cache the response. [true] (optional) * request: options for the request. (optional) * @param callback(err, config) called once the operation completes. */ api.getAuthorityConfig = function(host, options, callback) { return _getServiceConfig(host, '/.well-known/payswarm', options, callback); // TODO: validate result }; /** * Gets the service config for a Web Keys endpoint. * * @param host the Web Keys host and port. * @param options: (optional) * cache: true to cache the response. [true] (optional) * request: options for the request. (optional) * @param callback(err, config) called once the operation completes. */ api.getWebKeysConfig = function(host, options, callback) { return _getServiceConfig(host, '/.well-known/web-keys', options, callback); // TODO: validate result }; /** * Caches a license at the PaySwarm Authority and returns the result. * * @param host the PaySwarm Authority host and port. * @param id the ID of the license to cache. * @param callback(err, result) called once the operation completes. */ api.cacheLicenseAtAuthority = function(host, id, callback) { async.auto({ getConfig: function(callback) { api.getAuthorityConfig(host, callback); }, sign: function(callback) { var msg = { '@context': api.CONTEXT_URL, license: id }; api.sign(msg, callback); }, post: ['getConfig', 'sign', function(callback, results) { var url = results.getConfig.licensesService; var msg = results.sign; api.postJsonLd(url, msg, callback); }], checkLicense: ['post', function(callback, results) { var license = results.post; if(license === null || typeof license !== 'object') { return callback(new Error('[payswarm.cacheLicenseAtAuthority] ' + 'Invalid response when caching license.')); } // FIXME: use JSON-LD exceptions if('message' in license) { return callback(new Error('[payswarm.cacheLicenseAtAuthority] ' + 'Error while caching license: ' + license.message)); } callback(null, license); }] }, function(err, results) { callback(err, results.checkLicense); }); }; /** * Generates a PEM-encoded key pair and stores it by calling the * 'storeKeyPair' hook. * * @param options the options to use. (optional) * [keySize] the size of the key in bits (default: 2048). * @param callback(err, pair) called once the operation completes. */ api.createKeyPair = function(options, callback) { if(typeof options === 'function') { callback = options; options = {}; } var keySize = options.keySize || 2048; var keypair = ursa.generatePrivateKey(keySize, 65537); // get keys in PEM-format var privateKey = keypair.toPrivatePem('utf8'); var publicKey = keypair.toPublicPem('utf8'); if(!('storeKeyPair' in hooks)) { return callback(null, {privateKey: privateKey, publicKey: publicKey}); } // store key pair return hooks.storeKeyPair(publicKey, privateKey, function(err) { if(err) { return callback(err); } callback(null, {privateKey: privateKey, publicKey: publicKey}); }); }; /** * Adds a trusted PaySwarm Authority. Only trusted PaySwarm Authorities can * be used in financial transactions. * * @param host the PaySwarm Authority host and port. * @param callback(err) called once the operation completes. */ api.addTrustedAuthority = function(host, callback) { // get authority config api.getAuthorityConfig(host, function(err, config) { if(err) { return callback(err); } // store authority identity var id = config.authorityIdentity; hooks.storeTrustedAuthority(id, callback); }); }; /** * Get the PaySwarm Authority's vendor registration URL, including the * parameters required to register the vendor. If a key pair does not exist * it will be generated, otherwise the existing key pair will be used unless * overwriteKeyPair is set to true. * * @param host the PaySwarm Authority host and port. * @param registrationCallback the registrationCallback to use. * @param options the options to use: * overwriteKeyPair true to generate a new key-pair even if * there is an existing one. * @param callback(err, url) called once the operation completes. */ api.getRegisterVendorUrl = function( host, registrationCallback, options, callback) { async.auto({ trustedAuthority: function(callback) { // automatically trust given payswarm authority api.addTrustedAuthority(host, callback); }, getRegisterUrl: function(callback) { // get register URL from authority config api.getAuthorityConfig(host, function(err, config) { if(err) { return callback(err); } callback(null, config.vendorRegistrationService); }); }, getPublicKey: function(callback) { // use existing public key if overwrite is not specified if(!options.overwriteKeyPair) { return hooks.getPublicKey(callback); } // no public key available (or overwriting), generate new key pair api.createKeyPair(function(err, pair) { if(err) { return callback(err); } callback(null, pair.publicKey); }); }, createNonce: function(callback) { api.createNonce(callback); } }, function(err, results) { if(err) { return callback(err); } // add query parameters to the register URL var url = api.addQueryVars(results.getRegisterUrl, { 'public-key': results.getPublicKey, 'registration-callback': registrationCallback, 'response-nonce': results.createNonce }); callback(null, url); }); }; /** * Completes the vendor registration process by verifying the response * from the PaySwarm Authority. * * @param msg the JSON-encoded encrypted registration response message. * @param options the options to use. * privateKey the private key to decrypt with, in PEM-encoded format. * @param callback(err, prefs) called once the operation completes. */ api.registerVendor = function(msg, options, callback) { async.auto({ decode: function(callback) { api.decodeAuthorityMessage(msg, options, callback); }, checkMessage: ['decode', function(callback, results) { var prefs = results.decode; if(jsonld.hasValue(prefs, 'type', 'Error')) { return callback(new Error('[payswarm.registerVendor] ' + prefs.errorMessage)); } if(!jsonld.hasValue(prefs, 'type', 'IdentityPreferences')) { return callback(new Error('[payswarm.registerVendor] ' + 'Invalid registration response from PaySwarm Authority.')); } callback(); }], storePublicKeyId: ['checkMessage', function(callback, results) { var prefs = results.decode; hooks.storePublicKeyId(prefs.publicKey, callback); }] }, function(err, results) { if(err) { return callback(err); } callback(null, results.decode); }); }; /** * Get the PaySwarm Authority's purchase URL, including the parameters * identifying the Listing with the Asset to be purchased. * * @param host the PaySwarm Authority host and port. * @param listingId the ID (IRI) for the Listing. * @param listingHash the hash for the Listing. * @param purchaseCallback the callback URL for the purchase result. * @param callback(err, url) called once the operation completes. */ api.getPurchaseUrl = function( host, listingId, listingHash, purchaseCallback, callback) { async.auto({ getPurchaseUrl: function(callback) { // get purchase URL from authority config api.getAuthorityConfig(host, function(err, config) { if(err) { return callback(err); } callback(null, config.paymentService); }); }, createNonce: function(callback) { api.createNonce(callback); } }, function(err, results) { if(err) { return callback(err); } // add query parameters to the register URL var url = api.addQueryVars(results.getPurchaseUrl, { listing: listingId, 'listing-hash': listingHash, callback: purchaseCallback, 'response-nonce': results.createNonce }); callback(null, url); }); }; /** * Performs an automated purchase on behalf of a customer who has previously * authorized it. * * @param listing the listing object containing the asset to purchase. * @param options the options to use. * customer the URL for the identity that is purchasing the asset. * publicKey the URL for the public key associated with the private * key to use to sign the purchase request. * privateKeyPem the private key, in PEM-format, to use to sign * the purchase request. * FIXME: transactionService undocumented -- should this be passed * as an option or retrieved via the customer's PA config? * [source] the URL for the customer's financial account to use to * pay for the asset (this may be omitted if a customer has * previously associated a budget with the vendor that signed * the listing). * [verbose] true if debugging information should be printed to the * console. * [request] options for network requests. * @param callback(err, receipt) called once the operation completes. */ api.purchase = function(listing, options, callback) { // decrypt and verify message async.waterfall([ function(callback) { // frame the listing jsonld.frame(listing, api.FRAMES.Listing, callback); }, function(framedListing, callback) { if(framedListing['@graph'].length === 0) { return callback(new Error('[payswarm.purchase] ' + 'No Listings found.')); } if(framedListing['@graph'].length > 1) { return callback(new Error('[payswarm.purchase] ' + 'More than one Listing found.')); } // extract listing from JSON-LD graph and set @context listing = framedListing['@graph'][0]; // FIXME: validate listing listing['@context'] = api.CONTEXT_URL; callback(); }, function(callback) { api.hash(listing, function(err, hash) { callback(err, hash); }); }, function(hash, callback) { // generate the purchase request var purchaseRequest = { '@context': api.CONTEXT_URL, type: 'PurchaseRequest', identity: options.identity, listing: listing.id, listingHash: hash }; if(options.source) { purchaseRequest.source = options.source; } // sign the purchase request api.sign(purchaseRequest, { publicKeyId: options.publicKey, privateKeyPem: options.privateKeyPem }, callback); }, function(signedPurchaseRequest, callback) { if(options.verbose) { console.log('payswarm.purchase - POSTing purchase request to:', JSON.stringify(options.transactionService, null, 2)); console.log('payswarm.purchase - Purchase Request:', JSON.stringify(signedPurchaseRequest, null, 2)); } // post the purchase request to the transaction service api.postJsonLd( options.transactionService, signedPurchaseRequest, {request: options.request}, callback); } ], callback); }; /** * Completes the purchase process by verifying the response from the PaySwarm * Authority and returning the receipt. * * @param msg the JSON-encoded encrypted purchase response message. * @param options the options to use. * privateKey the private key to decrypt with, in PEM-encoded format. * @param callback(err, receipt) called once the operation completes. */ api.getReceipt = function(msg, options, callback) { async.auto({ decode: function(callback) { api.decodeAuthorityMessage(msg, options, callback); }, checkMessage: ['decode', function(callback, results) { var receipt = results.decode; if(jsonld.hasValue(receipt, 'type', 'Error')) { return callback(new Error('[payswarm.getReceipt] ' + receipt.errorMessage)); } if(!jsonld.hasValue(receipt, 'type', 'Receipt')) { return callback(new Error('[payswarm.getReceipt] ' + 'Invalid purchase response from PaySwarm Authority.')); } callback(); }], validate: ['checkMessage', function(callback, results) { var receipt = results.decode; if(!('contract' in receipt || (typeof receipt.contract !== 'object'))) { return callback(new Error('[payswarm.getReceipt] ' + 'Unknown Receipt format.')); } var contract = receipt.contract; if(!('assetAcquirer' in contract) || !('asset' in contract) || !('license' in contract)) { return callback(new Error('[payswarm.getReceipt] ' + 'Unknown Contract format.')); } callback(); }] }, function(err, results) { if(err) { return callback(err); } callback(null, results.decode); }); }; /** * Add query variables to an existing url. * * @param url the url to add the query vars to. * @param qvars the query variables to add, eg: {foo: 'bar'}. * * @return string the updated url. */ api.addQueryVars = function(url, qvars) { var parsed = URL.parse(url, true); for(var key in qvars) { parsed.query[key] = qvars[key]; } return URL.format(parsed); }; /** * Determines whether or not the given Listing's validity period has passed. * * @param listing the Listing to check. * * @return true if the validity period still applies, false if not. */ api.isListingValid = function(listing) { try { var now = new Date(); var validFrom = Date.parse(listing.validFrom); var validUntil = Date.parse(listing.validUntil); return (now >= validFrom && now <= validUntil); } catch(ex) { return false; } }; /** * Default GET JSON-LD hook. * * @param url The URL of the document to retrieve. * @param options options for request (optional). * @param callback(err, result) called once the operation completes. */ api.defaultGetJsonLd = function(url, options, callback) { if(typeof options === 'function') { callback = options; options = {}; } jsonld.request(url, options, function(err, res, data) { callback(err, data); }); }; /** * Default POST JSON-LD hook. * * @param url the URL. * @param obj the JSON-LD object. * @param options options for request (mutable, optional). * @param callback(err, result) called once the operation completes. */ api.defaultPostJsonLd = function(url, obj, options, callback) { if(typeof options === 'function') { callback = options; options = {}; } // setup options options = options || {}; options.method = 'POST'; options.headers = options.headers || {}; options.headers['Content-Type'] = 'application/ld+json'; options.body = JSON.stringify(obj); jsonld.request(url, options, function(err, res, data) { callback(err, data); }); }; /** * Gets the passed date in W3C format (eg: 2011-03-09T21:55:41Z). * * @param date the date. * * @return the date in W3C format. */ api.w3cDate = function(date) { if(date === undefined || date === null) { date = new Date(); } return util.format('%d-%s-%sT%s:%s:%sZ', date.getUTCFullYear(), _zeroFill2(date.getUTCMonth() + 1), _zeroFill2(date.getUTCDate()), _zeroFill2(date.getUTCHours()), _zeroFill2(date.getUTCMinutes()), _zeroFill2(date.getUTCSeconds())); }; function _zeroFill2(num) { return (num < 10) ? '0' + num : '' + num; } /** Default GET/POST JSON-LD hooks. */ api.addHook('getJsonLd', api.defaultGetJsonLd); api.addHook('postJsonLd', api.defaultPostJsonLd); // JSON-LD document loader var nodeDocumentLoader = jsonld.documentLoaders.node({secure: true}); api.jsonLdDocumentLoader = function(url, callback) { var context = api.CONTEXTS[url]; if(context) { return callback(null, { contextUrl: null, document: {'@context': context}, documentUrl: url }); } nodeDocumentLoader(url, callback); }; jsonld.documentLoader = api.jsonLdDocumentLoader;
[lib] Minor formatting fix.
lib/payswarm-client.js
[lib] Minor formatting fix.
<ide><path>ib/payswarm-client.js <ide> <ide> jsonld.normalize( <ide> result, { <del> format: 'application/nquads' <del> }, function(err, normalized) { <add> format: 'application/nquads' <add> }, function(err, normalized) { <ide> if(err) { <ide> return callback(err); <ide> } <ide> callback(null, {data: normalized, signature: signature}); <del> }); <add> }); <ide> }], <ide> verifySignature: ['normalize', function(callback, results) { <ide> // ensure key has not been revoked
Java
mit
f41fa6075dc1317ba66df13e139c5c7ca20a5381
0
FranckCo/Metadata-API
package fr.insee.rmes.api.geo; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.List; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import fr.insee.rmes.api.AbstractMetadataApi; import fr.insee.rmes.modeles.geo.EnumTypeGeographie; import fr.insee.rmes.modeles.geo.territoire.Projection; import fr.insee.rmes.modeles.geo.territoire.Territoire; import fr.insee.rmes.modeles.geo.territoires.Projections; import fr.insee.rmes.queries.geo.CsvGeoUtils; import fr.insee.rmes.utils.Constants; import fr.insee.rmes.utils.DateUtils; public abstract class AbstractGeoApi extends AbstractMetadataApi { protected static final String LITTERAL_PARAMETER_DATE_WITH_HISTORY = ". Le paramètre '*' permet de renvoyer tout l'historique."; protected CsvGeoUtils csvGeoUtils = new CsvGeoUtils(); private static Logger logger = LogManager.getLogger(AbstractGeoApi.class); // Method to find a territoire object protected Response generateResponseATerritoireByCode(String csvResult, String header, Territoire territoire) { territoire = (Territoire) csvUtils.populatePOJO(csvResult, territoire); return this .generateStatusResponse( ! StringUtils.isEmpty(territoire.getUri()), territoire, this.getFirstValidHeader(header)); } // Method to find a list of territoires protected Response generateResponseListOfTerritoire( String csvResult, String header, Class<?> rootClass, Class<? extends Territoire> classObject) { List<? extends Territoire> listeTerritoires = csvUtils.populateMultiPOJO(csvResult, classObject); return this.generateListStatusResponse(rootClass, listeTerritoires, this.getFirstValidHeader(header)); } protected boolean verifyParametersTypeAndDateAreValid(String typeTerritoire, String date) { return (this.verifyParameterTypeTerritoireIsRight(typeTerritoire)) && (this.verifyParameterDateIsRightWithoutHistory(date)); } protected boolean verifyParameterTypeTerritoireIsRight(String typeTerritoire) { return (typeTerritoire == null) || (EnumTypeGeographie .streamValuesTypeGeo() .anyMatch(s -> s.getTypeObjetGeo().equalsIgnoreCase(typeTerritoire))); } protected String formatValidParametertypeTerritoireIfIsNull(String typeTerritoire) { return (typeTerritoire != null) ? EnumTypeGeographie.getTypeObjetGeoIgnoreCase(typeTerritoire) : Constants.NONE; } private boolean verifyParameterDateIsRight(String date, boolean withHistory) { return (date == null) || (DateUtils.isValidDate(date)) || (withHistory && date.equals("*")); } protected boolean verifyParameterDateIsRightWithoutHistory(String date) { return this.verifyParameterDateIsRight(date, false); } protected boolean verifyParameterDateIsRightWithHistory(String date) { return this.verifyParameterDateIsRight(date, true); } protected String formatValidParameterDateIfIsNull(String date) { return (date != null) ? date : DateUtils.getDateTodayStringFormat(); } protected String formatValidParameterFiltreIfIsNull(String filtreNom) { return (filtreNom != null) ? filtreNom : "*"; } protected boolean formatValidParameterBooleanIfIsNull(Boolean bool) { return bool != null && bool; } protected Response generateStatusResponse(boolean objectIsFound, Object o, String header) { if (objectIsFound) { return Response.ok(responseUtils.produceResponse(o, header)).build(); } else { return Response.status(Status.NOT_FOUND).entity("").build(); } } /** * @param listObject : for XML, pojo containing a list * @param o : for JSON, list of pojo * @param header * @return */ protected Response generateListStatusResponse(Class<?> listObject, List<?> o, String header) { if (o.isEmpty()) { return Response.status(Status.NOT_FOUND).entity("").build(); } else if (StringUtils.equalsAnyIgnoreCase(header, MediaType.APPLICATION_XML)) { Constructor<?> constructor; Object sampleObject = null; try { constructor = listObject.getConstructor(List.class); sampleObject = constructor.newInstance(o); } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { logger.error(e.getMessage()); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("").build(); } return Response.ok(responseUtils.produceResponse(sampleObject, header)).build(); } else if (StringUtils.equalsAnyIgnoreCase(header, MediaType.APPLICATION_JSON)) { return Response.ok(responseUtils.produceResponse(o, header)).build(); } else { return Response.status(Status.NOT_ACCEPTABLE).entity("").build(); } } protected Response generateBadRequestResponse() { return Response.status(Status.BAD_REQUEST).entity("").build(); } // Method to find a list of projections protected Response generateResponseListOfProjection(String csvResult, String header) { List<Projection> listProj = csvGeoUtils.populateProjections(csvResult); return this.generateListStatusResponse(Projections.class, listProj, this.getFirstValidHeader(header)); } }
src/main/java/fr/insee/rmes/api/geo/AbstractGeoApi.java
package fr.insee.rmes.api.geo; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.List; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import fr.insee.rmes.api.AbstractMetadataApi; import fr.insee.rmes.modeles.geo.EnumTypeGeographie; import fr.insee.rmes.modeles.geo.territoire.Projection; import fr.insee.rmes.modeles.geo.territoire.Territoire; import fr.insee.rmes.modeles.geo.territoires.Projections; import fr.insee.rmes.queries.geo.CsvGeoUtils; import fr.insee.rmes.utils.Constants; import fr.insee.rmes.utils.DateUtils; public abstract class AbstractGeoApi extends AbstractMetadataApi { protected static final String LITTERAL_PARAMETER_DATE_WITH_HISTORY = ". Le paramètre '*' permet de renvoyer tout l'historique."; protected CsvGeoUtils csvGeoUtils = new CsvGeoUtils(); private static Logger logger = LogManager.getLogger(AbstractGeoApi.class); // Method to find a territoire object protected Response generateResponseATerritoireByCode(String csvResult, String header, Territoire territoire) { territoire = (Territoire) csvUtils.populatePOJO(csvResult, territoire); return this .generateStatusResponse( ! StringUtils.isEmpty(territoire.getUri()), territoire, this.getFirstValidHeader(header)); } // Method to find a list of territoires protected Response generateResponseListOfTerritoire( String csvResult, String header, Class<?> rootClass, Class<? extends Territoire> classObject) { List<? extends Territoire> listeTerritoires = csvUtils.populateMultiPOJO(csvResult, classObject); return this.generateListStatusResponse(rootClass, listeTerritoires, this.getFirstValidHeader(header)); } protected boolean verifyParametersTypeAndDateAreValid(String typeTerritoire, String date) { return (this.verifyParameterTypeTerritoireIsRight(typeTerritoire)) && (this.verifyParameterDateIsRightWithoutHistory(date)); } protected boolean verifyParameterTypeTerritoireIsRight(String typeTerritoire) { return (typeTerritoire == null) || (EnumTypeGeographie .streamValuesTypeGeo() .anyMatch(s -> s.getTypeObjetGeo().equalsIgnoreCase(typeTerritoire))); } protected String formatValidParametertypeTerritoireIfIsNull(String typeTerritoire) { return (typeTerritoire != null) ? EnumTypeGeographie.getTypeObjetGeoIgnoreCase(typeTerritoire) : Constants.NONE; } private boolean verifyParameterDateIsRight(String date, boolean withHistory) { return (date == null) || (DateUtils.isValidDate(date)) || (withHistory && date.equals("*")); } protected boolean verifyParameterDateIsRightWithoutHistory(String date) { return this.verifyParameterDateIsRight(date, false); } protected boolean verifyParameterDateIsRightWithHistory(String date) { return this.verifyParameterDateIsRight(date, true); } protected String formatValidParameterDateIfIsNull(String date) { return (date != null) ? date : DateUtils.getDateTodayStringFormat(); } protected String formatValidParameterFiltreIfIsNull(String filtreNom) { return (filtreNom != null) ? filtreNom : "*"; } protected Boolean formatValidParameterBooleanIfIsNull(Boolean bool) { return bool != null; } protected Response generateStatusResponse(boolean objectIsFound, Object o, String header) { if (objectIsFound) { return Response.ok(responseUtils.produceResponse(o, header)).build(); } else { return Response.status(Status.NOT_FOUND).entity("").build(); } } /** * @param listObject : for XML, pojo containing a list * @param o : for JSON, list of pojo * @param header * @return */ protected Response generateListStatusResponse(Class<?> listObject, List<?> o, String header) { if (o.isEmpty()) { return Response.status(Status.NOT_FOUND).entity("").build(); } else if (StringUtils.equalsAnyIgnoreCase(header, MediaType.APPLICATION_XML)) { Constructor<?> constructor; Object sampleObject = null; try { constructor = listObject.getConstructor(List.class); sampleObject = constructor.newInstance(o); } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { logger.error(e.getMessage()); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("").build(); } return Response.ok(responseUtils.produceResponse(sampleObject, header)).build(); } else if (StringUtils.equalsAnyIgnoreCase(header, MediaType.APPLICATION_JSON)) { return Response.ok(responseUtils.produceResponse(o, header)).build(); } else { return Response.status(Status.NOT_ACCEPTABLE).entity("").build(); } } protected Response generateBadRequestResponse() { return Response.status(Status.BAD_REQUEST).entity("").build(); } // Method to find a list of projections protected Response generateResponseListOfProjection(String csvResult, String header) { List<Projection> listProj = csvGeoUtils.populateProjections(csvResult); return this.generateListStatusResponse(Projections.class, listProj, this.getFirstValidHeader(header)); } }
Fix wrong cache disabling when using GET /geo/communes
src/main/java/fr/insee/rmes/api/geo/AbstractGeoApi.java
Fix wrong cache disabling when using GET /geo/communes
<ide><path>rc/main/java/fr/insee/rmes/api/geo/AbstractGeoApi.java <ide> return (filtreNom != null) ? filtreNom : "*"; <ide> } <ide> <del> protected Boolean formatValidParameterBooleanIfIsNull(Boolean bool) { <del> return bool != null; <add> protected boolean formatValidParameterBooleanIfIsNull(Boolean bool) { <add> return bool != null && bool; <ide> } <ide> <ide>
Java
apache-2.0
a02a8d231915fcfd1603d3161f3300e8ae5dd6d1
0
Sage-Bionetworks/BridgePF,DwayneJengSage/BridgePF,alxdarksage/BridgePF,Sage-Bionetworks/BridgePF,alxdarksage/BridgePF,DwayneJengSage/BridgePF,DwayneJengSage/BridgePF,alxdarksage/BridgePF,Sage-Bionetworks/BridgePF
package org.sagebionetworks.bridge.dynamodb; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import javax.annotation.Resource; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.sagebionetworks.bridge.models.studies.StudyIdentifier; import org.sagebionetworks.bridge.models.studies.StudyIdentifierImpl; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @ContextConfiguration("classpath:test-context.xml") @RunWith(SpringJUnit4ClassRunner.class) public class DynamoUserConsentDaoTest { private static final String HEALTH_CODE = "hc789"; private static final StudyIdentifier STUDY_IDENTIFIER = new StudyIdentifierImpl("study123"); @Resource private DynamoUserConsentDao userConsentDao; @Before public void before() { DynamoInitializer.init(DynamoUserConsent2.class); DynamoTestUtil.clearTable(DynamoUserConsent2.class); } @After public void after() { DynamoTestUtil.clearTable(DynamoUserConsent2.class); } @Test public void canConsentToStudy() { // Not consented yet final DynamoStudyConsent1 consent = createStudyConsent(); assertFalse(userConsentDao.hasConsented(HEALTH_CODE, new StudyIdentifierImpl(consent.getStudyKey()))); // Give consent userConsentDao.giveConsent(HEALTH_CODE, consent); assertTrue(userConsentDao.hasConsented(HEALTH_CODE, new StudyIdentifierImpl(consent.getStudyKey()))); // Withdraw userConsentDao.withdrawConsent(HEALTH_CODE, STUDY_IDENTIFIER); assertFalse(userConsentDao.hasConsented(HEALTH_CODE, new StudyIdentifierImpl(consent.getStudyKey()))); // Can give consent again if the previous consent is withdrawn userConsentDao.giveConsent(HEALTH_CODE, consent); assertTrue(userConsentDao.hasConsented(HEALTH_CODE, new StudyIdentifierImpl(consent.getStudyKey()))); // Withdraw again userConsentDao.withdrawConsent(HEALTH_CODE, STUDY_IDENTIFIER); assertFalse(userConsentDao.hasConsented(HEALTH_CODE, new StudyIdentifierImpl(consent.getStudyKey()))); } @Test public void canCountStudyParticipants() throws InterruptedException { final DynamoStudyConsent1 consent = createStudyConsent(); for (int i=1; i < 6; i++) { userConsentDao.giveConsent(HEALTH_CODE+i, consent); } Thread.sleep(3000); long count = userConsentDao.getNumberOfParticipants(STUDY_IDENTIFIER); assertEquals("Correct number of participants", 5, count); userConsentDao.withdrawConsent(HEALTH_CODE+"5", STUDY_IDENTIFIER); Thread.sleep(3000); count = userConsentDao.getNumberOfParticipants(STUDY_IDENTIFIER); assertEquals("Correct number of participants", 4, count); userConsentDao.giveConsent(HEALTH_CODE+"5", consent); Thread.sleep(3000); count = userConsentDao.getNumberOfParticipants(STUDY_IDENTIFIER); assertEquals("Correct number of participants", 5, count); } private DynamoStudyConsent1 createStudyConsent() { final DynamoStudyConsent1 consent = new DynamoStudyConsent1(); consent.setStudyKey(STUDY_IDENTIFIER.getIdentifier()); consent.setCreatedOn(123L); return consent; } }
test/org/sagebionetworks/bridge/dynamodb/DynamoUserConsentDaoTest.java
package org.sagebionetworks.bridge.dynamodb; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import javax.annotation.Resource; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.sagebionetworks.bridge.models.studies.StudyIdentifier; import org.sagebionetworks.bridge.models.studies.StudyIdentifierImpl; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @ContextConfiguration("classpath:test-context.xml") @RunWith(SpringJUnit4ClassRunner.class) public class DynamoUserConsentDaoTest { private static final String HEALTH_CODE = "hc789"; private static final StudyIdentifier STUDY_IDENTIFIER = new StudyIdentifierImpl("study123"); @Resource private DynamoUserConsentDao userConsentDao; @Before public void before() { DynamoInitializer.init(DynamoUserConsent2.class); DynamoTestUtil.clearTable(DynamoUserConsent2.class); } @After public void after() { DynamoTestUtil.clearTable(DynamoUserConsent2.class); } @Test public void canConsentToStudy() { // Not consented yet final DynamoStudyConsent1 consent = createStudyConsent(); assertFalse(userConsentDao.hasConsented(HEALTH_CODE, new StudyIdentifierImpl(consent.getStudyKey()))); // Give consent userConsentDao.giveConsent(HEALTH_CODE, consent); assertTrue(userConsentDao.hasConsented(HEALTH_CODE, new StudyIdentifierImpl(consent.getStudyKey()))); // Withdraw userConsentDao.withdrawConsent(HEALTH_CODE, STUDY_IDENTIFIER); assertFalse(userConsentDao.hasConsented(HEALTH_CODE, new StudyIdentifierImpl(consent.getStudyKey()))); // Can give consent again if the previous consent is withdrawn userConsentDao.giveConsent(HEALTH_CODE, consent); assertTrue(userConsentDao.hasConsented(HEALTH_CODE, new StudyIdentifierImpl(consent.getStudyKey()))); // Withdraw again userConsentDao.withdrawConsent(HEALTH_CODE, STUDY_IDENTIFIER); assertFalse(userConsentDao.hasConsented(HEALTH_CODE, new StudyIdentifierImpl(consent.getStudyKey()))); } @Test public void canCountStudyParticipants() { final DynamoStudyConsent1 consent = createStudyConsent(); for (int i=1; i < 6; i++) { userConsentDao.giveConsent(HEALTH_CODE+i, consent); } long count = userConsentDao.getNumberOfParticipants(STUDY_IDENTIFIER); assertEquals("Correct number of participants", 5, count); userConsentDao.withdrawConsent(HEALTH_CODE+"5", STUDY_IDENTIFIER); count = userConsentDao.getNumberOfParticipants(STUDY_IDENTIFIER); assertEquals("Correct number of participants", 4, count); userConsentDao.giveConsent(HEALTH_CODE+"5", consent); count = userConsentDao.getNumberOfParticipants(STUDY_IDENTIFIER); assertEquals("Correct number of participants", 5, count); } private DynamoStudyConsent1 createStudyConsent() { final DynamoStudyConsent1 consent = new DynamoStudyConsent1(); consent.setStudyKey(STUDY_IDENTIFIER.getIdentifier()); consent.setCreatedOn(123L); return consent; } }
Adding Thread.sleep() to test in order to pass in production environment
test/org/sagebionetworks/bridge/dynamodb/DynamoUserConsentDaoTest.java
Adding Thread.sleep() to test in order to pass in production environment
<ide><path>est/org/sagebionetworks/bridge/dynamodb/DynamoUserConsentDaoTest.java <ide> } <ide> <ide> @Test <del> public void canCountStudyParticipants() { <add> public void canCountStudyParticipants() throws InterruptedException { <ide> final DynamoStudyConsent1 consent = createStudyConsent(); <ide> for (int i=1; i < 6; i++) { <ide> userConsentDao.giveConsent(HEALTH_CODE+i, consent); <ide> } <del> <add> Thread.sleep(3000); <add> <ide> long count = userConsentDao.getNumberOfParticipants(STUDY_IDENTIFIER); <ide> assertEquals("Correct number of participants", 5, count); <del> <add> <ide> userConsentDao.withdrawConsent(HEALTH_CODE+"5", STUDY_IDENTIFIER); <add> Thread.sleep(3000); <ide> count = userConsentDao.getNumberOfParticipants(STUDY_IDENTIFIER); <ide> assertEquals("Correct number of participants", 4, count); <del> <add> <ide> userConsentDao.giveConsent(HEALTH_CODE+"5", consent); <add> Thread.sleep(3000); <ide> count = userConsentDao.getNumberOfParticipants(STUDY_IDENTIFIER); <ide> assertEquals("Correct number of participants", 5, count); <ide> }
Java
apache-2.0
67ad78608c7a978ae86affc871a4bdaa48915a33
0
ejona86/grpc-java,grpc/grpc-java,ejona86/grpc-java,stanley-cheung/grpc-java,ejona86/grpc-java,grpc/grpc-java,dapengzhang0/grpc-java,stanley-cheung/grpc-java,grpc/grpc-java,stanley-cheung/grpc-java,dapengzhang0/grpc-java,stanley-cheung/grpc-java,dapengzhang0/grpc-java,dapengzhang0/grpc-java,ejona86/grpc-java,grpc/grpc-java
/* * Copyright 2020 The gRPC Authors * * 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 io.grpc.xds; import static com.google.common.base.Preconditions.checkArgument; import static io.grpc.xds.EnvoyProtoData.TRANSPORT_SOCKET_NAME_TLS; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Stopwatch; import com.google.common.base.Supplier; import com.google.protobuf.Any; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.util.Durations; import io.envoyproxy.envoy.config.cluster.v3.CircuitBreakers.Thresholds; import io.envoyproxy.envoy.config.cluster.v3.Cluster; import io.envoyproxy.envoy.config.cluster.v3.Cluster.DiscoveryType; import io.envoyproxy.envoy.config.cluster.v3.Cluster.EdsClusterConfig; import io.envoyproxy.envoy.config.cluster.v3.Cluster.LbPolicy; import io.envoyproxy.envoy.config.core.v3.HttpProtocolOptions; import io.envoyproxy.envoy.config.core.v3.RoutingPriority; import io.envoyproxy.envoy.config.endpoint.v3.ClusterLoadAssignment; import io.envoyproxy.envoy.config.endpoint.v3.LbEndpoint; import io.envoyproxy.envoy.config.listener.v3.Listener; import io.envoyproxy.envoy.config.route.v3.RouteConfiguration; import io.envoyproxy.envoy.config.route.v3.VirtualHost; import io.envoyproxy.envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager; import io.envoyproxy.envoy.extensions.filters.network.http_connection_manager.v3.Rds; import io.envoyproxy.envoy.extensions.transport_sockets.tls.v3.UpstreamTlsContext; import io.grpc.Status; import io.grpc.SynchronizationContext.ScheduledHandle; import io.grpc.internal.BackoffPolicy; import io.grpc.xds.EnvoyProtoData.DropOverload; import io.grpc.xds.EnvoyProtoData.Locality; import io.grpc.xds.EnvoyProtoData.LocalityLbEndpoints; import io.grpc.xds.EnvoyProtoData.Node; import io.grpc.xds.EnvoyProtoData.StructOrError; import io.grpc.xds.LoadStatsManager.LoadStatsStore; import io.grpc.xds.XdsLogger.XdsLogLevel; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; /** * XdsClient implementation for client side usages. */ final class ClientXdsClient extends AbstractXdsClient { // Longest time to wait, since the subscription to some resource, for concluding its absence. @VisibleForTesting static final int INITIAL_RESOURCE_FETCH_TIMEOUT_SEC = 15; private static final String TYPE_URL_HTTP_CONNECTION_MANAGER_V2 = "type.googleapis.com/envoy.config.filter.network.http_connection_manager.v2" + ".HttpConnectionManager"; private static final String TYPE_URL_HTTP_CONNECTION_MANAGER = "type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3" + ".HttpConnectionManager"; private static final String TYPE_URL_UPSTREAM_TLS_CONTEXT = "type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.UpstreamTlsContext"; private static final String TYPE_URL_UPSTREAM_TLS_CONTEXT_V2 = "type.googleapis.com/envoy.api.v2.auth.UpstreamTlsContext"; private final Map<String, ResourceSubscriber> ldsResourceSubscribers = new HashMap<>(); private final Map<String, ResourceSubscriber> rdsResourceSubscribers = new HashMap<>(); private final Map<String, ResourceSubscriber> cdsResourceSubscribers = new HashMap<>(); private final Map<String, ResourceSubscriber> edsResourceSubscribers = new HashMap<>(); private final LoadStatsManager loadStatsManager = new LoadStatsManager(); private final LoadReportClient lrsClient; private boolean reportingLoad; ClientXdsClient(XdsChannel channel, Node node, ScheduledExecutorService timeService, BackoffPolicy.Provider backoffPolicyProvider, Supplier<Stopwatch> stopwatchSupplier) { super(channel, node, timeService, backoffPolicyProvider, stopwatchSupplier); lrsClient = new LoadReportClient(loadStatsManager, channel, node, getSyncContext(), timeService, backoffPolicyProvider, stopwatchSupplier); } @Override protected void handleLdsResponse(String versionInfo, List<Any> resources, String nonce) { // Unpack Listener messages. List<Listener> listeners = new ArrayList<>(resources.size()); List<String> listenerNames = new ArrayList<>(resources.size()); try { for (com.google.protobuf.Any res : resources) { if (res.getTypeUrl().equals(ResourceType.LDS.typeUrlV2())) { res = res.toBuilder().setTypeUrl(ResourceType.LDS.typeUrl()).build(); } Listener listener = res.unpack(Listener.class); listeners.add(listener); listenerNames.add(listener.getName()); } } catch (InvalidProtocolBufferException e) { getLogger().log(XdsLogLevel.WARNING, "Failed to unpack Listeners in LDS response {0}", e); nackResponse(ResourceType.LDS, nonce, "Malformed LDS response: " + e); return; } getLogger().log(XdsLogLevel.INFO, "Received LDS response for resources: {0}", listenerNames); // Unpack HttpConnectionManager messages. Map<String, HttpConnectionManager> httpConnectionManagers = new HashMap<>(listeners.size()); try { for (Listener listener : listeners) { Any apiListener = listener.getApiListener().getApiListener(); if (apiListener.getTypeUrl().equals(TYPE_URL_HTTP_CONNECTION_MANAGER_V2)) { apiListener = apiListener.toBuilder().setTypeUrl(TYPE_URL_HTTP_CONNECTION_MANAGER).build(); } HttpConnectionManager hcm = apiListener.unpack(HttpConnectionManager.class); httpConnectionManagers.put(listener.getName(), hcm); } } catch (InvalidProtocolBufferException e) { getLogger().log( XdsLogLevel.WARNING, "Failed to unpack HttpConnectionManagers in Listeners of LDS response {0}", e); nackResponse(ResourceType.LDS, nonce, "Malformed LDS response: " + e); return; } Map<String, LdsUpdate> ldsUpdates = new HashMap<>(); Set<String> rdsNames = new HashSet<>(); String errorMessage = null; for (Map.Entry<String, HttpConnectionManager> entry : httpConnectionManagers.entrySet()) { String listenerName = entry.getKey(); HttpConnectionManager hcm = entry.getValue(); LdsUpdate.Builder updateBuilder = LdsUpdate.newBuilder(); if (hcm.hasRouteConfig()) { for (VirtualHost virtualHostProto : hcm.getRouteConfig().getVirtualHostsList()) { StructOrError<EnvoyProtoData.VirtualHost> virtualHost = EnvoyProtoData.VirtualHost.fromEnvoyProtoVirtualHost(virtualHostProto); if (virtualHost.getErrorDetail() != null) { errorMessage = "Listener " + listenerName + " contains invalid virtual host: " + virtualHost.getErrorDetail(); break; } else { updateBuilder.addVirtualHost(virtualHost.getStruct()); } } } else if (hcm.hasRds()) { Rds rds = hcm.getRds(); if (!rds.getConfigSource().hasAds()) { errorMessage = "Listener " + listenerName + " with RDS config_source not set to ADS"; } else { updateBuilder.setRdsName(rds.getRouteConfigName()); rdsNames.add(rds.getRouteConfigName()); } } else { errorMessage = "Listener " + listenerName + " without inline RouteConfiguration or RDS"; } if (errorMessage != null) { break; } if (hcm.hasCommonHttpProtocolOptions()) { HttpProtocolOptions options = hcm.getCommonHttpProtocolOptions(); if (options.hasMaxStreamDuration()) { updateBuilder.setHttpMaxStreamDurationNano( Durations.toNanos(options.getMaxStreamDuration())); } } ldsUpdates.put(listenerName, updateBuilder.build()); } if (errorMessage != null) { nackResponse(ResourceType.LDS, nonce, errorMessage); return; } ackResponse(ResourceType.LDS, versionInfo, nonce); for (String resource : ldsResourceSubscribers.keySet()) { ResourceSubscriber subscriber = ldsResourceSubscribers.get(resource); if (ldsUpdates.containsKey(resource)) { subscriber.onData(ldsUpdates.get(resource)); } else { subscriber.onAbsent(); } } for (String resource : rdsResourceSubscribers.keySet()) { if (!rdsNames.contains(resource)) { ResourceSubscriber subscriber = rdsResourceSubscribers.get(resource); subscriber.onAbsent(); } } } @Override protected void handleRdsResponse(String versionInfo, List<Any> resources, String nonce) { // Unpack RouteConfiguration messages. Map<String, RouteConfiguration> routeConfigs = new HashMap<>(resources.size()); try { for (com.google.protobuf.Any res : resources) { if (res.getTypeUrl().equals(ResourceType.RDS.typeUrlV2())) { res = res.toBuilder().setTypeUrl(ResourceType.RDS.typeUrl()).build(); } RouteConfiguration rc = res.unpack(RouteConfiguration.class); routeConfigs.put(rc.getName(), rc); } } catch (InvalidProtocolBufferException e) { getLogger().log( XdsLogLevel.WARNING, "Failed to unpack RouteConfiguration in RDS response {0}", e); nackResponse(ResourceType.RDS, nonce, "Malformed RDS response: " + e); return; } getLogger().log( XdsLogLevel.INFO, "Received RDS response for resources: {0}", routeConfigs.keySet()); Map<String, RdsUpdate> rdsUpdates = new HashMap<>(); String errorMessage = null; for (Map.Entry<String, RouteConfiguration> entry : routeConfigs.entrySet()) { String routeConfigName = entry.getKey(); RouteConfiguration routeConfig = entry.getValue(); List<EnvoyProtoData.VirtualHost> virtualHosts = new ArrayList<>(routeConfig.getVirtualHostsCount()); for (VirtualHost virtualHostProto : routeConfig.getVirtualHostsList()) { StructOrError<EnvoyProtoData.VirtualHost> virtualHost = EnvoyProtoData.VirtualHost.fromEnvoyProtoVirtualHost(virtualHostProto); if (virtualHost.getErrorDetail() != null) { errorMessage = "RouteConfiguration " + routeConfigName + " contains invalid virtual host: " + virtualHost.getErrorDetail(); break; } else { virtualHosts.add(virtualHost.getStruct()); } } if (errorMessage != null) { break; } rdsUpdates.put(routeConfigName, RdsUpdate.fromVirtualHosts(virtualHosts)); } if (errorMessage != null) { nackResponse(ResourceType.RDS, nonce, errorMessage); return; } ackResponse(ResourceType.RDS, versionInfo, nonce); for (String resource : rdsResourceSubscribers.keySet()) { if (rdsUpdates.containsKey(resource)) { ResourceSubscriber subscriber = rdsResourceSubscribers.get(resource); subscriber.onData(rdsUpdates.get(resource)); } } } @Override protected void handleCdsResponse(String versionInfo, List<Any> resources, String nonce) { // Unpack Cluster messages. List<Cluster> clusters = new ArrayList<>(resources.size()); List<String> clusterNames = new ArrayList<>(resources.size()); try { for (com.google.protobuf.Any res : resources) { if (res.getTypeUrl().equals(ResourceType.CDS.typeUrlV2())) { res = res.toBuilder().setTypeUrl(ResourceType.CDS.typeUrl()).build(); } Cluster cluster = res.unpack(Cluster.class); clusters.add(cluster); clusterNames.add(cluster.getName()); } } catch (InvalidProtocolBufferException e) { getLogger().log(XdsLogLevel.WARNING, "Failed to unpack Clusters in CDS response {0}", e); nackResponse(ResourceType.CDS, nonce, "Malformed CDS response: " + e); return; } getLogger().log(XdsLogLevel.INFO, "Received CDS response for resources: {0}", clusterNames); String errorMessage = null; // Cluster information update for requested clusters received in this CDS response. Map<String, CdsUpdate> cdsUpdates = new HashMap<>(); // CDS responses represents the state of the world, EDS services not referenced by // Clusters are those no longer exist. Set<String> edsServices = new HashSet<>(); for (Cluster cluster : clusters) { String clusterName = cluster.getName(); // Skip information for clusters not requested. // Management server is required to always send newly requested resources, even if they // may have been sent previously (proactively). Thus, client does not need to cache // unrequested resources. if (!cdsResourceSubscribers.containsKey(clusterName)) { continue; } CdsUpdate.Builder updateBuilder = CdsUpdate.newBuilder(); updateBuilder.setClusterName(clusterName); // The type field must be set to EDS. if (!cluster.getType().equals(DiscoveryType.EDS)) { errorMessage = "Cluster " + clusterName + " : only EDS discovery type is supported " + "in gRPC."; break; } // In the eds_cluster_config field, the eds_config field must be set to indicate to // use EDS (must be set to use ADS). EdsClusterConfig edsClusterConfig = cluster.getEdsClusterConfig(); if (!edsClusterConfig.getEdsConfig().hasAds()) { errorMessage = "Cluster " + clusterName + " : field eds_cluster_config must be set to " + "indicate to use EDS over ADS."; break; } // If the service_name field is set, that value will be used for the EDS request. if (!edsClusterConfig.getServiceName().isEmpty()) { updateBuilder.setEdsServiceName(edsClusterConfig.getServiceName()); edsServices.add(edsClusterConfig.getServiceName()); } else { edsServices.add(clusterName); } // The lb_policy field must be set to ROUND_ROBIN. if (!cluster.getLbPolicy().equals(LbPolicy.ROUND_ROBIN)) { errorMessage = "Cluster " + clusterName + " : only round robin load balancing policy is " + "supported in gRPC."; break; } updateBuilder.setLbPolicy("round_robin"); // If the lrs_server field is set, it must have its self field set, in which case the // client should use LRS for load reporting. Otherwise (the lrs_server field is not set), // LRS load reporting will be disabled. if (cluster.hasLrsServer()) { if (!cluster.getLrsServer().hasSelf()) { errorMessage = "Cluster " + clusterName + " : only support enabling LRS for the same " + "management server."; break; } updateBuilder.setLrsServerName(""); } if (cluster.hasCircuitBreakers()) { List<Thresholds> thresholds = cluster.getCircuitBreakers().getThresholdsList(); for (Thresholds threshold : thresholds) { if (threshold.getPriority() != RoutingPriority.DEFAULT) { continue; } if (threshold.hasMaxRequests()) { updateBuilder.setMaxConcurrentRequests(threshold.getMaxRequests().getValue()); } } } try { EnvoyServerProtoData.UpstreamTlsContext upstreamTlsContext = getTlsContextFromCluster(cluster); if (upstreamTlsContext != null && upstreamTlsContext.getCommonTlsContext() != null) { updateBuilder.setUpstreamTlsContext(upstreamTlsContext); } } catch (InvalidProtocolBufferException e) { errorMessage = "Cluster " + clusterName + " : " + e.getMessage(); break; } cdsUpdates.put(clusterName, updateBuilder.build()); } if (errorMessage != null) { nackResponse(ResourceType.CDS, nonce, errorMessage); return; } ackResponse(ResourceType.CDS, versionInfo, nonce); for (String resource : cdsResourceSubscribers.keySet()) { ResourceSubscriber subscriber = cdsResourceSubscribers.get(resource); if (cdsUpdates.containsKey(resource)) { subscriber.onData(cdsUpdates.get(resource)); } else { subscriber.onAbsent(); } } for (String resource : edsResourceSubscribers.keySet()) { ResourceSubscriber subscriber = edsResourceSubscribers.get(resource); if (!edsServices.contains(resource)) { subscriber.onAbsent(); } } } @Nullable private static EnvoyServerProtoData.UpstreamTlsContext getTlsContextFromCluster(Cluster cluster) throws InvalidProtocolBufferException { if (cluster.hasTransportSocket() && TRANSPORT_SOCKET_NAME_TLS.equals(cluster.getTransportSocket().getName())) { Any any = cluster.getTransportSocket().getTypedConfig(); if (any.getTypeUrl().equals(TYPE_URL_UPSTREAM_TLS_CONTEXT_V2)) { any = any.toBuilder().setTypeUrl(TYPE_URL_UPSTREAM_TLS_CONTEXT).build(); } return EnvoyServerProtoData.UpstreamTlsContext.fromEnvoyProtoUpstreamTlsContext( any.unpack(UpstreamTlsContext.class)); } return null; } @Override protected void handleEdsResponse(String versionInfo, List<Any> resources, String nonce) { // Unpack ClusterLoadAssignment messages. List<ClusterLoadAssignment> clusterLoadAssignments = new ArrayList<>(resources.size()); List<String> claNames = new ArrayList<>(resources.size()); try { for (com.google.protobuf.Any res : resources) { if (res.getTypeUrl().equals(ResourceType.EDS.typeUrlV2())) { res = res.toBuilder().setTypeUrl(ResourceType.EDS.typeUrl()).build(); } ClusterLoadAssignment assignment = res.unpack(ClusterLoadAssignment.class); clusterLoadAssignments.add(assignment); claNames.add(assignment.getClusterName()); } } catch (InvalidProtocolBufferException e) { getLogger().log( XdsLogLevel.WARNING, "Failed to unpack ClusterLoadAssignments in EDS response {0}", e); nackResponse(ResourceType.EDS, nonce, "Malformed EDS response: " + e); return; } getLogger().log(XdsLogLevel.INFO, "Received EDS response for resources: {0}", claNames); String errorMessage = null; // Endpoint information updates for requested clusters received in this EDS response. Map<String, EdsUpdate> edsUpdates = new HashMap<>(); // Walk through each ClusterLoadAssignment message. If any of them for requested clusters // contain invalid information for gRPC's load balancing usage, the whole response is rejected. for (ClusterLoadAssignment assignment : clusterLoadAssignments) { String clusterName = assignment.getClusterName(); // Skip information for clusters not requested. // Management server is required to always send newly requested resources, even if they // may have been sent previously (proactively). Thus, client does not need to cache // unrequested resources. if (!edsResourceSubscribers.containsKey(clusterName)) { continue; } EdsUpdate.Builder updateBuilder = EdsUpdate.newBuilder(); updateBuilder.setClusterName(clusterName); Set<Integer> priorities = new HashSet<>(); int maxPriority = -1; for (io.envoyproxy.envoy.config.endpoint.v3.LocalityLbEndpoints localityLbEndpoints : assignment.getEndpointsList()) { // Filter out localities without or with 0 weight. if (!localityLbEndpoints.hasLoadBalancingWeight() || localityLbEndpoints.getLoadBalancingWeight().getValue() < 1) { continue; } int localityPriority = localityLbEndpoints.getPriority(); if (localityPriority < 0) { errorMessage = "ClusterLoadAssignment " + clusterName + " : locality with negative priority."; break; } maxPriority = Math.max(maxPriority, localityPriority); priorities.add(localityPriority); // The endpoint field of each lb_endpoints must be set. // Inside of it: the address field must be set. for (LbEndpoint lbEndpoint : localityLbEndpoints.getLbEndpointsList()) { if (!lbEndpoint.getEndpoint().hasAddress()) { errorMessage = "ClusterLoadAssignment " + clusterName + " : endpoint with no address."; break; } } if (errorMessage != null) { break; } // Note endpoints with health status other than UNHEALTHY and UNKNOWN are still // handed over to watching parties. It is watching parties' responsibility to // filter out unhealthy endpoints. See EnvoyProtoData.LbEndpoint#isHealthy(). updateBuilder.addLocalityLbEndpoints( Locality.fromEnvoyProtoLocality(localityLbEndpoints.getLocality()), LocalityLbEndpoints.fromEnvoyProtoLocalityLbEndpoints(localityLbEndpoints)); } if (errorMessage != null) { break; } if (priorities.size() != maxPriority + 1) { errorMessage = "ClusterLoadAssignment " + clusterName + " : sparse priorities."; break; } for (ClusterLoadAssignment.Policy.DropOverload dropOverload : assignment.getPolicy().getDropOverloadsList()) { updateBuilder.addDropPolicy(DropOverload.fromEnvoyProtoDropOverload(dropOverload)); } EdsUpdate update = updateBuilder.build(); edsUpdates.put(clusterName, update); } if (errorMessage != null) { nackResponse(ResourceType.EDS, nonce, errorMessage); return; } ackResponse(ResourceType.EDS, versionInfo, nonce); for (String resource : edsResourceSubscribers.keySet()) { ResourceSubscriber subscriber = edsResourceSubscribers.get(resource); if (edsUpdates.containsKey(resource)) { subscriber.onData(edsUpdates.get(resource)); } } } @Override protected void handleStreamClosed(Status error) { cleanUpResourceTimers(); for (ResourceSubscriber subscriber : ldsResourceSubscribers.values()) { subscriber.onError(error); } for (ResourceSubscriber subscriber : rdsResourceSubscribers.values()) { subscriber.onError(error); } for (ResourceSubscriber subscriber : cdsResourceSubscribers.values()) { subscriber.onError(error); } for (ResourceSubscriber subscriber : edsResourceSubscribers.values()) { subscriber.onError(error); } } @Override protected void handleStreamRestarted() { for (ResourceSubscriber subscriber : ldsResourceSubscribers.values()) { subscriber.restartTimer(); } for (ResourceSubscriber subscriber : rdsResourceSubscribers.values()) { subscriber.restartTimer(); } for (ResourceSubscriber subscriber : cdsResourceSubscribers.values()) { subscriber.restartTimer(); } for (ResourceSubscriber subscriber : edsResourceSubscribers.values()) { subscriber.restartTimer(); } } @Override protected void handleShutdown() { if (reportingLoad) { lrsClient.stopLoadReporting(); } cleanUpResourceTimers(); } @Nullable @Override Collection<String> getSubscribedResources(ResourceType type) { switch (type) { case LDS: return ldsResourceSubscribers.isEmpty() ? null : ldsResourceSubscribers.keySet(); case RDS: return rdsResourceSubscribers.isEmpty() ? null : rdsResourceSubscribers.keySet(); case CDS: return cdsResourceSubscribers.isEmpty() ? null : cdsResourceSubscribers.keySet(); case EDS: return edsResourceSubscribers.isEmpty() ? null : edsResourceSubscribers.keySet(); case UNKNOWN: default: throw new AssertionError("Unknown resource type"); } } @Override void watchLdsResource(final String resourceName, final LdsResourceWatcher watcher) { getSyncContext().execute(new Runnable() { @Override public void run() { ResourceSubscriber subscriber = ldsResourceSubscribers.get(resourceName); if (subscriber == null) { getLogger().log(XdsLogLevel.INFO, "Subscribe LDS resource {0}", resourceName); subscriber = new ResourceSubscriber(ResourceType.LDS, resourceName); ldsResourceSubscribers.put(resourceName, subscriber); adjustResourceSubscription(ResourceType.LDS); } subscriber.addWatcher(watcher); } }); } @Override void cancelLdsResourceWatch(final String resourceName, final LdsResourceWatcher watcher) { getSyncContext().execute(new Runnable() { @Override public void run() { ResourceSubscriber subscriber = ldsResourceSubscribers.get(resourceName); subscriber.removeWatcher(watcher); if (!subscriber.isWatched()) { subscriber.stopTimer(); getLogger().log(XdsLogLevel.INFO, "Unsubscribe LDS resource {0}", resourceName); ldsResourceSubscribers.remove(resourceName); adjustResourceSubscription(ResourceType.LDS); } } }); } @Override void watchRdsResource(final String resourceName, final RdsResourceWatcher watcher) { getSyncContext().execute(new Runnable() { @Override public void run() { ResourceSubscriber subscriber = rdsResourceSubscribers.get(resourceName); if (subscriber == null) { getLogger().log(XdsLogLevel.INFO, "Subscribe RDS resource {0}", resourceName); subscriber = new ResourceSubscriber(ResourceType.RDS, resourceName); rdsResourceSubscribers.put(resourceName, subscriber); adjustResourceSubscription(ResourceType.RDS); } subscriber.addWatcher(watcher); } }); } @Override void cancelRdsResourceWatch(final String resourceName, final RdsResourceWatcher watcher) { getSyncContext().execute(new Runnable() { @Override public void run() { ResourceSubscriber subscriber = rdsResourceSubscribers.get(resourceName); subscriber.removeWatcher(watcher); if (!subscriber.isWatched()) { subscriber.stopTimer(); getLogger().log(XdsLogLevel.INFO, "Unsubscribe RDS resource {0}", resourceName); rdsResourceSubscribers.remove(resourceName); adjustResourceSubscription(ResourceType.RDS); } } }); } @Override void watchCdsResource(final String resourceName, final CdsResourceWatcher watcher) { getSyncContext().execute(new Runnable() { @Override public void run() { ResourceSubscriber subscriber = cdsResourceSubscribers.get(resourceName); if (subscriber == null) { getLogger().log(XdsLogLevel.INFO, "Subscribe CDS resource {0}", resourceName); subscriber = new ResourceSubscriber(ResourceType.CDS, resourceName); cdsResourceSubscribers.put(resourceName, subscriber); adjustResourceSubscription(ResourceType.CDS); } subscriber.addWatcher(watcher); } }); } @Override void cancelCdsResourceWatch(final String resourceName, final CdsResourceWatcher watcher) { getSyncContext().execute(new Runnable() { @Override public void run() { ResourceSubscriber subscriber = cdsResourceSubscribers.get(resourceName); subscriber.removeWatcher(watcher); if (!subscriber.isWatched()) { subscriber.stopTimer(); getLogger().log(XdsLogLevel.INFO, "Unsubscribe CDS resource {0}", resourceName); cdsResourceSubscribers.remove(resourceName); adjustResourceSubscription(ResourceType.CDS); } } }); } @Override void watchEdsResource(final String resourceName, final EdsResourceWatcher watcher) { getSyncContext().execute(new Runnable() { @Override public void run() { ResourceSubscriber subscriber = edsResourceSubscribers.get(resourceName); if (subscriber == null) { getLogger().log(XdsLogLevel.INFO, "Subscribe EDS resource {0}", resourceName); subscriber = new ResourceSubscriber(ResourceType.EDS, resourceName); edsResourceSubscribers.put(resourceName, subscriber); adjustResourceSubscription(ResourceType.EDS); } subscriber.addWatcher(watcher); } }); } @Override void cancelEdsResourceWatch(final String resourceName, final EdsResourceWatcher watcher) { getSyncContext().execute(new Runnable() { @Override public void run() { ResourceSubscriber subscriber = edsResourceSubscribers.get(resourceName); subscriber.removeWatcher(watcher); if (!subscriber.isWatched()) { subscriber.stopTimer(); getLogger().log(XdsLogLevel.INFO, "Unsubscribe EDS resource {0}", resourceName); edsResourceSubscribers.remove(resourceName); adjustResourceSubscription(ResourceType.EDS); } } }); } @Override LoadStatsStore addClientStats(String clusterName, @Nullable String clusterServiceName) { LoadStatsStore loadStatsStore; synchronized (this) { loadStatsStore = loadStatsManager.addLoadStats(clusterName, clusterServiceName); } getSyncContext().execute(new Runnable() { @Override public void run() { if (!reportingLoad) { lrsClient.startLoadReporting(); reportingLoad = true; } } }); return loadStatsStore; } @Override void removeClientStats(String clusterName, @Nullable String clusterServiceName) { synchronized (this) { loadStatsManager.removeLoadStats(clusterName, clusterServiceName); } } private void cleanUpResourceTimers() { for (ResourceSubscriber subscriber : ldsResourceSubscribers.values()) { subscriber.stopTimer(); } for (ResourceSubscriber subscriber : rdsResourceSubscribers.values()) { subscriber.stopTimer(); } for (ResourceSubscriber subscriber : cdsResourceSubscribers.values()) { subscriber.stopTimer(); } for (ResourceSubscriber subscriber : edsResourceSubscribers.values()) { subscriber.stopTimer(); } } /** * Tracks a single subscribed resource. */ private final class ResourceSubscriber { private final ResourceType type; private final String resource; private final Set<ResourceWatcher> watchers = new HashSet<>(); private ResourceUpdate data; private boolean absent; private ScheduledHandle respTimer; ResourceSubscriber(ResourceType type, String resource) { this.type = type; this.resource = resource; if (isInBackoff()) { return; } restartTimer(); } void addWatcher(ResourceWatcher watcher) { checkArgument(!watchers.contains(watcher), "watcher %s already registered", watcher); watchers.add(watcher); if (data != null) { notifyWatcher(watcher, data); } else if (absent) { watcher.onResourceDoesNotExist(resource); } } void removeWatcher(ResourceWatcher watcher) { checkArgument(watchers.contains(watcher), "watcher %s not registered", watcher); watchers.remove(watcher); } void restartTimer() { if (data != null || absent) { // resource already resolved return; } class ResourceNotFound implements Runnable { @Override public void run() { getLogger().log(XdsLogLevel.INFO, "{0} resource {1} initial fetch timeout", type, resource); respTimer = null; onAbsent(); } @Override public String toString() { return type + this.getClass().getSimpleName(); } } respTimer = getSyncContext().schedule( new ResourceNotFound(), INITIAL_RESOURCE_FETCH_TIMEOUT_SEC, TimeUnit.SECONDS, getTimeService()); } void stopTimer() { if (respTimer != null && respTimer.isPending()) { respTimer.cancel(); respTimer = null; } } boolean isWatched() { return !watchers.isEmpty(); } void onData(ResourceUpdate data) { if (respTimer != null && respTimer.isPending()) { respTimer.cancel(); respTimer = null; } ResourceUpdate oldData = this.data; this.data = data; absent = false; if (!Objects.equals(oldData, data)) { for (ResourceWatcher watcher : watchers) { notifyWatcher(watcher, data); } } } void onAbsent() { if (respTimer != null && respTimer.isPending()) { // too early to conclude absence return; } getLogger().log(XdsLogLevel.INFO, "Conclude {0} resource {1} not exist", type, resource); if (!absent) { data = null; absent = true; for (ResourceWatcher watcher : watchers) { watcher.onResourceDoesNotExist(resource); } } } void onError(Status error) { if (respTimer != null && respTimer.isPending()) { respTimer.cancel(); respTimer = null; } for (ResourceWatcher watcher : watchers) { watcher.onError(error); } } private void notifyWatcher(ResourceWatcher watcher, ResourceUpdate update) { switch (type) { case LDS: ((LdsResourceWatcher) watcher).onChanged((LdsUpdate) update); break; case RDS: ((RdsResourceWatcher) watcher).onChanged((RdsUpdate) update); break; case CDS: ((CdsResourceWatcher) watcher).onChanged((CdsUpdate) update); break; case EDS: ((EdsResourceWatcher) watcher).onChanged((EdsUpdate) update); break; case UNKNOWN: default: throw new AssertionError("should never be here"); } } } }
xds/src/main/java/io/grpc/xds/ClientXdsClient.java
/* * Copyright 2020 The gRPC Authors * * 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 io.grpc.xds; import static com.google.common.base.Preconditions.checkArgument; import static io.grpc.xds.EnvoyProtoData.TRANSPORT_SOCKET_NAME_TLS; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Stopwatch; import com.google.common.base.Supplier; import com.google.protobuf.Any; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.util.Durations; import io.envoyproxy.envoy.config.cluster.v3.CircuitBreakers.Thresholds; import io.envoyproxy.envoy.config.cluster.v3.Cluster; import io.envoyproxy.envoy.config.cluster.v3.Cluster.DiscoveryType; import io.envoyproxy.envoy.config.cluster.v3.Cluster.EdsClusterConfig; import io.envoyproxy.envoy.config.cluster.v3.Cluster.LbPolicy; import io.envoyproxy.envoy.config.core.v3.HttpProtocolOptions; import io.envoyproxy.envoy.config.core.v3.RoutingPriority; import io.envoyproxy.envoy.config.endpoint.v3.ClusterLoadAssignment; import io.envoyproxy.envoy.config.endpoint.v3.LbEndpoint; import io.envoyproxy.envoy.config.listener.v3.Listener; import io.envoyproxy.envoy.config.route.v3.RouteConfiguration; import io.envoyproxy.envoy.config.route.v3.VirtualHost; import io.envoyproxy.envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager; import io.envoyproxy.envoy.extensions.filters.network.http_connection_manager.v3.Rds; import io.envoyproxy.envoy.extensions.transport_sockets.tls.v3.UpstreamTlsContext; import io.grpc.Status; import io.grpc.SynchronizationContext.ScheduledHandle; import io.grpc.internal.BackoffPolicy; import io.grpc.xds.EnvoyProtoData.DropOverload; import io.grpc.xds.EnvoyProtoData.Locality; import io.grpc.xds.EnvoyProtoData.LocalityLbEndpoints; import io.grpc.xds.EnvoyProtoData.Node; import io.grpc.xds.EnvoyProtoData.StructOrError; import io.grpc.xds.LoadStatsManager.LoadStatsStore; import io.grpc.xds.XdsLogger.XdsLogLevel; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; /** * XdsClient implementation for client side usages. */ final class ClientXdsClient extends AbstractXdsClient { // Longest time to wait, since the subscription to some resource, for concluding its absence. @VisibleForTesting static final int INITIAL_RESOURCE_FETCH_TIMEOUT_SEC = 15; private static final String TYPE_URL_HTTP_CONNECTION_MANAGER_V2 = "type.googleapis.com/envoy.config.filter.network.http_connection_manager.v2" + ".HttpConnectionManager"; private static final String TYPE_URL_HTTP_CONNECTION_MANAGER = "type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3" + ".HttpConnectionManager"; private static final String TYPE_URL_UPSTREAM_TLS_CONTEXT = "type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.UpstreamTlsContext"; private static final String TYPE_URL_UPSTREAM_TLS_CONTEXT_V2 = "type.googleapis.com/envoy.api.v2.auth.UpstreamTlsContext"; private final Map<String, ResourceSubscriber> ldsResourceSubscribers = new HashMap<>(); private final Map<String, ResourceSubscriber> rdsResourceSubscribers = new HashMap<>(); private final Map<String, ResourceSubscriber> cdsResourceSubscribers = new HashMap<>(); private final Map<String, ResourceSubscriber> edsResourceSubscribers = new HashMap<>(); private final LoadStatsManager loadStatsManager = new LoadStatsManager(); private final LoadReportClient lrsClient; private boolean reportingLoad; ClientXdsClient(XdsChannel channel, Node node, ScheduledExecutorService timeService, BackoffPolicy.Provider backoffPolicyProvider, Supplier<Stopwatch> stopwatchSupplier) { super(channel, node, timeService, backoffPolicyProvider, stopwatchSupplier); lrsClient = new LoadReportClient(loadStatsManager, channel, node, getSyncContext(), timeService, backoffPolicyProvider, stopwatchSupplier); } @Override protected void handleLdsResponse(String versionInfo, List<Any> resources, String nonce) { // Unpack Listener messages. List<Listener> listeners = new ArrayList<>(resources.size()); List<String> listenerNames = new ArrayList<>(resources.size()); try { for (com.google.protobuf.Any res : resources) { if (res.getTypeUrl().equals(ResourceType.LDS.typeUrlV2())) { res = res.toBuilder().setTypeUrl(ResourceType.LDS.typeUrl()).build(); } Listener listener = res.unpack(Listener.class); listeners.add(listener); listenerNames.add(listener.getName()); } } catch (InvalidProtocolBufferException e) { getLogger().log(XdsLogLevel.WARNING, "Failed to unpack Listeners in LDS response {0}", e); nackResponse(ResourceType.LDS, nonce, "Malformed LDS response: " + e); return; } getLogger().log(XdsLogLevel.INFO, "Received LDS response for resources: {0}", listenerNames); // Unpack HttpConnectionManager messages. Map<String, HttpConnectionManager> httpConnectionManagers = new HashMap<>(listeners.size()); try { for (Listener listener : listeners) { Any apiListener = listener.getApiListener().getApiListener(); if (apiListener.getTypeUrl().equals(TYPE_URL_HTTP_CONNECTION_MANAGER_V2)) { apiListener = apiListener.toBuilder().setTypeUrl(TYPE_URL_HTTP_CONNECTION_MANAGER).build(); } HttpConnectionManager hcm = apiListener.unpack(HttpConnectionManager.class); httpConnectionManagers.put(listener.getName(), hcm); } } catch (InvalidProtocolBufferException e) { getLogger().log( XdsLogLevel.WARNING, "Failed to unpack HttpConnectionManagers in Listeners of LDS response {0}", e); nackResponse(ResourceType.LDS, nonce, "Malformed LDS response: " + e); return; } Map<String, LdsUpdate> ldsUpdates = new HashMap<>(); Set<String> rdsNames = new HashSet<>(); String errorMessage = null; for (Map.Entry<String, HttpConnectionManager> entry : httpConnectionManagers.entrySet()) { String listenerName = entry.getKey(); HttpConnectionManager hcm = entry.getValue(); LdsUpdate.Builder updateBuilder = LdsUpdate.newBuilder(); if (hcm.hasRouteConfig()) { for (VirtualHost virtualHostProto : hcm.getRouteConfig().getVirtualHostsList()) { StructOrError<EnvoyProtoData.VirtualHost> virtualHost = EnvoyProtoData.VirtualHost.fromEnvoyProtoVirtualHost(virtualHostProto); if (virtualHost.getErrorDetail() != null) { errorMessage = "Listener " + listenerName + " contains invalid virtual host: " + virtualHost.getErrorDetail(); break; } else { updateBuilder.addVirtualHost(virtualHost.getStruct()); } } } else if (hcm.hasRds()) { Rds rds = hcm.getRds(); if (!rds.getConfigSource().hasAds()) { errorMessage = "Listener " + listenerName + " with RDS config_source not set to ADS"; } else { updateBuilder.setRdsName(rds.getRouteConfigName()); rdsNames.add(rds.getRouteConfigName()); } } else { errorMessage = "Listener " + listenerName + " without inline RouteConfiguration or RDS"; } if (errorMessage != null) { break; } if (hcm.hasCommonHttpProtocolOptions()) { HttpProtocolOptions options = hcm.getCommonHttpProtocolOptions(); if (options.hasMaxStreamDuration()) { updateBuilder.setHttpMaxStreamDurationNano( Durations.toNanos(options.getMaxStreamDuration())); } } ldsUpdates.put(listenerName, updateBuilder.build()); } if (errorMessage != null) { nackResponse(ResourceType.LDS, nonce, errorMessage); return; } ackResponse(ResourceType.LDS, versionInfo, nonce); for (String resource : ldsResourceSubscribers.keySet()) { ResourceSubscriber subscriber = ldsResourceSubscribers.get(resource); if (ldsUpdates.containsKey(resource)) { subscriber.onData(ldsUpdates.get(resource)); } else { subscriber.onAbsent(); } } for (String resource : rdsResourceSubscribers.keySet()) { if (!rdsNames.contains(resource)) { ResourceSubscriber subscriber = rdsResourceSubscribers.get(resource); subscriber.onAbsent(); } } } @Override protected void handleRdsResponse(String versionInfo, List<Any> resources, String nonce) { // Unpack RouteConfiguration messages. Map<String, RouteConfiguration> routeConfigs = new HashMap<>(resources.size()); try { for (com.google.protobuf.Any res : resources) { if (res.getTypeUrl().equals(ResourceType.RDS.typeUrlV2())) { res = res.toBuilder().setTypeUrl(ResourceType.RDS.typeUrl()).build(); } RouteConfiguration rc = res.unpack(RouteConfiguration.class); routeConfigs.put(rc.getName(), rc); } } catch (InvalidProtocolBufferException e) { getLogger().log( XdsLogLevel.WARNING, "Failed to unpack RouteConfiguration in RDS response {0}", e); nackResponse(ResourceType.RDS, nonce, "Malformed RDS response: " + e); return; } getLogger().log( XdsLogLevel.INFO, "Received RDS response for resources: {0}", routeConfigs.keySet()); Map<String, RdsUpdate> rdsUpdates = new HashMap<>(); String errorMessage = null; for (Map.Entry<String, RouteConfiguration> entry : routeConfigs.entrySet()) { String routeConfigName = entry.getKey(); RouteConfiguration routeConfig = entry.getValue(); List<EnvoyProtoData.VirtualHost> virtualHosts = new ArrayList<>(routeConfig.getVirtualHostsCount()); for (VirtualHost virtualHostProto : routeConfig.getVirtualHostsList()) { StructOrError<EnvoyProtoData.VirtualHost> virtualHost = EnvoyProtoData.VirtualHost.fromEnvoyProtoVirtualHost(virtualHostProto); if (virtualHost.getErrorDetail() != null) { errorMessage = "RouteConfiguration " + routeConfigName + " contains invalid virtual host: " + virtualHost.getErrorDetail(); break; } else { virtualHosts.add(virtualHost.getStruct()); } } if (errorMessage != null) { break; } rdsUpdates.put(routeConfigName, RdsUpdate.fromVirtualHosts(virtualHosts)); } if (errorMessage != null) { nackResponse(ResourceType.RDS, nonce, errorMessage); return; } ackResponse(ResourceType.RDS, versionInfo, nonce); for (String resource : rdsResourceSubscribers.keySet()) { if (rdsUpdates.containsKey(resource)) { ResourceSubscriber subscriber = rdsResourceSubscribers.get(resource); subscriber.onData(rdsUpdates.get(resource)); } } } @Override protected void handleCdsResponse(String versionInfo, List<Any> resources, String nonce) { // Unpack Cluster messages. List<Cluster> clusters = new ArrayList<>(resources.size()); List<String> clusterNames = new ArrayList<>(resources.size()); try { for (com.google.protobuf.Any res : resources) { if (res.getTypeUrl().equals(ResourceType.CDS.typeUrlV2())) { res = res.toBuilder().setTypeUrl(ResourceType.CDS.typeUrl()).build(); } Cluster cluster = res.unpack(Cluster.class); clusters.add(cluster); clusterNames.add(cluster.getName()); } } catch (InvalidProtocolBufferException e) { getLogger().log(XdsLogLevel.WARNING, "Failed to unpack Clusters in CDS response {0}", e); nackResponse(ResourceType.CDS, nonce, "Malformed CDS response: " + e); return; } getLogger().log(XdsLogLevel.INFO, "Received CDS response for resources: {0}", clusterNames); String errorMessage = null; // Cluster information update for requested clusters received in this CDS response. Map<String, CdsUpdate> cdsUpdates = new HashMap<>(); // CDS responses represents the state of the world, EDS services not referenced by // Clusters are those no longer exist. Set<String> edsServices = new HashSet<>(); for (Cluster cluster : clusters) { String clusterName = cluster.getName(); // Skip information for clusters not requested. // Management server is required to always send newly requested resources, even if they // may have been sent previously (proactively). Thus, client does not need to cache // unrequested resources. if (!cdsResourceSubscribers.containsKey(clusterName)) { continue; } CdsUpdate.Builder updateBuilder = CdsUpdate.newBuilder(); updateBuilder.setClusterName(clusterName); // The type field must be set to EDS. if (!cluster.getType().equals(DiscoveryType.EDS)) { errorMessage = "Cluster " + clusterName + " : only EDS discovery type is supported " + "in gRPC."; break; } // In the eds_cluster_config field, the eds_config field must be set to indicate to // use EDS (must be set to use ADS). EdsClusterConfig edsClusterConfig = cluster.getEdsClusterConfig(); if (!edsClusterConfig.getEdsConfig().hasAds()) { errorMessage = "Cluster " + clusterName + " : field eds_cluster_config must be set to " + "indicate to use EDS over ADS."; break; } // If the service_name field is set, that value will be used for the EDS request. if (!edsClusterConfig.getServiceName().isEmpty()) { updateBuilder.setEdsServiceName(edsClusterConfig.getServiceName()); edsServices.add(edsClusterConfig.getServiceName()); } else { edsServices.add(clusterName); } // The lb_policy field must be set to ROUND_ROBIN. if (!cluster.getLbPolicy().equals(LbPolicy.ROUND_ROBIN)) { errorMessage = "Cluster " + clusterName + " : only round robin load balancing policy is " + "supported in gRPC."; break; } updateBuilder.setLbPolicy("round_robin"); // If the lrs_server field is set, it must have its self field set, in which case the // client should use LRS for load reporting. Otherwise (the lrs_server field is not set), // LRS load reporting will be disabled. if (cluster.hasLrsServer()) { if (!cluster.getLrsServer().hasSelf()) { errorMessage = "Cluster " + clusterName + " : only support enabling LRS for the same " + "management server."; break; } updateBuilder.setLrsServerName(""); } if (cluster.hasCircuitBreakers()) { List<Thresholds> thresholds = cluster.getCircuitBreakers().getThresholdsList(); for (Thresholds threshold : thresholds) { if (threshold.getPriority() != RoutingPriority.DEFAULT) { continue; } if (threshold.hasMaxRequests()) { updateBuilder.setMaxConcurrentRequests(threshold.getMaxRequests().getValue()); } } } try { EnvoyServerProtoData.UpstreamTlsContext upstreamTlsContext = getTlsContextFromCluster(cluster); if (upstreamTlsContext != null && upstreamTlsContext.getCommonTlsContext() != null) { updateBuilder.setUpstreamTlsContext(upstreamTlsContext); } } catch (InvalidProtocolBufferException e) { errorMessage = "Cluster " + clusterName + " : " + e.getMessage(); break; } cdsUpdates.put(clusterName, updateBuilder.build()); } if (errorMessage != null) { nackResponse(ResourceType.CDS, nonce, errorMessage); return; } ackResponse(ResourceType.CDS, versionInfo, nonce); for (String resource : cdsResourceSubscribers.keySet()) { ResourceSubscriber subscriber = cdsResourceSubscribers.get(resource); if (cdsUpdates.containsKey(resource)) { subscriber.onData(cdsUpdates.get(resource)); } else { subscriber.onAbsent(); } } for (String resource : edsResourceSubscribers.keySet()) { ResourceSubscriber subscriber = edsResourceSubscribers.get(resource); if (!edsServices.contains(resource)) { subscriber.onAbsent(); } } } @Nullable private static EnvoyServerProtoData.UpstreamTlsContext getTlsContextFromCluster(Cluster cluster) throws InvalidProtocolBufferException { if (cluster.hasTransportSocket() && TRANSPORT_SOCKET_NAME_TLS.equals(cluster.getTransportSocket().getName())) { Any any = cluster.getTransportSocket().getTypedConfig(); if (any.getTypeUrl().equals(TYPE_URL_UPSTREAM_TLS_CONTEXT_V2)) { any = any.toBuilder().setTypeUrl(TYPE_URL_UPSTREAM_TLS_CONTEXT).build(); } return EnvoyServerProtoData.UpstreamTlsContext.fromEnvoyProtoUpstreamTlsContext( any.unpack(UpstreamTlsContext.class)); } return null; } @Override protected void handleEdsResponse(String versionInfo, List<Any> resources, String nonce) { // Unpack ClusterLoadAssignment messages. List<ClusterLoadAssignment> clusterLoadAssignments = new ArrayList<>(resources.size()); List<String> claNames = new ArrayList<>(resources.size()); try { for (com.google.protobuf.Any res : resources) { if (res.getTypeUrl().equals(ResourceType.EDS.typeUrlV2())) { res = res.toBuilder().setTypeUrl(ResourceType.EDS.typeUrl()).build(); } ClusterLoadAssignment assignment = res.unpack(ClusterLoadAssignment.class); clusterLoadAssignments.add(assignment); claNames.add(assignment.getClusterName()); } } catch (InvalidProtocolBufferException e) { getLogger().log( XdsLogLevel.WARNING, "Failed to unpack ClusterLoadAssignments in EDS response {0}", e); nackResponse(ResourceType.EDS, nonce, "Malformed EDS response: " + e); return; } getLogger().log(XdsLogLevel.INFO, "Received EDS response for resources: {0}", claNames); String errorMessage = null; // Endpoint information updates for requested clusters received in this EDS response. Map<String, EdsUpdate> edsUpdates = new HashMap<>(); // Walk through each ClusterLoadAssignment message. If any of them for requested clusters // contain invalid information for gRPC's load balancing usage, the whole response is rejected. for (ClusterLoadAssignment assignment : clusterLoadAssignments) { String clusterName = assignment.getClusterName(); // Skip information for clusters not requested. // Management server is required to always send newly requested resources, even if they // may have been sent previously (proactively). Thus, client does not need to cache // unrequested resources. if (!edsResourceSubscribers.containsKey(clusterName)) { continue; } EdsUpdate.Builder updateBuilder = EdsUpdate.newBuilder(); updateBuilder.setClusterName(clusterName); Set<Integer> priorities = new HashSet<>(); int maxPriority = -1; for (io.envoyproxy.envoy.config.endpoint.v3.LocalityLbEndpoints localityLbEndpoints : assignment.getEndpointsList()) { // Filter out localities without or with 0 weight. if (!localityLbEndpoints.hasLoadBalancingWeight() || localityLbEndpoints.getLoadBalancingWeight().getValue() < 1) { continue; } int localityPriority = localityLbEndpoints.getPriority(); if (localityPriority < 0) { errorMessage = "ClusterLoadAssignment " + clusterName + " : locality with negative priority."; break; } maxPriority = Math.max(maxPriority, localityPriority); priorities.add(localityPriority); // The endpoint field of each lb_endpoints must be set. // Inside of it: the address field must be set. for (LbEndpoint lbEndpoint : localityLbEndpoints.getLbEndpointsList()) { if (!lbEndpoint.getEndpoint().hasAddress()) { errorMessage = "ClusterLoadAssignment " + clusterName + " : endpoint with no address."; break; } } if (errorMessage != null) { break; } // Note endpoints with health status other than UNHEALTHY and UNKNOWN are still // handed over to watching parties. It is watching parties' responsibility to // filter out unhealthy endpoints. See EnvoyProtoData.LbEndpoint#isHealthy(). updateBuilder.addLocalityLbEndpoints( Locality.fromEnvoyProtoLocality(localityLbEndpoints.getLocality()), LocalityLbEndpoints.fromEnvoyProtoLocalityLbEndpoints(localityLbEndpoints)); } if (errorMessage != null) { break; } if (priorities.size() != maxPriority + 1) { errorMessage = "ClusterLoadAssignment " + clusterName + " : sparse priorities."; break; } for (ClusterLoadAssignment.Policy.DropOverload dropOverload : assignment.getPolicy().getDropOverloadsList()) { updateBuilder.addDropPolicy(DropOverload.fromEnvoyProtoDropOverload(dropOverload)); } EdsUpdate update = updateBuilder.build(); edsUpdates.put(clusterName, update); } if (errorMessage != null) { nackResponse(ResourceType.EDS, nonce, errorMessage); return; } ackResponse(ResourceType.EDS, versionInfo, nonce); for (String resource : edsResourceSubscribers.keySet()) { ResourceSubscriber subscriber = edsResourceSubscribers.get(resource); if (edsUpdates.containsKey(resource)) { subscriber.onData(edsUpdates.get(resource)); } } } @Override protected void handleStreamClosed(Status error) { cleanUpResourceTimers(); for (ResourceSubscriber subscriber : ldsResourceSubscribers.values()) { subscriber.onError(error); } for (ResourceSubscriber subscriber : rdsResourceSubscribers.values()) { subscriber.onError(error); } for (ResourceSubscriber subscriber : cdsResourceSubscribers.values()) { subscriber.onError(error); } for (ResourceSubscriber subscriber : edsResourceSubscribers.values()) { subscriber.onError(error); } } @Override protected void handleStreamRestarted() { for (ResourceSubscriber subscriber : ldsResourceSubscribers.values()) { subscriber.restartTimer(); } for (ResourceSubscriber subscriber : rdsResourceSubscribers.values()) { subscriber.restartTimer(); } for (ResourceSubscriber subscriber : cdsResourceSubscribers.values()) { subscriber.restartTimer(); } for (ResourceSubscriber subscriber : edsResourceSubscribers.values()) { subscriber.restartTimer(); } } @Override protected void handleShutdown() { if (reportingLoad) { lrsClient.stopLoadReporting(); } cleanUpResourceTimers(); } @Nullable @Override Collection<String> getSubscribedResources(ResourceType type) { switch (type) { case LDS: return ldsResourceSubscribers.isEmpty() ? null : ldsResourceSubscribers.keySet(); case RDS: return rdsResourceSubscribers.isEmpty() ? null : rdsResourceSubscribers.keySet(); case CDS: return cdsResourceSubscribers.isEmpty() ? null : cdsResourceSubscribers.keySet(); case EDS: return edsResourceSubscribers.isEmpty() ? null : edsResourceSubscribers.keySet(); case UNKNOWN: default: throw new AssertionError("Unknown resource type"); } } @Override void watchLdsResource(final String resourceName, final LdsResourceWatcher watcher) { getSyncContext().execute(new Runnable() { @Override public void run() { ResourceSubscriber subscriber = ldsResourceSubscribers.get(resourceName); if (subscriber == null) { getLogger().log(XdsLogLevel.INFO, "Subscribe CDS resource {0}", resourceName); subscriber = new ResourceSubscriber(ResourceType.LDS, resourceName); ldsResourceSubscribers.put(resourceName, subscriber); adjustResourceSubscription(ResourceType.LDS); } subscriber.addWatcher(watcher); } }); } @Override void cancelLdsResourceWatch(final String resourceName, final LdsResourceWatcher watcher) { getSyncContext().execute(new Runnable() { @Override public void run() { ResourceSubscriber subscriber = ldsResourceSubscribers.get(resourceName); subscriber.removeWatcher(watcher); if (!subscriber.isWatched()) { subscriber.stopTimer(); getLogger().log(XdsLogLevel.INFO, "Unsubscribe LDS resource {0}", resourceName); ldsResourceSubscribers.remove(resourceName); adjustResourceSubscription(ResourceType.LDS); } } }); } @Override void watchRdsResource(final String resourceName, final RdsResourceWatcher watcher) { getSyncContext().execute(new Runnable() { @Override public void run() { ResourceSubscriber subscriber = rdsResourceSubscribers.get(resourceName); if (subscriber == null) { getLogger().log(XdsLogLevel.INFO, "Subscribe RDS resource {0}", resourceName); subscriber = new ResourceSubscriber(ResourceType.RDS, resourceName); rdsResourceSubscribers.put(resourceName, subscriber); adjustResourceSubscription(ResourceType.RDS); } subscriber.addWatcher(watcher); } }); } @Override void cancelRdsResourceWatch(final String resourceName, final RdsResourceWatcher watcher) { getSyncContext().execute(new Runnable() { @Override public void run() { ResourceSubscriber subscriber = rdsResourceSubscribers.get(resourceName); subscriber.removeWatcher(watcher); if (!subscriber.isWatched()) { subscriber.stopTimer(); getLogger().log(XdsLogLevel.INFO, "Unsubscribe RDS resource {0}", resourceName); rdsResourceSubscribers.remove(resourceName); adjustResourceSubscription(ResourceType.RDS); } } }); } @Override void watchCdsResource(final String resourceName, final CdsResourceWatcher watcher) { getSyncContext().execute(new Runnable() { @Override public void run() { ResourceSubscriber subscriber = cdsResourceSubscribers.get(resourceName); if (subscriber == null) { getLogger().log(XdsLogLevel.INFO, "Subscribe CDS resource {0}", resourceName); subscriber = new ResourceSubscriber(ResourceType.CDS, resourceName); cdsResourceSubscribers.put(resourceName, subscriber); adjustResourceSubscription(ResourceType.CDS); } subscriber.addWatcher(watcher); } }); } @Override void cancelCdsResourceWatch(final String resourceName, final CdsResourceWatcher watcher) { getSyncContext().execute(new Runnable() { @Override public void run() { ResourceSubscriber subscriber = cdsResourceSubscribers.get(resourceName); subscriber.removeWatcher(watcher); if (!subscriber.isWatched()) { subscriber.stopTimer(); getLogger().log(XdsLogLevel.INFO, "Unsubscribe CDS resource {0}", resourceName); cdsResourceSubscribers.remove(resourceName); adjustResourceSubscription(ResourceType.CDS); } } }); } @Override void watchEdsResource(final String resourceName, final EdsResourceWatcher watcher) { getSyncContext().execute(new Runnable() { @Override public void run() { ResourceSubscriber subscriber = edsResourceSubscribers.get(resourceName); if (subscriber == null) { getLogger().log(XdsLogLevel.INFO, "Subscribe EDS resource {0}", resourceName); subscriber = new ResourceSubscriber(ResourceType.EDS, resourceName); edsResourceSubscribers.put(resourceName, subscriber); adjustResourceSubscription(ResourceType.EDS); } subscriber.addWatcher(watcher); } }); } @Override void cancelEdsResourceWatch(final String resourceName, final EdsResourceWatcher watcher) { getSyncContext().execute(new Runnable() { @Override public void run() { ResourceSubscriber subscriber = edsResourceSubscribers.get(resourceName); subscriber.removeWatcher(watcher); if (!subscriber.isWatched()) { subscriber.stopTimer(); getLogger().log(XdsLogLevel.INFO, "Unsubscribe EDS resource {0}", resourceName); edsResourceSubscribers.remove(resourceName); adjustResourceSubscription(ResourceType.EDS); } } }); } @Override LoadStatsStore addClientStats(String clusterName, @Nullable String clusterServiceName) { LoadStatsStore loadStatsStore; synchronized (this) { loadStatsStore = loadStatsManager.addLoadStats(clusterName, clusterServiceName); } getSyncContext().execute(new Runnable() { @Override public void run() { if (!reportingLoad) { lrsClient.startLoadReporting(); reportingLoad = true; } } }); return loadStatsStore; } @Override void removeClientStats(String clusterName, @Nullable String clusterServiceName) { synchronized (this) { loadStatsManager.removeLoadStats(clusterName, clusterServiceName); } } private void cleanUpResourceTimers() { for (ResourceSubscriber subscriber : ldsResourceSubscribers.values()) { subscriber.stopTimer(); } for (ResourceSubscriber subscriber : rdsResourceSubscribers.values()) { subscriber.stopTimer(); } for (ResourceSubscriber subscriber : cdsResourceSubscribers.values()) { subscriber.stopTimer(); } for (ResourceSubscriber subscriber : edsResourceSubscribers.values()) { subscriber.stopTimer(); } } /** * Tracks a single subscribed resource. */ private final class ResourceSubscriber { private final ResourceType type; private final String resource; private final Set<ResourceWatcher> watchers = new HashSet<>(); private ResourceUpdate data; private boolean absent; private ScheduledHandle respTimer; ResourceSubscriber(ResourceType type, String resource) { this.type = type; this.resource = resource; if (isInBackoff()) { return; } restartTimer(); } void addWatcher(ResourceWatcher watcher) { checkArgument(!watchers.contains(watcher), "watcher %s already registered", watcher); watchers.add(watcher); if (data != null) { notifyWatcher(watcher, data); } else if (absent) { watcher.onResourceDoesNotExist(resource); } } void removeWatcher(ResourceWatcher watcher) { checkArgument(watchers.contains(watcher), "watcher %s not registered", watcher); watchers.remove(watcher); } void restartTimer() { if (data != null || absent) { // resource already resolved return; } class ResourceNotFound implements Runnable { @Override public void run() { getLogger().log(XdsLogLevel.INFO, "{0} resource {1} initial fetch timeout", type, resource); respTimer = null; onAbsent(); } @Override public String toString() { return type + this.getClass().getSimpleName(); } } respTimer = getSyncContext().schedule( new ResourceNotFound(), INITIAL_RESOURCE_FETCH_TIMEOUT_SEC, TimeUnit.SECONDS, getTimeService()); } void stopTimer() { if (respTimer != null && respTimer.isPending()) { respTimer.cancel(); respTimer = null; } } boolean isWatched() { return !watchers.isEmpty(); } void onData(ResourceUpdate data) { if (respTimer != null && respTimer.isPending()) { respTimer.cancel(); respTimer = null; } ResourceUpdate oldData = this.data; this.data = data; absent = false; if (!Objects.equals(oldData, data)) { for (ResourceWatcher watcher : watchers) { notifyWatcher(watcher, data); } } } void onAbsent() { if (respTimer != null && respTimer.isPending()) { // too early to conclude absence return; } getLogger().log(XdsLogLevel.INFO, "Conclude {0} resource {1} not exist", type, resource); if (!absent) { data = null; absent = true; for (ResourceWatcher watcher : watchers) { watcher.onResourceDoesNotExist(resource); } } } void onError(Status error) { if (respTimer != null && respTimer.isPending()) { respTimer.cancel(); respTimer = null; } for (ResourceWatcher watcher : watchers) { watcher.onError(error); } } private void notifyWatcher(ResourceWatcher watcher, ResourceUpdate update) { switch (type) { case LDS: ((LdsResourceWatcher) watcher).onChanged((LdsUpdate) update); break; case RDS: ((RdsResourceWatcher) watcher).onChanged((RdsUpdate) update); break; case CDS: ((CdsResourceWatcher) watcher).onChanged((CdsUpdate) update); break; case EDS: ((EdsResourceWatcher) watcher).onChanged((EdsUpdate) update); break; case UNKNOWN: default: throw new AssertionError("should never be here"); } } } }
xds: fix typo in a log message (#7762)
xds/src/main/java/io/grpc/xds/ClientXdsClient.java
xds: fix typo in a log message (#7762)
<ide><path>ds/src/main/java/io/grpc/xds/ClientXdsClient.java <ide> public void run() { <ide> ResourceSubscriber subscriber = ldsResourceSubscribers.get(resourceName); <ide> if (subscriber == null) { <del> getLogger().log(XdsLogLevel.INFO, "Subscribe CDS resource {0}", resourceName); <add> getLogger().log(XdsLogLevel.INFO, "Subscribe LDS resource {0}", resourceName); <ide> subscriber = new ResourceSubscriber(ResourceType.LDS, resourceName); <ide> ldsResourceSubscribers.put(resourceName, subscriber); <ide> adjustResourceSubscription(ResourceType.LDS);
Java
mit
b8b775fa8576e982918531249179867bd411ebad
0
turbolinks/turbolinks-android,timoschloesser/turbolinks-android,timoschloesser/turbolinks-android,timoschloesser/turbolinks-android,gavinliu/turbolinks-android,timoschloesser/turbolinks-android,gavinliu/turbolinks-android,gavinliu/turbolinks-android,turbolinks/turbolinks-android,turbolinks/turbolinks-android,turbolinks/turbolinks-android,gavinliu/turbolinks-android
package com.basecamp.turbolinks; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.MutableContextWrapper; import android.graphics.Bitmap; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.v4.widget.SwipeRefreshLayout; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.ValueCallback; import android.webkit.WebResourceRequest; import android.webkit.WebResourceResponse; import android.webkit.WebView; import android.webkit.WebViewClient; import java.util.Date; import java.util.HashMap; /** * <p>The main concrete class to use Turbolinks 5 in your app.</p> */ public class TurbolinksSession implements CanScrollUpCallback { // --------------------------------------------------- // Package public vars (allows for greater flexibility and access for testing) // --------------------------------------------------- boolean bridgeInjectionInProgress; // Ensures the bridge is only injected once boolean coldBootInProgress; boolean restoreWithCachedSnapshot; boolean turbolinksIsReady; // Script finished and TL fully instantiated boolean screenshotsEnabled; boolean pullToRefreshEnabled; int progressIndicatorDelay; long previousOverrideTime; Activity activity; HashMap<String, Object> javascriptInterfaces = new HashMap<>(); HashMap<String, String> restorationIdentifierMap = new HashMap<>(); String location; String currentVisitIdentifier; TurbolinksAdapter turbolinksAdapter; TurbolinksView turbolinksView; TurbolinksSwipeRefreshLayout swipeRefreshLayout; View progressView; View progressIndicator; static volatile TurbolinksSession defaultInstance; // --------------------------------------------------- // Final vars // --------------------------------------------------- static final String ACTION_ADVANCE = "advance"; static final String ACTION_RESTORE = "restore"; static final String ACTION_REPLACE = "replace"; static final String JAVASCRIPT_INTERFACE_NAME = "TurbolinksNative"; static final int PROGRESS_INDICATOR_DELAY = 500; final Context applicationContext; final WebView webView; // --------------------------------------------------- // Constructor // --------------------------------------------------- /** * Private constructor called to return a new Turbolinks instance. * * @param context Any Android context. */ private TurbolinksSession(final Context context) { if (context == null) { throw new IllegalArgumentException("Context must not be null."); } this.applicationContext = context.getApplicationContext(); this.screenshotsEnabled = true; this.pullToRefreshEnabled = true; this.swipeRefreshLayout = new TurbolinksSwipeRefreshLayout(context, null); this.swipeRefreshLayout.setCallback(this); this.swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { visitLocationWithAction(location, ACTION_REPLACE); } }); this.webView = TurbolinksHelper.createWebView(applicationContext); this.webView.addJavascriptInterface(this, JAVASCRIPT_INTERFACE_NAME); this.webView.setWebViewClient(new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { coldBootInProgress = true; } @Override public void onPageFinished(WebView view, final String location) { String jsCall = "window.webView == null"; webView.evaluateJavascript(jsCall, new ValueCallback<String>() { @Override public void onReceiveValue(String s) { if (Boolean.parseBoolean(s) && !bridgeInjectionInProgress) { bridgeInjectionInProgress = true; TurbolinksHelper.injectTurbolinksBridge(TurbolinksSession.this, applicationContext, webView); TurbolinksLog.d("Bridge injected"); turbolinksAdapter.onPageFinished(); } } }); } /** * Turbolinks will not call adapter.visitProposedToLocationWithAction in some cases, * like target=_blank or when the domain doesn't match. We still route those here. * This is mainly only called when links within a webView are clicked and not during * loadUrl. However, a redirect on a cold boot can also cause this to fire, so don't * override in that situation, since Turbolinks is not yet ready. * http://stackoverflow.com/a/6739042/3280911 */ @Override public boolean shouldOverrideUrlLoading(WebView view, String location) { if (!turbolinksIsReady || coldBootInProgress) { return false; } /** * Prevents firing twice in a row within a few milliseconds of each other, which * happens. So we check for a slight delay between requests, which is plenty of time * to allow for a user to click the same link again. */ long currentOverrideTime = new Date().getTime(); if ((currentOverrideTime - previousOverrideTime) > 500) { previousOverrideTime = currentOverrideTime; TurbolinksLog.d("Overriding load: " + location); visitProposedToLocationWithAction(location, ACTION_ADVANCE); } return true; } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); resetToColdBoot(); turbolinksAdapter.onReceivedError(errorCode); TurbolinksLog.d("onReceivedError: " + errorCode); } @Override @TargetApi(Build.VERSION_CODES.M) public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) { super.onReceivedHttpError(view, request, errorResponse); if (request.isForMainFrame()) { resetToColdBoot(); turbolinksAdapter.onReceivedError(errorResponse.getStatusCode()); TurbolinksLog.d("onReceivedHttpError: " + errorResponse.getStatusCode()); } } }); } // --------------------------------------------------- // Initialization // --------------------------------------------------- /** * Creates a brand new TurbolinksSession that the calling application will be responsible for * managing. * * @param context Any Android context. * @return TurbolinksSession to be managed by the calling application. */ public static TurbolinksSession getNew(Context context) { TurbolinksLog.d("TurbolinksSession getNew called"); return new TurbolinksSession(context); } /** * Convenience method that returns a default TurbolinksSession. This is useful for when an * app only needs one instance of a TurbolinksSession. * * @param context Any Android context. * @return The default, static instance of a TurbolinksSession, guaranteed to not be null. */ public static TurbolinksSession getDefault(Context context) { if (defaultInstance == null) { synchronized (TurbolinksSession.class) { if (defaultInstance == null) { TurbolinksLog.d("Default instance is null, creating new"); defaultInstance = TurbolinksSession.getNew(context); } } } return defaultInstance; } /** * Resets the default TurbolinksSession instance to null in case you want a fresh session. */ public static void resetDefault() { defaultInstance = null; } // --------------------------------------------------- // Required chained methods // --------------------------------------------------- /** * <p><b>REQUIRED</b> Turbolinks requires a context for a variety of uses, and for maximum clarity * we ask for an Activity context instead of a generic one. (On occassion, we've run into WebView * bugs where an Activity is the only fix).</p> * * <p>It's best to pass a new activity to Turbolinks for each new visit for clarity. This ensures * there is a one-to-one relationship maintained between internal activity IDs and visit IDs.</p> * * @param activity An Android Activity, one per visit. * @return The TurbolinksSession to continue the chained calls. */ public TurbolinksSession activity(Activity activity) { this.activity = activity; Context webViewContext = webView.getContext(); if (webViewContext instanceof MutableContextWrapper) { ((MutableContextWrapper) webViewContext).setBaseContext(this.activity); } return this; } /** * <p><b>REQUIRED</b> A {@link TurbolinksAdapter} implementation is required so that callbacks * during the Turbolinks event lifecycle can be passed back to your app.</p> * * @param turbolinksAdapter Any class that implements {@link TurbolinksAdapter}. * @return The TurbolinksSession to continue the chained calls. */ public TurbolinksSession adapter(TurbolinksAdapter turbolinksAdapter) { this.turbolinksAdapter = turbolinksAdapter; return this; } /** * <p><b>REQUIRED</b> A {@link TurbolinksView} object that's been inflated in a custom layout is * required so the library can manage various view-related tasks: attaching/detaching the * internal webView, showing/hiding a progress loading view, etc.</p> * * @param turbolinksView An inflated TurbolinksView from your custom layout. * @return The TurbolinksSession to continue the chained calls. */ public TurbolinksSession view(TurbolinksView turbolinksView) { this.turbolinksView = turbolinksView; this.turbolinksView.attachWebView(webView, swipeRefreshLayout, screenshotsEnabled, pullToRefreshEnabled); return this; } /** * <p><b>REQUIRED</b> Executes a Turbolinks visit. Must be called at the end of the chain -- * all required parameters will first be validated before firing.</p> * * @param location The URL to visit. */ public void visit(String location) { TurbolinksLog.d("visit called"); this.location = location; validateRequiredParams(); initProgressView(); if (turbolinksIsReady) { visitCurrentLocationWithTurbolinks(); } if (!turbolinksIsReady && !coldBootInProgress) { TurbolinksLog.d("Cold booting: " + location); webView.loadUrl(location); } // Reset so that cached snapshot is not the default for the next visit restoreWithCachedSnapshot = false; /* if (!turbolinksIsReady && coldBootInProgress), we don't fire a new visit. This is typically a slow connection load. This allows the previous cold boot to finish (inject TL). No matter what, if new requests are sent to Turbolinks via Turbolinks.location, we'll always have the last desired location. And when setTurbolinksIsReady(true) is called, we open that last location. */ } // --------------------------------------------------- // Optional chained methods // --------------------------------------------------- /** * <p><b>Optional</b> This will override the default progress view/progress indicator that's provided * out of the box. This allows you to customize how you want the progress view to look while * pages are loading.</p> * * @param progressView A custom progressView object. * @param progressIndicatorResId The resource ID of a progressIndicator object inside the progressView. * @param progressIndicatorDelay The delay, in milliseconds, before the progress indicator should be displayed * inside the progress view (default is 500 ms). * @return The TurbolinksSession to continue the chained calls. */ public TurbolinksSession progressView(View progressView, int progressIndicatorResId, int progressIndicatorDelay) { this.progressView = progressView; this.progressIndicator = progressView.findViewById(progressIndicatorResId); this.progressIndicatorDelay = progressIndicatorDelay; if (this.progressIndicator == null) { throw new IllegalArgumentException("A progress indicator view must be provided in your custom progressView."); } return this; } /** * <p><b>Optional</b> By default Turbolinks will "advance" to the next page and scroll position * will not be restored. Optionally calling this method allows you to set the behavior on a * per-visitbasis. This will be reset to "false" after each visit.</p> * * @param restoreWithCachedSnapshot If true, will restore scroll position. If false, will not restore * scroll position. * @return The TurbolinksSession to continue the chained calls. */ public TurbolinksSession restoreWithCachedSnapshot(boolean restoreWithCachedSnapshot) { this.restoreWithCachedSnapshot = restoreWithCachedSnapshot; return this; } // --------------------------------------------------- // TurbolinksNative adapter methods // --------------------------------------------------- /** * <p><b>JavascriptInterface only</b> Called by Turbolinks when a new visit is initiated from a * webView link.</p> * * <p>Warning: This method is public so it can be used as a Javascript Interface. you should * never call this directly as it could lead to unintended behavior.</p> * * @param location URL to be visited. * @param action Whether to treat the request as an advance (navigating forward) or a replace (back). */ @SuppressWarnings("unused") @android.webkit.JavascriptInterface public void visitProposedToLocationWithAction(final String location, final String action) { TurbolinksLog.d("visitProposedToLocationWithAction called"); TurbolinksHelper.runOnMainThread(applicationContext, new Runnable() { @Override public void run() { turbolinksAdapter.visitProposedToLocationWithAction(location, action); } }); } /** * <p><b>JavascriptInterface only</b> Called by Turbolinks when a new visit has just started.</p> * * <p>Warning: This method is public so it can be used as a Javascript Interface. you should * never call this directly as it could lead to unintended behavior.</p> * * @param visitIdentifier A unique identifier for the visit. * @param visitHasCachedSnapshot Whether the visit has a cached snapshot available. */ @SuppressWarnings("unused") @android.webkit.JavascriptInterface public void visitStarted(String visitIdentifier, boolean visitHasCachedSnapshot) { TurbolinksLog.d("visitStarted called"); currentVisitIdentifier = visitIdentifier; runJavascript("webView.changeHistoryForVisitWithIdentifier", visitIdentifier); runJavascript("webView.issueRequestForVisitWithIdentifier", visitIdentifier); runJavascript("webView.loadCachedSnapshotForVisitWithIdentifier", visitIdentifier); } /** * <p><b>JavascriptInterface only</b> Called by Turbolinks when the HTTP request has been * completed.</p> * * <p>Warning: This method is public so it can be used as a Javascript Interface. you should * never call this directly as it could lead to unintended behavior.</p> * * @param visitIdentifier A unique identifier for the visit. */ @SuppressWarnings("unused") @android.webkit.JavascriptInterface public void visitRequestCompleted(String visitIdentifier) { TurbolinksLog.d("visitRequestCompleted called"); if (TextUtils.equals(visitIdentifier, currentVisitIdentifier)) { runJavascript("webView.loadResponseForVisitWithIdentifier", visitIdentifier); } } /** * <p><b>JavascriptInterface only</b> Called by Turbolinks when the HTTP request has failed.</p> * * <p>Warning: This method is public so it can be used as a Javascript Interface. you should * never call this directly as it could lead to unintended behavior.</p> * * @param visitIdentifier A unique identifier for the visit. * @param statusCode The HTTP status code that caused the failure. */ @SuppressWarnings("unused") @android.webkit.JavascriptInterface public void visitRequestFailedWithStatusCode(final String visitIdentifier, final int statusCode) { TurbolinksLog.d("visitRequestFailedWithStatusCode called"); hideProgressView(visitIdentifier); if (TextUtils.equals(visitIdentifier, currentVisitIdentifier)) { TurbolinksHelper.runOnMainThread(applicationContext, new Runnable() { @Override public void run() { turbolinksAdapter.requestFailedWithStatusCode(statusCode); } }); } } /** * <p><b>JavascriptInterface only</b> Called by Turbolinks once the page has been fully rendered * in the webView.</p> * * <p>Warning: This method is public so it can be used as a Javascript Interface. you should * never call this directly as it could lead to unintended behavior.</p> * * @param visitIdentifier A unique identifier for the visit. */ @SuppressWarnings("unused") @android.webkit.JavascriptInterface public void visitRendered(String visitIdentifier) { TurbolinksLog.d("visitRendered called, hiding progress view for identifier: " + visitIdentifier); hideProgressView(visitIdentifier); } /** * <p><b>JavascriptInterface only</b> Called by Turbolinks when the visit is fully completed -- * request successful and page rendered.</p> * * <p>Warning: This method is public so it can be used as a Javascript Interface. you should * never call this directly as it could lead to unintended behavior.</p> * * @param visitIdentifier A unique identifier for the visit. * @param restorationIdentifier A unique identifier for restoring the page and scroll position * from cache. */ @SuppressWarnings("unused") @android.webkit.JavascriptInterface public void visitCompleted(String visitIdentifier, String restorationIdentifier) { TurbolinksLog.d("visitCompleted called"); addRestorationIdentifierToMap(restorationIdentifier); if (TextUtils.equals(visitIdentifier, currentVisitIdentifier)) { TurbolinksHelper.runOnMainThread(applicationContext, new Runnable() { @Override public void run() { turbolinksAdapter.visitCompleted(); swipeRefreshLayout.setRefreshing(false); } }); } } /** * <p><b>JavascriptInterface only</b> Called when Turbolinks detects that the page being visited * has been invalidated, typically by new resources in the the page HEAD.</p> * * <p>Warning: This method is public so it can be used as a Javascript Interface. you should * never call this directly as it could lead to unintended behavior.</p> */ @SuppressWarnings("unused") @android.webkit.JavascriptInterface public void pageInvalidated() { TurbolinksLog.d("pageInvalidated called"); resetToColdBoot(); TurbolinksHelper.runOnMainThread(applicationContext, new Runnable() { @Override public void run() { // route through normal chain so progress view is shown, regular logging, etc. turbolinksAdapter.pageInvalidated(); visit(location); } }); } // --------------------------------------------------- // TurbolinksNative helper methods // --------------------------------------------------- /** * <p><b>JavascriptInterface only</b> Hides the progress view when the page is fully rendered.</p> * * <p>Note: This method is public so it can be used as a Javascript Interface. For all practical * purposes, you should never call this directly.</p> * * @param visitIdentifier A unique identifier for the visit. */ @SuppressWarnings("unused") @android.webkit.JavascriptInterface public void hideProgressView(final String visitIdentifier) { TurbolinksHelper.runOnMainThread(applicationContext, new Runnable() { @Override public void run() { /** * pageInvalidated will cold boot, but another in-flight response from * visitResponseLoaded could attempt to hide the progress view. Checking * turbolinksIsReady ensures progress view isn't hidden too soon by the non cold boot. */ if (turbolinksIsReady && TextUtils.equals(visitIdentifier, currentVisitIdentifier)) { TurbolinksLog.d("Hiding progress view for visitIdentifier: " + visitIdentifier + ", currentVisitIdentifier: " + currentVisitIdentifier); turbolinksView.hideProgress(); progressView = null; } } }); } /** * <p><b>JavascriptInterface only</b> Sets internal flags that indicate whether Turbolinks in * the webView is ready for use.</p> * * <p>Note: This method is public so it can be used as a Javascript Interface. For all practical * purposes, you should never call this directly.</p> * * @param turbolinksIsReady The Javascript bridge checks the current page for Turbolinks, and * sends the results of that check here. */ @SuppressWarnings("unused") @android.webkit.JavascriptInterface public void setTurbolinksIsReady(boolean turbolinksIsReady) { this.turbolinksIsReady = turbolinksIsReady; if (turbolinksIsReady) { bridgeInjectionInProgress = false; TurbolinksHelper.runOnMainThread(applicationContext, new Runnable() { @Override public void run() { TurbolinksLog.d("TurbolinksSession is ready"); visitCurrentLocationWithTurbolinks(); } }); coldBootInProgress = false; } else { TurbolinksLog.d("TurbolinksSession is not ready. Resetting and throw error."); resetToColdBoot(); visitRequestFailedWithStatusCode(currentVisitIdentifier, 500); } } /** * <p><b>JavascriptInterface only</b> Handles the error condition when reaching a page without * Turbolinks.</p> * * <p>Note: This method is public so it can be used as a Javascript Interface. For all practical * purposes, you should never call this directly.</p> */ @SuppressWarnings("unused") @android.webkit.JavascriptInterface public void turbolinksDoesNotExist() { TurbolinksHelper.runOnMainThread(applicationContext, new Runnable() { @Override public void run() { TurbolinksLog.d("Error instantiating turbolinks_bridge.js - resetting to cold boot."); resetToColdBoot(); turbolinksView.hideProgress(); } }); } // ----------------------------------------------------------------------- // Public // ----------------------------------------------------------------------- /** * <p>Provides the ability to add an arbitrary number of custom Javascript Interfaces to the built-in * Turbolinks webView.</p> * * @param object The object with annotated JavascriptInterface methods * @param name The unique name for the interface (must not use the reserved name "TurbolinksNative") */ @SuppressLint("JavascriptInterface") public void addJavascriptInterface(Object object, String name) { if (TextUtils.equals(name, JAVASCRIPT_INTERFACE_NAME)) { throw new IllegalArgumentException(JAVASCRIPT_INTERFACE_NAME + " is a reserved Javascript Interface name."); } if (javascriptInterfaces.get(name) == null) { javascriptInterfaces.put(name, object); webView.addJavascriptInterface(object, name); TurbolinksLog.d("Adding JavascriptInterface: " + name + " for " + object.getClass().toString()); } } /** * <p>Returns the activity attached to the Turbolinks call.</p> * * @return The attached activity. */ public Activity getActivity() { return activity; } /** * <p>Returns the internal WebView used by Turbolinks.</p> * * @return The WebView used by Turbolinks. */ public WebView getWebView() { return webView; } /** * <p>Resets the TurbolinksSession to go through the full cold booting sequence (full page load) * on the next Turbolinks visit.</p> */ public void resetToColdBoot() { bridgeInjectionInProgress = false; turbolinksIsReady = false; coldBootInProgress = false; } /** * <p>Runs a Javascript function with any number of arbitrary params in the Turbolinks webView.</p> * * @param functionName The name of the function, without any parenthesis or params * @param params A comma delimited list of params. Params will be automatically JSONified. */ public void runJavascript(final String functionName, final Object... params) { TurbolinksHelper.runJavascript(applicationContext, webView, functionName, params); } /** * <p>Runs raw Javascript in webView. Simply wraps the loadUrl("javascript: methodName()") call.</p> * * @param rawJavascript The full Javascript string that will be executed by the WebView. */ public void runJavascriptRaw(String rawJavascript) { TurbolinksHelper.runJavascriptRaw(applicationContext, webView, rawJavascript); } /** * <p>Tells the logger whether to allow logging in debug mode.</p> * * @param enabled If true debug logging is enabled. */ public void setDebugLoggingEnabled(boolean enabled) { TurbolinksLog.setDebugLoggingEnabled(enabled); } /** * <p>Determines whether screenshots are displayed (instead of a progress view) when resuming * an activity. Default is true.</p> * * @param enabled If true automatic screenshotting is enabled. */ public void setScreenshotsEnabled(boolean enabled) { screenshotsEnabled = enabled; } /** * <p>Determines whether WebViews can be refreshed by pulling/swiping from the top * of the WebView. Default is true.</p> * * @param enabled If true pulling to refresh the WebView is enabled */ public void setPullToRefreshEnabled(boolean enabled) { pullToRefreshEnabled = enabled; } /** * <p>Provides the status of whether Turbolinks is initialized and ready for use.</p> * * @return True if Turbolinks has been fully loaded and detected on the page. */ public boolean turbolinksIsReady() { return turbolinksIsReady; } /** * <p>A convenience method to fire a Turbolinks visit manually.</p> * * @param location URL to visit. * @param action Whether to treat the request as an advance (navigating forward) or a replace (back). */ public void visitLocationWithAction(String location, String action) { runJavascript("webView.visitLocationWithActionAndRestorationIdentifier", TurbolinksHelper.encodeUrl(location), action, getRestorationIdentifierFromMap()); } // --------------------------------------------------- // Private // --------------------------------------------------- /** * <p>Adds the restoration (cached scroll position) identifier to the local Hashmap.</p> * * @param value Restoration ID provided by Turbolinks. */ private void addRestorationIdentifierToMap(String value) { if (activity != null) { restorationIdentifierMap.put(activity.toString(), value); } } /** * <p>Gets the restoration ID for the current activity.</p> * * @return Restoration ID for the current activity. */ private String getRestorationIdentifierFromMap() { return restorationIdentifierMap.get(activity.toString()); } /** * <p>Shows the progress view, either a custom one provided or the default.</p> * * <p>A default progress view is inflated if {@link #progressView} isn't called. * If already inflated, progress view is fully detached before being shown since it's reused.</p> */ private void initProgressView() { // No custom progress view provided, use default if (progressView == null) { progressView = LayoutInflater.from(activity).inflate(R.layout.turbolinks_progress, turbolinksView, false); TurbolinksLog.d("TurbolinksSession background: " + turbolinksView.getBackground()); progressView.setBackground(turbolinksView.getBackground()); progressIndicator = progressView.findViewById(R.id.turbolinks_default_progress_indicator); progressIndicatorDelay = PROGRESS_INDICATOR_DELAY; Drawable background = turbolinksView.getBackground() != null ? turbolinksView.getBackground() : new ColorDrawable(activity.getResources().getColor(android.R.color.white)); progressView.setBackground(background); } // A progress view can be reused, so ensure it's detached from its previous parent first if (progressView.getParent() != null) { ((ViewGroup) progressView.getParent()).removeView(progressView); } // Executed from here to account for progress indicator delay turbolinksView.showProgress(progressView, progressIndicator, progressIndicatorDelay); } /** * <p>Convenience method to simply revisit the current location in the TurbolinksSession. Useful * so that different visit logic can be wrappered around this call in {@link #visit} or * {@link #setTurbolinksIsReady(boolean)}</p> */ private void visitCurrentLocationWithTurbolinks() { TurbolinksLog.d("Visiting current stored location: " + location); String action = restoreWithCachedSnapshot ? ACTION_RESTORE : ACTION_ADVANCE; visitLocationWithAction(location, action); } /** * <p>Ensures all required chained calls/parameters ({@link #activity}, {@link #turbolinksView}, * and location}) are set before calling {@link #visit(String)}.</p> */ private void validateRequiredParams() { if (activity == null) { throw new IllegalArgumentException("TurbolinksSession.activity(activity) must be called with a non-null object."); } if (turbolinksAdapter == null) { throw new IllegalArgumentException("TurbolinksSession.adapter(turbolinksAdapter) must be called with a non-null object."); } if (turbolinksView == null) { throw new IllegalArgumentException("TurbolinksSession.view(turbolinksView) must be called with a non-null object."); } if (TextUtils.isEmpty(location)) { throw new IllegalArgumentException("TurbolinksSession.visit(location) location value must not be null."); } } // --------------------------------------------------- // Interfaces // --------------------------------------------------- /** * <p>Determines if the user can scroll up, or if the WebView is at the top</p> * * @return True if the WebView can be scrolled up. False if the WebView is at the top. */ @Override public boolean canChildScrollUp() { return this.webView.getScrollY() > 0; } }
turbolinks/src/main/java/com/basecamp/turbolinks/TurbolinksSession.java
package com.basecamp.turbolinks; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.MutableContextWrapper; import android.graphics.Bitmap; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.v4.widget.SwipeRefreshLayout; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.ValueCallback; import android.webkit.WebResourceRequest; import android.webkit.WebResourceResponse; import android.webkit.WebView; import android.webkit.WebViewClient; import java.util.Date; import java.util.HashMap; /** * <p>The main concrete class to use Turbolinks 5 in your app.</p> */ public class TurbolinksSession implements CanScrollUpCallback { // --------------------------------------------------- // Package public vars (allows for greater flexibility and access for testing) // --------------------------------------------------- boolean bridgeInjectionInProgress; // Ensures the bridge is only injected once boolean coldBootInProgress; boolean restoreWithCachedSnapshot; boolean turbolinksIsReady; // Script finished and TL fully instantiated boolean screenshotsEnabled; boolean pullToRefreshEnabled; int progressIndicatorDelay; long previousOverrideTime; Activity activity; HashMap<String, Object> javascriptInterfaces = new HashMap<>(); HashMap<String, String> restorationIdentifierMap = new HashMap<>(); String location; String currentVisitIdentifier; TurbolinksAdapter turbolinksAdapter; TurbolinksView turbolinksView; TurbolinksSwipeRefreshLayout swipeRefreshLayout; View progressView; View progressIndicator; static volatile TurbolinksSession defaultInstance; // --------------------------------------------------- // Final vars // --------------------------------------------------- static final String ACTION_ADVANCE = "advance"; static final String ACTION_RESTORE = "restore"; static final String ACTION_REPLACE = "replace"; static final String JAVASCRIPT_INTERFACE_NAME = "TurbolinksNative"; static final int PROGRESS_INDICATOR_DELAY = 500; final Context applicationContext; final WebView webView; // --------------------------------------------------- // Constructor // --------------------------------------------------- /** * Private constructor called to return a new Turbolinks instance. * * @param context Any Android context. */ private TurbolinksSession(final Context context) { if (context == null) { throw new IllegalArgumentException("Context must not be null."); } this.applicationContext = context.getApplicationContext(); this.screenshotsEnabled = true; this.pullToRefreshEnabled = true; this.swipeRefreshLayout = new TurbolinksSwipeRefreshLayout(context, null); this.swipeRefreshLayout.setCallback(this); this.swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { visitLocationWithAction(location, ACTION_REPLACE); } }); this.webView = TurbolinksHelper.createWebView(applicationContext); this.webView.addJavascriptInterface(this, JAVASCRIPT_INTERFACE_NAME); this.webView.setWebViewClient(new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { coldBootInProgress = true; } @Override public void onPageFinished(WebView view, final String location) { String jsCall = "window.webView == null"; webView.evaluateJavascript(jsCall, new ValueCallback<String>() { @Override public void onReceiveValue(String s) { if (Boolean.parseBoolean(s) && !bridgeInjectionInProgress) { bridgeInjectionInProgress = true; TurbolinksHelper.injectTurbolinksBridge(TurbolinksSession.this, applicationContext, webView); TurbolinksLog.d("Bridge injected"); turbolinksAdapter.onPageFinished(); } } }); } /** * Turbolinks will not call adapter.visitProposedToLocationWithAction in some cases, * like target=_blank or when the domain doesn't match. We still route those here. * This is mainly only called when links within a webView are clicked and not during * loadUrl. However, a redirect on a cold boot can also cause this to fire, so don't * override in that situation, since Turbolinks is not yet ready. * http://stackoverflow.com/a/6739042/3280911 */ @Override public boolean shouldOverrideUrlLoading(WebView view, String location) { if (!turbolinksIsReady || coldBootInProgress) { return false; } /** * Prevents firing twice in a row within a few milliseconds of each other, which * happens. So we check for a slight delay between requests, which is plenty of time * to allow for a user to click the same link again. */ long currentOverrideTime = new Date().getTime(); if ((currentOverrideTime - previousOverrideTime) > 500) { previousOverrideTime = currentOverrideTime; TurbolinksLog.d("Overriding load: " + location); visitProposedToLocationWithAction(location, ACTION_ADVANCE); } return true; } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); resetToColdBoot(); turbolinksAdapter.onReceivedError(errorCode); TurbolinksLog.d("onReceivedError: " + errorCode); } @Override @TargetApi(Build.VERSION_CODES.M) public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) { super.onReceivedHttpError(view, request, errorResponse); if (request.isForMainFrame()) { resetToColdBoot(); turbolinksAdapter.onReceivedError(errorResponse.getStatusCode()); TurbolinksLog.d("onReceivedHttpError: " + errorResponse.getStatusCode()); } } }); } // --------------------------------------------------- // Initialization // --------------------------------------------------- /** * Creates a brand new TurbolinksSession that the calling application will be responsible for * managing. * * @param context Any Android context. * @return TurbolinksSession to be managed by the calling application. */ public static TurbolinksSession getNew(Context context) { TurbolinksLog.d("TurbolinksSession getNew called"); return new TurbolinksSession(context); } /** * Convenience method that returns a default TurbolinksSession. This is useful for when an * app only needs one instance of a TurbolinksSession. * * @param context Any Android context. * @return The default, static instance of a TurbolinksSession, guaranteed to not be null. */ public static TurbolinksSession getDefault(Context context) { if (defaultInstance == null) { synchronized (TurbolinksSession.class) { if (defaultInstance == null) { TurbolinksLog.d("Default instance is null, creating new"); defaultInstance = TurbolinksSession.getNew(context); } } } return defaultInstance; } /** * Resets the default TurbolinksSession instance to null in case you want a fresh session. */ public static void resetDefault() { defaultInstance = null; } // --------------------------------------------------- // Required chained methods // --------------------------------------------------- /** * <p><b>REQUIRED</b> Turbolinks requires a context for a variety of uses, and for maximum clarity * we ask for an Activity context instead of a generic one. (On occassion, we've run into WebView * bugs where an Activity is the only fix).</p> * * <p>It's best to pass a new activity to Turbolinks for each new visit for clarity. This ensures * there is a one-to-one relationship maintained between internal activity IDs and visit IDs.</p> * * @param activity An Android Activity, one per visit. * @return The TurbolinksSession to continue the chained calls. */ public TurbolinksSession activity(Activity activity) { this.activity = activity; Context webViewContext = webView.getContext(); if (webViewContext instanceof MutableContextWrapper) { ((MutableContextWrapper) webViewContext).setBaseContext(this.activity); } return this; } /** * <p><b>REQUIRED</b> A {@link TurbolinksAdapter} implementation is required so that callbacks * during the Turbolinks event lifecycle can be passed back to your app.</p> * * @param turbolinksAdapter Any class that implements {@link TurbolinksAdapter}. * @return The TurbolinksSession to continue the chained calls. */ public TurbolinksSession adapter(TurbolinksAdapter turbolinksAdapter) { this.turbolinksAdapter = turbolinksAdapter; return this; } /** * <p><b>REQUIRED</b> A {@link TurbolinksView} object that's been inflated in a custom layout is * required so the library can manage various view-related tasks: attaching/detaching the * internal webView, showing/hiding a progress loading view, etc.</p> * * @param turbolinksView An inflated TurbolinksView from your custom layout. * @return The TurbolinksSession to continue the chained calls. */ public TurbolinksSession view(TurbolinksView turbolinksView) { this.turbolinksView = turbolinksView; this.turbolinksView.attachWebView(webView, swipeRefreshLayout, screenshotsEnabled, pullToRefreshEnabled); return this; } /** * <p><b>REQUIRED</b> Executes a Turbolinks visit. Must be called at the end of the chain -- * all required parameters will first be validated before firing.</p> * * @param location The URL to visit. */ public void visit(String location) { TurbolinksLog.d("visit called"); this.location = location; validateRequiredParams(); initProgressView(); if (turbolinksIsReady) { visitCurrentLocationWithTurbolinks(); } if (!turbolinksIsReady && !coldBootInProgress) { TurbolinksLog.d("Cold booting: " + location); webView.loadUrl(location); } // Reset so that cached snapshot is not the default for the next visit restoreWithCachedSnapshot = false; /* if (!turbolinksIsReady && coldBootInProgress), we don't fire a new visit. This is typically a slow connection load. This allows the previous cold boot to finish (inject TL). No matter what, if new requests are sent to Turbolinks via Turbolinks.location, we'll always have the last desired location. And when setTurbolinksIsReady(true) is called, we open that last location. */ } // --------------------------------------------------- // Optional chained methods // --------------------------------------------------- /** * <p><b>Optional</b> This will override the default progress view/progress indicator that's provided * out of the box. This allows you to customize how you want the progress view to look while * pages are loading.</p> * * @param progressView A custom progressView object. * @param progressIndicatorResId The resource ID of a progressIndicator object inside the progressView. * @param progressIndicatorDelay The delay, in milliseconds, before the progress indicator should be displayed * inside the progress view (default is 500 ms). * @return The TurbolinksSession to continue the chained calls. */ public TurbolinksSession progressView(View progressView, int progressIndicatorResId, int progressIndicatorDelay) { this.progressView = progressView; this.progressIndicator = progressView.findViewById(progressIndicatorResId); this.progressIndicatorDelay = progressIndicatorDelay; if (this.progressIndicator == null) { throw new IllegalArgumentException("A progress indicator view must be provided in your custom progressView."); } return this; } /** * <p><b>Optional</b> By default Turbolinks will "advance" to the next page and scroll position * will not be restored. Optionally calling this method allows you to set the behavior on a * per-visitbasis. This will be reset to "false" after each visit.</p> * * @param restoreWithCachedSnapshot If true, will restore scroll position. If false, will not restore * scroll position. * @return The TurbolinksSession to continue the chained calls. */ public TurbolinksSession restoreWithCachedSnapshot(boolean restoreWithCachedSnapshot) { this.restoreWithCachedSnapshot = restoreWithCachedSnapshot; return this; } // --------------------------------------------------- // TurbolinksNative adapter methods // --------------------------------------------------- /** * <p><b>JavascriptInterface only</b> Called by Turbolinks when a new visit is initiated from a * webView link.</p> * * <p>Warning: This method is public so it can be used as a Javascript Interface. you should * never call this directly as it could lead to unintended behavior.</p> * * @param location URL to be visited. * @param action Whether to treat the request as an advance (navigating forward) or a replace (back). */ @SuppressWarnings("unused") @android.webkit.JavascriptInterface public void visitProposedToLocationWithAction(final String location, final String action) { TurbolinksLog.d("visitProposedToLocationWithAction called"); TurbolinksHelper.runOnMainThread(applicationContext, new Runnable() { @Override public void run() { turbolinksAdapter.visitProposedToLocationWithAction(location, action); } }); } /** * <p><b>JavascriptInterface only</b> Called by Turbolinks when a new visit has just started.</p> * * <p>Warning: This method is public so it can be used as a Javascript Interface. you should * never call this directly as it could lead to unintended behavior.</p> * * @param visitIdentifier A unique identifier for the visit. * @param visitHasCachedSnapshot Whether the visit has a cached snapshot available. */ @SuppressWarnings("unused") @android.webkit.JavascriptInterface public void visitStarted(String visitIdentifier, boolean visitHasCachedSnapshot) { TurbolinksLog.d("visitStarted called"); currentVisitIdentifier = visitIdentifier; runJavascript("webView.changeHistoryForVisitWithIdentifier", visitIdentifier); runJavascript("webView.issueRequestForVisitWithIdentifier", visitIdentifier); runJavascript("webView.loadCachedSnapshotForVisitWithIdentifier", visitIdentifier); } /** * <p><b>JavascriptInterface only</b> Called by Turbolinks when the HTTP request has been * completed.</p> * * <p>Warning: This method is public so it can be used as a Javascript Interface. you should * never call this directly as it could lead to unintended behavior.</p> * * @param visitIdentifier A unique identifier for the visit. */ @SuppressWarnings("unused") @android.webkit.JavascriptInterface public void visitRequestCompleted(String visitIdentifier) { TurbolinksLog.d("visitRequestCompleted called"); if (TextUtils.equals(visitIdentifier, currentVisitIdentifier)) { runJavascript("webView.loadResponseForVisitWithIdentifier", visitIdentifier); } } /** * <p><b>JavascriptInterface only</b> Called by Turbolinks when the HTTP request has failed.</p> * * <p>Warning: This method is public so it can be used as a Javascript Interface. you should * never call this directly as it could lead to unintended behavior.</p> * * @param visitIdentifier A unique identifier for the visit. * @param statusCode The HTTP status code that caused the failure. */ @SuppressWarnings("unused") @android.webkit.JavascriptInterface public void visitRequestFailedWithStatusCode(final String visitIdentifier, final int statusCode) { TurbolinksLog.d("visitRequestFailedWithStatusCode called"); if (TextUtils.equals(visitIdentifier, currentVisitIdentifier)) { TurbolinksHelper.runOnMainThread(applicationContext, new Runnable() { @Override public void run() { turbolinksAdapter.requestFailedWithStatusCode(statusCode); } }); } } /** * <p><b>JavascriptInterface only</b> Called by Turbolinks once the page has been fully rendered * in the webView.</p> * * <p>Warning: This method is public so it can be used as a Javascript Interface. you should * never call this directly as it could lead to unintended behavior.</p> * * @param visitIdentifier A unique identifier for the visit. */ @SuppressWarnings("unused") @android.webkit.JavascriptInterface public void visitRendered(String visitIdentifier) { TurbolinksLog.d("visitRendered called, hiding progress view for identifier: " + visitIdentifier); hideProgressView(visitIdentifier); } /** * <p><b>JavascriptInterface only</b> Called by Turbolinks when the visit is fully completed -- * request successful and page rendered.</p> * * <p>Warning: This method is public so it can be used as a Javascript Interface. you should * never call this directly as it could lead to unintended behavior.</p> * * @param visitIdentifier A unique identifier for the visit. * @param restorationIdentifier A unique identifier for restoring the page and scroll position * from cache. */ @SuppressWarnings("unused") @android.webkit.JavascriptInterface public void visitCompleted(String visitIdentifier, String restorationIdentifier) { TurbolinksLog.d("visitCompleted called"); addRestorationIdentifierToMap(restorationIdentifier); if (TextUtils.equals(visitIdentifier, currentVisitIdentifier)) { TurbolinksHelper.runOnMainThread(applicationContext, new Runnable() { @Override public void run() { turbolinksAdapter.visitCompleted(); swipeRefreshLayout.setRefreshing(false); } }); } } /** * <p><b>JavascriptInterface only</b> Called when Turbolinks detects that the page being visited * has been invalidated, typically by new resources in the the page HEAD.</p> * * <p>Warning: This method is public so it can be used as a Javascript Interface. you should * never call this directly as it could lead to unintended behavior.</p> */ @SuppressWarnings("unused") @android.webkit.JavascriptInterface public void pageInvalidated() { TurbolinksLog.d("pageInvalidated called"); resetToColdBoot(); TurbolinksHelper.runOnMainThread(applicationContext, new Runnable() { @Override public void run() { // route through normal chain so progress view is shown, regular logging, etc. turbolinksAdapter.pageInvalidated(); visit(location); } }); } // --------------------------------------------------- // TurbolinksNative helper methods // --------------------------------------------------- /** * <p><b>JavascriptInterface only</b> Hides the progress view when the page is fully rendered.</p> * * <p>Note: This method is public so it can be used as a Javascript Interface. For all practical * purposes, you should never call this directly.</p> * * @param visitIdentifier A unique identifier for the visit. */ @SuppressWarnings("unused") @android.webkit.JavascriptInterface public void hideProgressView(final String visitIdentifier) { TurbolinksHelper.runOnMainThread(applicationContext, new Runnable() { @Override public void run() { /** * pageInvalidated will cold boot, but another in-flight response from * visitResponseLoaded could attempt to hide the progress view. Checking * turbolinksIsReady ensures progress view isn't hidden too soon by the non cold boot. */ if (turbolinksIsReady && TextUtils.equals(visitIdentifier, currentVisitIdentifier)) { TurbolinksLog.d("Hiding progress view for visitIdentifier: " + visitIdentifier + ", currentVisitIdentifier: " + currentVisitIdentifier); turbolinksView.hideProgress(); progressView = null; } } }); } /** * <p><b>JavascriptInterface only</b> Sets internal flags that indicate whether Turbolinks in * the webView is ready for use.</p> * * <p>Note: This method is public so it can be used as a Javascript Interface. For all practical * purposes, you should never call this directly.</p> * * @param turbolinksIsReady The Javascript bridge checks the current page for Turbolinks, and * sends the results of that check here. */ @SuppressWarnings("unused") @android.webkit.JavascriptInterface public void setTurbolinksIsReady(boolean turbolinksIsReady) { this.turbolinksIsReady = turbolinksIsReady; if (turbolinksIsReady) { bridgeInjectionInProgress = false; TurbolinksHelper.runOnMainThread(applicationContext, new Runnable() { @Override public void run() { TurbolinksLog.d("TurbolinksSession is ready"); visitCurrentLocationWithTurbolinks(); } }); coldBootInProgress = false; } else { TurbolinksLog.d("TurbolinksSession is not ready. Resetting and throw error."); resetToColdBoot(); visitRequestFailedWithStatusCode(currentVisitIdentifier, 500); } } /** * <p><b>JavascriptInterface only</b> Handles the error condition when reaching a page without * Turbolinks.</p> * * <p>Note: This method is public so it can be used as a Javascript Interface. For all practical * purposes, you should never call this directly.</p> */ @SuppressWarnings("unused") @android.webkit.JavascriptInterface public void turbolinksDoesNotExist() { TurbolinksHelper.runOnMainThread(applicationContext, new Runnable() { @Override public void run() { TurbolinksLog.d("Error instantiating turbolinks_bridge.js - resetting to cold boot."); resetToColdBoot(); turbolinksView.hideProgress(); } }); } // ----------------------------------------------------------------------- // Public // ----------------------------------------------------------------------- /** * <p>Provides the ability to add an arbitrary number of custom Javascript Interfaces to the built-in * Turbolinks webView.</p> * * @param object The object with annotated JavascriptInterface methods * @param name The unique name for the interface (must not use the reserved name "TurbolinksNative") */ @SuppressLint("JavascriptInterface") public void addJavascriptInterface(Object object, String name) { if (TextUtils.equals(name, JAVASCRIPT_INTERFACE_NAME)) { throw new IllegalArgumentException(JAVASCRIPT_INTERFACE_NAME + " is a reserved Javascript Interface name."); } if (javascriptInterfaces.get(name) == null) { javascriptInterfaces.put(name, object); webView.addJavascriptInterface(object, name); TurbolinksLog.d("Adding JavascriptInterface: " + name + " for " + object.getClass().toString()); } } /** * <p>Returns the activity attached to the Turbolinks call.</p> * * @return The attached activity. */ public Activity getActivity() { return activity; } /** * <p>Returns the internal WebView used by Turbolinks.</p> * * @return The WebView used by Turbolinks. */ public WebView getWebView() { return webView; } /** * <p>Resets the TurbolinksSession to go through the full cold booting sequence (full page load) * on the next Turbolinks visit.</p> */ public void resetToColdBoot() { bridgeInjectionInProgress = false; turbolinksIsReady = false; coldBootInProgress = false; } /** * <p>Runs a Javascript function with any number of arbitrary params in the Turbolinks webView.</p> * * @param functionName The name of the function, without any parenthesis or params * @param params A comma delimited list of params. Params will be automatically JSONified. */ public void runJavascript(final String functionName, final Object... params) { TurbolinksHelper.runJavascript(applicationContext, webView, functionName, params); } /** * <p>Runs raw Javascript in webView. Simply wraps the loadUrl("javascript: methodName()") call.</p> * * @param rawJavascript The full Javascript string that will be executed by the WebView. */ public void runJavascriptRaw(String rawJavascript) { TurbolinksHelper.runJavascriptRaw(applicationContext, webView, rawJavascript); } /** * <p>Tells the logger whether to allow logging in debug mode.</p> * * @param enabled If true debug logging is enabled. */ public void setDebugLoggingEnabled(boolean enabled) { TurbolinksLog.setDebugLoggingEnabled(enabled); } /** * <p>Determines whether screenshots are displayed (instead of a progress view) when resuming * an activity. Default is true.</p> * * @param enabled If true automatic screenshotting is enabled. */ public void setScreenshotsEnabled(boolean enabled) { screenshotsEnabled = enabled; } /** * <p>Determines whether WebViews can be refreshed by pulling/swiping from the top * of the WebView. Default is true.</p> * * @param enabled If true pulling to refresh the WebView is enabled */ public void setPullToRefreshEnabled(boolean enabled) { pullToRefreshEnabled = enabled; } /** * <p>Provides the status of whether Turbolinks is initialized and ready for use.</p> * * @return True if Turbolinks has been fully loaded and detected on the page. */ public boolean turbolinksIsReady() { return turbolinksIsReady; } /** * <p>A convenience method to fire a Turbolinks visit manually.</p> * * @param location URL to visit. * @param action Whether to treat the request as an advance (navigating forward) or a replace (back). */ public void visitLocationWithAction(String location, String action) { runJavascript("webView.visitLocationWithActionAndRestorationIdentifier", TurbolinksHelper.encodeUrl(location), action, getRestorationIdentifierFromMap()); } // --------------------------------------------------- // Private // --------------------------------------------------- /** * <p>Adds the restoration (cached scroll position) identifier to the local Hashmap.</p> * * @param value Restoration ID provided by Turbolinks. */ private void addRestorationIdentifierToMap(String value) { if (activity != null) { restorationIdentifierMap.put(activity.toString(), value); } } /** * <p>Gets the restoration ID for the current activity.</p> * * @return Restoration ID for the current activity. */ private String getRestorationIdentifierFromMap() { return restorationIdentifierMap.get(activity.toString()); } /** * <p>Shows the progress view, either a custom one provided or the default.</p> * * <p>A default progress view is inflated if {@link #progressView} isn't called. * If already inflated, progress view is fully detached before being shown since it's reused.</p> */ private void initProgressView() { // No custom progress view provided, use default if (progressView == null) { progressView = LayoutInflater.from(activity).inflate(R.layout.turbolinks_progress, turbolinksView, false); TurbolinksLog.d("TurbolinksSession background: " + turbolinksView.getBackground()); progressView.setBackground(turbolinksView.getBackground()); progressIndicator = progressView.findViewById(R.id.turbolinks_default_progress_indicator); progressIndicatorDelay = PROGRESS_INDICATOR_DELAY; Drawable background = turbolinksView.getBackground() != null ? turbolinksView.getBackground() : new ColorDrawable(activity.getResources().getColor(android.R.color.white)); progressView.setBackground(background); } // A progress view can be reused, so ensure it's detached from its previous parent first if (progressView.getParent() != null) { ((ViewGroup) progressView.getParent()).removeView(progressView); } // Executed from here to account for progress indicator delay turbolinksView.showProgress(progressView, progressIndicator, progressIndicatorDelay); } /** * <p>Convenience method to simply revisit the current location in the TurbolinksSession. Useful * so that different visit logic can be wrappered around this call in {@link #visit} or * {@link #setTurbolinksIsReady(boolean)}</p> */ private void visitCurrentLocationWithTurbolinks() { TurbolinksLog.d("Visiting current stored location: " + location); String action = restoreWithCachedSnapshot ? ACTION_RESTORE : ACTION_ADVANCE; visitLocationWithAction(location, action); } /** * <p>Ensures all required chained calls/parameters ({@link #activity}, {@link #turbolinksView}, * and location}) are set before calling {@link #visit(String)}.</p> */ private void validateRequiredParams() { if (activity == null) { throw new IllegalArgumentException("TurbolinksSession.activity(activity) must be called with a non-null object."); } if (turbolinksAdapter == null) { throw new IllegalArgumentException("TurbolinksSession.adapter(turbolinksAdapter) must be called with a non-null object."); } if (turbolinksView == null) { throw new IllegalArgumentException("TurbolinksSession.view(turbolinksView) must be called with a non-null object."); } if (TextUtils.isEmpty(location)) { throw new IllegalArgumentException("TurbolinksSession.visit(location) location value must not be null."); } } // --------------------------------------------------- // Interfaces // --------------------------------------------------- /** * <p>Determines if the user can scroll up, or if the WebView is at the top</p> * * @return True if the WebView can be scrolled up. False if the WebView is at the top. */ @Override public boolean canChildScrollUp() { return this.webView.getScrollY() > 0; } }
Hide the progress view when an error occurs
turbolinks/src/main/java/com/basecamp/turbolinks/TurbolinksSession.java
Hide the progress view when an error occurs
<ide><path>urbolinks/src/main/java/com/basecamp/turbolinks/TurbolinksSession.java <ide> @android.webkit.JavascriptInterface <ide> public void visitRequestFailedWithStatusCode(final String visitIdentifier, final int statusCode) { <ide> TurbolinksLog.d("visitRequestFailedWithStatusCode called"); <add> hideProgressView(visitIdentifier); <ide> <ide> if (TextUtils.equals(visitIdentifier, currentVisitIdentifier)) { <ide> TurbolinksHelper.runOnMainThread(applicationContext, new Runnable() {
Java
apache-2.0
874eeb88d9dc5e8fbcd681672fb90a4cd7597fec
0
ollie314/kafka,Chasego/kafka,gf53520/kafka,gf53520/kafka,Chasego/kafka,MyPureCloud/kafka,Chasego/kafka,sslavic/kafka,ollie314/kafka,MyPureCloud/kafka,mihbor/kafka,Ishiihara/kafka,KevinLiLu/kafka,richhaase/kafka,gf53520/kafka,mihbor/kafka,lindong28/kafka,KevinLiLu/kafka,guozhangwang/kafka,Ishiihara/kafka,guozhangwang/kafka,richhaase/kafka,apache/kafka,noslowerdna/kafka,noslowerdna/kafka,Chasego/kafka,KevinLiLu/kafka,sslavic/kafka,guozhangwang/kafka,Ishiihara/kafka,richhaase/kafka,ollie314/kafka,lindong28/kafka,Esquive/kafka,apache/kafka,MyPureCloud/kafka,Ishiihara/kafka,apache/kafka,lindong28/kafka,mihbor/kafka,noslowerdna/kafka,sebadiaz/kafka,sebadiaz/kafka,KevinLiLu/kafka,sebadiaz/kafka,MyPureCloud/kafka,sebadiaz/kafka,Esquive/kafka,TiVo/kafka,Esquive/kafka,TiVo/kafka,TiVo/kafka,sslavic/kafka,noslowerdna/kafka,mihbor/kafka,apache/kafka,sslavic/kafka,richhaase/kafka,TiVo/kafka,ollie314/kafka,gf53520/kafka,lindong28/kafka,Esquive/kafka,guozhangwang/kafka
/* * 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.kafka.streams.state.internals; import org.apache.kafka.common.serialization.Serde; import org.apache.kafka.common.utils.Bytes; import org.apache.kafka.streams.KeyValue; import org.apache.kafka.streams.kstream.internals.CacheFlushListener; import org.apache.kafka.streams.processor.ProcessorContext; import org.apache.kafka.streams.processor.StateStore; import org.apache.kafka.streams.processor.internals.InternalProcessorContext; import org.apache.kafka.streams.processor.internals.ProcessorStateManager; import org.apache.kafka.streams.processor.internals.RecordContext; import org.apache.kafka.streams.state.KeyValueIterator; import org.apache.kafka.streams.state.KeyValueStore; import org.apache.kafka.streams.state.StateSerdes; import java.util.List; import java.util.Objects; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; class CachingKeyValueStore<K, V> extends WrappedStateStore.AbstractStateStore implements KeyValueStore<Bytes, byte[]>, CachedStateStore<K, V> { private final KeyValueStore<Bytes, byte[]> underlying; private final Serde<K> keySerde; private final Serde<V> valueSerde; private CacheFlushListener<K, V> flushListener; private boolean sendOldValues; private String cacheName; private ThreadCache cache; private InternalProcessorContext context; private StateSerdes<K, V> serdes; private Thread streamThread; private ReadWriteLock lock = new ReentrantReadWriteLock(); CachingKeyValueStore(final KeyValueStore<Bytes, byte[]> underlying, final Serde<K> keySerde, final Serde<V> valueSerde) { super(underlying); this.underlying = underlying; this.keySerde = keySerde; this.valueSerde = valueSerde; } @Override public void init(final ProcessorContext context, final StateStore root) { underlying.init(context, root); initInternal(context); // save the stream thread as we only ever want to trigger a flush // when the stream thread is the current thread. streamThread = Thread.currentThread(); } @SuppressWarnings("unchecked") private void initInternal(final ProcessorContext context) { this.context = (InternalProcessorContext) context; this.serdes = new StateSerdes<>(ProcessorStateManager.storeChangelogTopic(context.applicationId(), underlying.name()), keySerde == null ? (Serde<K>) context.keySerde() : keySerde, valueSerde == null ? (Serde<V>) context.valueSerde() : valueSerde); this.cache = this.context.getCache(); this.cacheName = ThreadCache.nameSpaceFromTaskIdAndStore(context.taskId().toString(), underlying.name()); cache.addDirtyEntryFlushListener(cacheName, new ThreadCache.DirtyEntryFlushListener() { @Override public void apply(final List<ThreadCache.DirtyEntry> entries) { for (ThreadCache.DirtyEntry entry : entries) { putAndMaybeForward(entry, (InternalProcessorContext) context); } } }); } private void putAndMaybeForward(final ThreadCache.DirtyEntry entry, final InternalProcessorContext context) { final RecordContext current = context.recordContext(); try { context.setRecordContext(entry.recordContext()); if (flushListener != null) { final V oldValue = sendOldValues ? serdes.valueFrom(underlying.get(entry.key())) : null; flushListener.apply(serdes.keyFrom(entry.key().get()), serdes.valueFrom(entry.newValue()), oldValue); } underlying.put(entry.key(), entry.newValue()); } finally { context.setRecordContext(current); } } public void setFlushListener(final CacheFlushListener<K, V> flushListener, final boolean sendOldValues) { this.flushListener = flushListener; this.sendOldValues = sendOldValues; } @Override public void flush() { lock.writeLock().lock(); try { cache.flush(cacheName); underlying.flush(); } finally { lock.writeLock().unlock(); } } @Override public void close() { flush(); underlying.close(); cache.close(cacheName); } @Override public boolean persistent() { return underlying.persistent(); } @Override public boolean isOpen() { return underlying.isOpen(); } @Override public byte[] get(final Bytes key) { validateStoreOpen(); Lock theLock; if (Thread.currentThread().equals(streamThread)) { theLock = lock.writeLock(); } else { theLock = lock.readLock(); } theLock.lock(); try { Objects.requireNonNull(key); return getInternal(key); } finally { theLock.unlock(); } } private byte[] getInternal(final Bytes key) { final LRUCacheEntry entry = cache.get(cacheName, key); if (entry == null) { final byte[] rawValue = underlying.get(key); if (rawValue == null) { return null; } // only update the cache if this call is on the streamThread // as we don't want other threads to trigger an eviction/flush if (Thread.currentThread().equals(streamThread)) { cache.put(cacheName, key, new LRUCacheEntry(rawValue)); } return rawValue; } if (entry.value == null) { return null; } return entry.value; } @Override public KeyValueIterator<Bytes, byte[]> range(final Bytes from, final Bytes to) { validateStoreOpen(); final KeyValueIterator<Bytes, byte[]> storeIterator = underlying.range(from, to); final ThreadCache.MemoryLRUCacheBytesIterator cacheIterator = cache.range(cacheName, from, to); return new MergedSortedCacheKeyValueBytesStoreIterator(cacheIterator, storeIterator); } @Override public KeyValueIterator<Bytes, byte[]> all() { validateStoreOpen(); final KeyValueIterator<Bytes, byte[]> storeIterator = new DelegatingPeekingKeyValueIterator<>(this.name(), underlying.all()); final ThreadCache.MemoryLRUCacheBytesIterator cacheIterator = cache.all(cacheName); return new MergedSortedCacheKeyValueBytesStoreIterator(cacheIterator, storeIterator); } @Override public long approximateNumEntries() { validateStoreOpen(); lock.readLock().lock(); try { return underlying.approximateNumEntries(); } finally { lock.readLock().unlock(); } } @Override public void put(final Bytes key, final byte[] value) { Objects.requireNonNull(key, "key cannot be null"); validateStoreOpen(); lock.writeLock().lock(); try { putInternal(key, value); } finally { lock.writeLock().unlock(); } } private void putInternal(final Bytes rawKey, final byte[] value) { Objects.requireNonNull(rawKey, "key cannot be null"); cache.put(cacheName, rawKey, new LRUCacheEntry(value, true, context.offset(), context.timestamp(), context.partition(), context.topic())); } @Override public byte[] putIfAbsent(final Bytes key, final byte[] value) { Objects.requireNonNull(key, "key cannot be null"); validateStoreOpen(); lock.writeLock().lock(); try { final byte[] v = getInternal(key); if (v == null) { putInternal(key, value); } return v; } finally { lock.writeLock().unlock(); } } @Override public void putAll(final List<KeyValue<Bytes, byte[]>> entries) { lock.writeLock().lock(); try { for (KeyValue<Bytes, byte[]> entry : entries) { put(entry.key, entry.value); } } finally { lock.writeLock().unlock(); } } @Override public byte[] delete(final Bytes key) { validateStoreOpen(); lock.writeLock().lock(); try { Objects.requireNonNull(key); final byte[] v = getInternal(key); cache.delete(cacheName, key); underlying.delete(key); return v; } finally { lock.writeLock().unlock(); } } KeyValueStore<Bytes, byte[]> underlying() { return underlying; } @Override public StateStore inner() { if (underlying instanceof WrappedStateStore) { return ((WrappedStateStore) underlying).inner(); } return underlying; } }
streams/src/main/java/org/apache/kafka/streams/state/internals/CachingKeyValueStore.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.kafka.streams.state.internals; import org.apache.kafka.common.serialization.Serde; import org.apache.kafka.common.utils.Bytes; import org.apache.kafka.streams.KeyValue; import org.apache.kafka.streams.kstream.internals.CacheFlushListener; import org.apache.kafka.streams.processor.ProcessorContext; import org.apache.kafka.streams.processor.StateStore; import org.apache.kafka.streams.processor.internals.InternalProcessorContext; import org.apache.kafka.streams.processor.internals.ProcessorStateManager; import org.apache.kafka.streams.processor.internals.RecordContext; import org.apache.kafka.streams.state.KeyValueIterator; import org.apache.kafka.streams.state.KeyValueStore; import org.apache.kafka.streams.state.StateSerdes; import java.util.List; import java.util.Objects; class CachingKeyValueStore<K, V> extends WrappedStateStore.AbstractStateStore implements KeyValueStore<Bytes, byte[]>, CachedStateStore<K, V> { private final KeyValueStore<Bytes, byte[]> underlying; private final Serde<K> keySerde; private final Serde<V> valueSerde; private CacheFlushListener<K, V> flushListener; private boolean sendOldValues; private String cacheName; private ThreadCache cache; private InternalProcessorContext context; private StateSerdes<K, V> serdes; private Thread streamThread; CachingKeyValueStore(final KeyValueStore<Bytes, byte[]> underlying, final Serde<K> keySerde, final Serde<V> valueSerde) { super(underlying); this.underlying = underlying; this.keySerde = keySerde; this.valueSerde = valueSerde; } @Override public void init(final ProcessorContext context, final StateStore root) { underlying.init(context, root); initInternal(context); // save the stream thread as we only ever want to trigger a flush // when the stream thread is the current thread. streamThread = Thread.currentThread(); } @SuppressWarnings("unchecked") private void initInternal(final ProcessorContext context) { this.context = (InternalProcessorContext) context; this.serdes = new StateSerdes<>(ProcessorStateManager.storeChangelogTopic(context.applicationId(), underlying.name()), keySerde == null ? (Serde<K>) context.keySerde() : keySerde, valueSerde == null ? (Serde<V>) context.valueSerde() : valueSerde); this.cache = this.context.getCache(); this.cacheName = ThreadCache.nameSpaceFromTaskIdAndStore(context.taskId().toString(), underlying.name()); cache.addDirtyEntryFlushListener(cacheName, new ThreadCache.DirtyEntryFlushListener() { @Override public void apply(final List<ThreadCache.DirtyEntry> entries) { for (ThreadCache.DirtyEntry entry : entries) { putAndMaybeForward(entry, (InternalProcessorContext) context); } } }); } private void putAndMaybeForward(final ThreadCache.DirtyEntry entry, final InternalProcessorContext context) { final RecordContext current = context.recordContext(); try { context.setRecordContext(entry.recordContext()); if (flushListener != null) { final V oldValue = sendOldValues ? serdes.valueFrom(underlying.get(entry.key())) : null; flushListener.apply(serdes.keyFrom(entry.key().get()), serdes.valueFrom(entry.newValue()), oldValue); } underlying.put(entry.key(), entry.newValue()); } finally { context.setRecordContext(current); } } public void setFlushListener(final CacheFlushListener<K, V> flushListener, final boolean sendOldValues) { this.flushListener = flushListener; this.sendOldValues = sendOldValues; } @Override public synchronized void flush() { cache.flush(cacheName); underlying.flush(); } @Override public void close() { flush(); underlying.close(); cache.close(cacheName); } @Override public boolean persistent() { return underlying.persistent(); } @Override public boolean isOpen() { return underlying.isOpen(); } @Override public synchronized byte[] get(final Bytes key) { validateStoreOpen(); Objects.requireNonNull(key); return getInternal(key); } private byte[] getInternal(final Bytes key) { final LRUCacheEntry entry = cache.get(cacheName, key); if (entry == null) { final byte[] rawValue = underlying.get(key); if (rawValue == null) { return null; } // only update the cache if this call is on the streamThread // as we don't want other threads to trigger an eviction/flush if (Thread.currentThread().equals(streamThread)) { cache.put(cacheName, key, new LRUCacheEntry(rawValue)); } return rawValue; } if (entry.value == null) { return null; } return entry.value; } @Override public KeyValueIterator<Bytes, byte[]> range(final Bytes from, final Bytes to) { validateStoreOpen(); final KeyValueIterator<Bytes, byte[]> storeIterator = underlying.range(from, to); final ThreadCache.MemoryLRUCacheBytesIterator cacheIterator = cache.range(cacheName, from, to); return new MergedSortedCacheKeyValueBytesStoreIterator(cacheIterator, storeIterator); } @Override public KeyValueIterator<Bytes, byte[]> all() { validateStoreOpen(); final KeyValueIterator<Bytes, byte[]> storeIterator = new DelegatingPeekingKeyValueIterator<>(this.name(), underlying.all()); final ThreadCache.MemoryLRUCacheBytesIterator cacheIterator = cache.all(cacheName); return new MergedSortedCacheKeyValueBytesStoreIterator(cacheIterator, storeIterator); } @Override public synchronized long approximateNumEntries() { validateStoreOpen(); return underlying.approximateNumEntries(); } @Override public synchronized void put(final Bytes key, final byte[] value) { Objects.requireNonNull(key, "key cannot be null"); validateStoreOpen(); putInternal(key, value); } private synchronized void putInternal(final Bytes rawKey, final byte[] value) { Objects.requireNonNull(rawKey, "key cannot be null"); cache.put(cacheName, rawKey, new LRUCacheEntry(value, true, context.offset(), context.timestamp(), context.partition(), context.topic())); } @Override public synchronized byte[] putIfAbsent(final Bytes key, final byte[] value) { Objects.requireNonNull(key, "key cannot be null"); validateStoreOpen(); final byte[] v = getInternal(key); if (v == null) { putInternal(key, value); } return v; } @Override public synchronized void putAll(final List<KeyValue<Bytes, byte[]>> entries) { for (KeyValue<Bytes, byte[]> entry : entries) { put(entry.key, entry.value); } } @Override public synchronized byte[] delete(final Bytes key) { validateStoreOpen(); Objects.requireNonNull(key); final byte[] v = getInternal(key); cache.delete(cacheName, key); underlying.delete(key); return v; } KeyValueStore<Bytes, byte[]> underlying() { return underlying; } @Override public StateStore inner() { if (underlying instanceof WrappedStateStore) { return ((WrappedStateStore) underlying).inner(); } return underlying; } }
KAFKA-6412 Improve synchronization in CachingKeyValueStore methods Currently CachingKeyValueStore methods are synchronized at method level. It seems we can use read lock for getter and write lock for put / delete methods. For getInternal(), if the underlying thread is streamThread, the getInternal() may trigger eviction. This can be handled by obtaining write lock at the beginning of the method for streamThread. The jmh patch is attached to JIRA: https://issues.apache.org/jira/secure/attachment/12905140/6412-jmh.v1.txt Author: tedyu <[email protected]> Reviewers: Damian Guy <[email protected]>, Bill Bejeck <[email protected]> Closes #4372 from tedyu/6412
streams/src/main/java/org/apache/kafka/streams/state/internals/CachingKeyValueStore.java
KAFKA-6412 Improve synchronization in CachingKeyValueStore methods
<ide><path>treams/src/main/java/org/apache/kafka/streams/state/internals/CachingKeyValueStore.java <ide> <ide> import java.util.List; <ide> import java.util.Objects; <add>import java.util.concurrent.locks.Lock; <add>import java.util.concurrent.locks.ReadWriteLock; <add>import java.util.concurrent.locks.ReentrantReadWriteLock; <ide> <ide> class CachingKeyValueStore<K, V> extends WrappedStateStore.AbstractStateStore implements KeyValueStore<Bytes, byte[]>, CachedStateStore<K, V> { <ide> <ide> private InternalProcessorContext context; <ide> private StateSerdes<K, V> serdes; <ide> private Thread streamThread; <add> private ReadWriteLock lock = new ReentrantReadWriteLock(); <ide> <ide> CachingKeyValueStore(final KeyValueStore<Bytes, byte[]> underlying, <ide> final Serde<K> keySerde, <ide> } <ide> <ide> @Override <del> public synchronized void flush() { <del> cache.flush(cacheName); <del> underlying.flush(); <add> public void flush() { <add> lock.writeLock().lock(); <add> try { <add> cache.flush(cacheName); <add> underlying.flush(); <add> } finally { <add> lock.writeLock().unlock(); <add> } <ide> } <ide> <ide> @Override <ide> } <ide> <ide> @Override <del> public synchronized byte[] get(final Bytes key) { <del> validateStoreOpen(); <del> Objects.requireNonNull(key); <del> return getInternal(key); <add> public byte[] get(final Bytes key) { <add> validateStoreOpen(); <add> Lock theLock; <add> if (Thread.currentThread().equals(streamThread)) { <add> theLock = lock.writeLock(); <add> } else { <add> theLock = lock.readLock(); <add> } <add> theLock.lock(); <add> try { <add> Objects.requireNonNull(key); <add> return getInternal(key); <add> } finally { <add> theLock.unlock(); <add> } <ide> } <ide> <ide> private byte[] getInternal(final Bytes key) { <ide> } <ide> <ide> @Override <del> public synchronized long approximateNumEntries() { <del> validateStoreOpen(); <del> return underlying.approximateNumEntries(); <del> } <del> <del> @Override <del> public synchronized void put(final Bytes key, final byte[] value) { <add> public long approximateNumEntries() { <add> validateStoreOpen(); <add> lock.readLock().lock(); <add> try { <add> return underlying.approximateNumEntries(); <add> } finally { <add> lock.readLock().unlock(); <add> } <add> } <add> <add> @Override <add> public void put(final Bytes key, final byte[] value) { <ide> Objects.requireNonNull(key, "key cannot be null"); <ide> validateStoreOpen(); <del> putInternal(key, value); <del> } <del> <del> private synchronized void putInternal(final Bytes rawKey, final byte[] value) { <add> lock.writeLock().lock(); <add> try { <add> putInternal(key, value); <add> } finally { <add> lock.writeLock().unlock(); <add> } <add> } <add> <add> private void putInternal(final Bytes rawKey, final byte[] value) { <ide> Objects.requireNonNull(rawKey, "key cannot be null"); <ide> cache.put(cacheName, rawKey, new LRUCacheEntry(value, true, context.offset(), <del> context.timestamp(), context.partition(), context.topic())); <del> } <del> <del> @Override <del> public synchronized byte[] putIfAbsent(final Bytes key, final byte[] value) { <add> context.timestamp(), context.partition(), context.topic())); <add> } <add> <add> @Override <add> public byte[] putIfAbsent(final Bytes key, final byte[] value) { <ide> Objects.requireNonNull(key, "key cannot be null"); <ide> validateStoreOpen(); <del> final byte[] v = getInternal(key); <del> if (v == null) { <del> putInternal(key, value); <del> } <del> return v; <del> } <del> <del> @Override <del> public synchronized void putAll(final List<KeyValue<Bytes, byte[]>> entries) { <del> for (KeyValue<Bytes, byte[]> entry : entries) { <del> put(entry.key, entry.value); <del> } <del> } <del> <del> @Override <del> public synchronized byte[] delete(final Bytes key) { <del> validateStoreOpen(); <del> Objects.requireNonNull(key); <del> final byte[] v = getInternal(key); <del> cache.delete(cacheName, key); <del> underlying.delete(key); <del> return v; <add> lock.writeLock().lock(); <add> try { <add> final byte[] v = getInternal(key); <add> if (v == null) { <add> putInternal(key, value); <add> } <add> return v; <add> } finally { <add> lock.writeLock().unlock(); <add> } <add> } <add> <add> @Override <add> public void putAll(final List<KeyValue<Bytes, byte[]>> entries) { <add> lock.writeLock().lock(); <add> try { <add> for (KeyValue<Bytes, byte[]> entry : entries) { <add> put(entry.key, entry.value); <add> } <add> } finally { <add> lock.writeLock().unlock(); <add> } <add> } <add> <add> @Override <add> public byte[] delete(final Bytes key) { <add> validateStoreOpen(); <add> lock.writeLock().lock(); <add> try { <add> Objects.requireNonNull(key); <add> final byte[] v = getInternal(key); <add> cache.delete(cacheName, key); <add> underlying.delete(key); <add> return v; <add> } finally { <add> lock.writeLock().unlock(); <add> } <ide> } <ide> <ide> KeyValueStore<Bytes, byte[]> underlying() {
JavaScript
mit
765d7d08ef82efc451eed9cc21690c2b53c6ccb7
0
weaintplastic/react-sketchapp
import processColor from './processColor'; import type { Color } from './processColor'; export const colors = { Haus: '#F3F4F4', Night: '#333', Sur: '#96DBE4', 'Sur a11y': '#24828F', Peach: '#EFADA0', 'Peach a11y': '#E37059', Pear: '#93DAAB', 'Pear a11y': '#2E854B', }; const typeSizes = [ 80, 48, 36, 24, 20, 16, ]; export const spacing = 16; const fontFamilies = { bold: 'SFUIDisplay-Bold', regular: 'SFUIDisplay-Regular', }; export const fonts = { Headline: { fontSize: typeSizes[0], fontFamily: fontFamilies.bold, lineHeight: 60, }, 'Title 1': { fontSize: typeSizes[2], fontFamily: fontFamilies.bold, lineHeight: 48, }, 'Title 2': { fontSize: typeSizes[3], fontFamily: fontFamilies.bold, lineHeight: 36, }, 'Title 3': { fontSize: typeSizes[4], fontFamily: fontFamilies.regular, lineHeight: 24, }, Body: { fontSize: typeSizes[5], fontFamily: fontFamilies.regular, lineHeight: 24, }, }; export default { colors: Object.keys(colors).reduce((acc, name) => ({ ...acc, [name]: processColor(colors[name]), }), {}), fonts, spacing, }; export type DesignSystem = { fonts: any, colors: {[key: string]: Color}, }
example-plugin/designSystem.js
import processColor from './processColor'; import type { Color } from './processColor'; export const colors = { Haus: '#F3F4F4', Night: '#333', Sur: '#96DBE4', 'Sur a11y': '#24828F', Peach: '#EFADA0', 'Peach a11y': '#E37059', Pear: '#93DAAB', 'Pear a11y': '#2E854B', }; const typeSizes = [ 80, 48, 36, 24, 20, 16, ]; export const spacing = 16; const fontFamilies = { bold: 'SFUIDisplay-Bold', regular: 'SFUIDisplay-Regular', }; export const fonts = { Headline: { fontSize: typeSizes[0], fontFamily: fontFamilies.bold, lineHeight: 60, }, 'Title 1': { fontSize: typeSizes[2], fontFamily: fontFamilies.bold, lineHeight: 48, }, 'Title 2': { fontSize: typeSizes[3], fontFamily: fontFamilies.bold, lineHeight: 36, }, 'Title 3': { fontSize: typeSizes[4], fontFamily: fontFamilies.regular, lineHeight: 24, }, Body: { fontSize: typeSizes[5], fontFamily: fontFamilies.regular, lineHeight: 24, }, }; export default { colors: colors.map(processColor), fonts, spacing, }; export type DesignSystem = { fonts: any, colors: {[key: string]: Color}, }
fix bug in example design system
example-plugin/designSystem.js
fix bug in example design system
<ide><path>xample-plugin/designSystem.js <ide> }; <ide> <ide> export default { <del> colors: colors.map(processColor), <add> colors: Object.keys(colors).reduce((acc, name) => ({ <add> ...acc, <add> [name]: processColor(colors[name]), <add> }), {}), <ide> fonts, <ide> spacing, <ide> };
Java
agpl-3.0
ba305852996c035831f46a6b3ec2d9056f30560f
0
rdkgit/opennms,tdefilip/opennms,roskens/opennms-pre-github,rdkgit/opennms,tdefilip/opennms,aihua/opennms,rdkgit/opennms,tdefilip/opennms,rdkgit/opennms,roskens/opennms-pre-github,aihua/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,rdkgit/opennms,rdkgit/opennms,tdefilip/opennms,aihua/opennms,aihua/opennms,aihua/opennms,aihua/opennms,aihua/opennms,roskens/opennms-pre-github,rdkgit/opennms,tdefilip/opennms,rdkgit/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,aihua/opennms,tdefilip/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,aihua/opennms,roskens/opennms-pre-github,tdefilip/opennms,rdkgit/opennms,tdefilip/opennms,tdefilip/opennms,rdkgit/opennms,roskens/opennms-pre-github
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) 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. * * OpenNMS(R) 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 OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <[email protected]> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.config; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.net.InetAddress; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.opennms.core.utils.ByteArrayComparator; import org.opennms.core.utils.ConfigFileConstants; import org.opennms.core.utils.IPLike; import org.opennms.core.utils.InetAddressUtils; import org.opennms.core.utils.LogUtils; import org.opennms.core.xml.JaxbUtils; import org.opennms.netmgt.config.snmp.Definition; import org.opennms.netmgt.config.snmp.Range; import org.opennms.netmgt.config.snmp.SnmpConfig; import org.opennms.netmgt.snmp.SnmpAgentConfig; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.xml.sax.InputSource; /** * This class is the main repository for SNMP configuration information used by * the capabilities daemon. When this class is loaded it reads the snmp * configuration into memory, and uses the configuration to find the * {@link org.opennms.netmgt.snmp.SnmpAgentConfig SnmpAgentConfig} objects for specific * addresses. If an address cannot be located in the configuration then a * default peer instance is returned to the caller. * * <strong>Note: </strong>Users of this class should make sure the * <em>init()</em> is called before calling any other method to ensure the * config is loaded before accessing other convenience methods. * * @author <a href="mailto:[email protected]">David Hustace</a> * @author <a href="mailto:[email protected]">Weave</a> * @author <a href="mailto:[email protected]">Gerald Turner</a> */ public class SnmpPeerFactory implements SnmpAgentConfigFactory { private static final int DEFAULT_SNMP_PORT = 161; private static final ReadWriteLock m_globalLock = new ReentrantReadWriteLock(); private static final Lock m_readLock = m_globalLock.readLock(); private static final Lock m_writeLock = m_globalLock.writeLock(); /** * The singleton instance of this factory */ private static SnmpPeerFactory m_singleton = null; /** * The config class loaded from the config file */ private static SnmpConfig m_config; private static File m_configFile; /** * This member is set to true if the configuration file has been loaded. */ private static boolean m_loaded = false; private static final int VERSION_UNSPECIFIED = -1; /** * Private constructor * * @exception java.io.IOException * Thrown if the specified config file cannot be read * @exception org.exolab.castor.xml.MarshalException * Thrown if the file does not conform to the schema. * @exception org.exolab.castor.xml.ValidationException * Thrown if the contents do not match the required schema. */ private SnmpPeerFactory(final File configFile) throws IOException { this(new FileSystemResource(configFile)); } /** * <p>Constructor for SnmpPeerFactory.</p> * * @param resource a {@link org.springframework.core.io.Resource} object. */ public SnmpPeerFactory(final Resource resource) { SnmpPeerFactory.getWriteLock().lock(); try { m_config = JaxbUtils.unmarshal(SnmpConfig.class, resource); } finally { SnmpPeerFactory.getWriteLock().unlock(); } } /** * <p>Constructor for SnmpPeerFactory.</p> * * @param rdr a {@link java.io.Reader} object. * @throws java.io.IOException if any. * @throws org.exolab.castor.xml.MarshalException if any. * @throws org.exolab.castor.xml.ValidationException if any. * @deprecated Use code for InputStream instead to avoid character set issues */ public SnmpPeerFactory(final Reader rdr) throws IOException { SnmpPeerFactory.getWriteLock().lock(); try { m_config = JaxbUtils.unmarshal(SnmpConfig.class, rdr); } finally { SnmpPeerFactory.getWriteLock().unlock(); } } /** * A constructor that takes a config string for use mostly in tests */ public SnmpPeerFactory(final String configString) throws IOException { SnmpPeerFactory.getWriteLock().lock(); try { m_config = JaxbUtils.unmarshal(SnmpConfig.class, configString); } finally { SnmpPeerFactory.getWriteLock().unlock(); } } /** * <p>Constructor for SnmpPeerFactory.</p> * * @param stream a {@link java.io.InputStream} object. */ public SnmpPeerFactory(final InputStream stream) { SnmpPeerFactory.getWriteLock().lock(); try { m_config = JaxbUtils.unmarshal(SnmpConfig.class, new InputSource(stream), null); } finally { SnmpPeerFactory.getWriteLock().unlock(); } } public static Lock getReadLock() { return m_readLock; } public static Lock getWriteLock() { return m_writeLock; } /** * Load the config from the default config file and create the singleton * instance of this factory. * * @exception java.io.IOException * Thrown if the specified config file cannot be read * @exception org.exolab.castor.xml.MarshalException * Thrown if the file does not conform to the schema. * @exception org.exolab.castor.xml.ValidationException * Thrown if the contents do not match the required schema. * @throws java.io.IOException if any. * @throws org.exolab.castor.xml.MarshalException if any. * @throws org.exolab.castor.xml.ValidationException if any. */ public static void init() throws IOException { SnmpPeerFactory.getWriteLock().lock(); try { if (m_loaded) { // init already called - return // to reload, reload() will need to be called return; } final File cfgFile = getFile(); LogUtils.debugf(SnmpPeerFactory.class, "init: config file path: %s", cfgFile.getPath()); m_singleton = new SnmpPeerFactory(cfgFile); m_loaded = true; } finally { SnmpPeerFactory.getWriteLock().unlock(); } } /** * Saves the current settings to disk * * @throws java.io.IOException if any. * @throws org.exolab.castor.xml.MarshalException if any. * @throws org.exolab.castor.xml.ValidationException if any. */ public static void saveCurrent() throws IOException { saveToFile(getFile()); } public static void saveToFile(final File file) throws UnsupportedEncodingException, FileNotFoundException, IOException { // Marshal to a string first, then write the string to the file. This // way the original config // isn't lost if the XML from the marshal is hosed. final String marshalledConfig = marshallConfig(); SnmpPeerFactory.getWriteLock().lock(); FileOutputStream out = null; Writer fileWriter = null; try { if (marshalledConfig != null) { out = new FileOutputStream(file); fileWriter = new OutputStreamWriter(out, "UTF-8"); fileWriter.write(marshalledConfig); fileWriter.flush(); fileWriter.close(); } } finally { IOUtils.closeQuietly(fileWriter); IOUtils.closeQuietly(out); SnmpPeerFactory.getWriteLock().unlock(); } } /** * Return the singleton instance of this factory. * * @return The current factory instance. * @throws java.lang.IllegalStateException * Thrown if the factory has not yet been initialized. */ public static SnmpPeerFactory getInstance() { SnmpPeerFactory.getReadLock().lock(); try { if (!m_loaded) { throw new IllegalStateException("The factory has not been initialized"); } return m_singleton; } finally { SnmpPeerFactory.getReadLock().unlock(); } } /** * <p>setFile</p> * * @param configFile a {@link java.io.File} object. */ public static void setFile(final File configFile) { SnmpPeerFactory.getWriteLock().lock(); try { final File oldFile = m_configFile; m_configFile = configFile; // if the file changed then we need to reload the config if (oldFile == null || m_configFile == null || !oldFile.equals(m_configFile)) { m_singleton = null; m_loaded = false; } } finally { SnmpPeerFactory.getWriteLock().unlock(); } } /** * <p>getFile</p> * * @return a {@link java.io.File} object. * @throws java.io.IOException if any. */ public static File getFile() throws IOException { SnmpPeerFactory.getReadLock().lock(); try { if (m_configFile == null) { setFile(ConfigFileConstants.getFile(ConfigFileConstants.SNMP_CONF_FILE_NAME)); } return m_configFile; } finally { SnmpPeerFactory.getReadLock().unlock(); } } /** * <p>setInstance</p> * * @param singleton a {@link org.opennms.netmgt.config.SnmpPeerFactory} object. */ public static void setInstance(final SnmpPeerFactory singleton) { SnmpPeerFactory.getWriteLock().lock(); try { m_singleton = singleton; m_loaded = true; } finally { SnmpPeerFactory.getWriteLock().unlock(); } } /** {@inheritDoc} */ public SnmpAgentConfig getAgentConfig(final InetAddress agentAddress) { return getAgentConfig(agentAddress, VERSION_UNSPECIFIED); } private SnmpAgentConfig getAgentConfig(final InetAddress agentInetAddress, final int requestedSnmpVersion) { SnmpPeerFactory.getReadLock().lock(); try { if (m_config == null) { final SnmpAgentConfig agentConfig = new SnmpAgentConfig(agentInetAddress); if (requestedSnmpVersion == VERSION_UNSPECIFIED) { agentConfig.setVersion(SnmpAgentConfig.DEFAULT_VERSION); } else { agentConfig.setVersion(requestedSnmpVersion); } return agentConfig; } final SnmpAgentConfig agentConfig = new SnmpAgentConfig(agentInetAddress); // Now set the defaults from the m_config setSnmpAgentConfig(agentConfig, new Definition(), requestedSnmpVersion); // Attempt to locate the node DEFLOOP: for (final Definition def : m_config.getDefinitionCollection()) { // check the specifics first for (final String saddr : def.getSpecificCollection()) { try { final InetAddress addr = InetAddressUtils.addr(saddr); if (addr != null && addr.equals(agentConfig.getAddress())) { setSnmpAgentConfig(agentConfig, def, requestedSnmpVersion); break DEFLOOP; } } catch (final IllegalArgumentException e) { LogUtils.debugf(this, e, "Error while reading SNMP config <specific> tag: %s", saddr); } } // check the ranges // final ByteArrayComparator comparator = new ByteArrayComparator(); for (final Range rng : def.getRangeCollection()) { final byte[] addr = agentConfig.getAddress().getAddress(); final byte[] begin = InetAddressUtils.toIpAddrBytes(rng.getBegin()); final byte[] end = InetAddressUtils.toIpAddrBytes(rng.getEnd()); boolean inRange = InetAddressUtils.isInetAddressInRange(addr, begin, end); if (comparator.compare(begin, end) <= 0) { inRange = InetAddressUtils.isInetAddressInRange(addr, begin, end); } else { LogUtils.warnf(this, "%s has an 'end' that is earlier than its 'beginning'!", rng); inRange = InetAddressUtils.isInetAddressInRange(addr, end, begin); } if (inRange) { setSnmpAgentConfig(agentConfig, def, requestedSnmpVersion); break DEFLOOP; } } // check the matching ip expressions for (final String ipMatch : def.getIpMatchCollection()) { if (IPLike.matches(agentInetAddress, ipMatch)) { setSnmpAgentConfig(agentConfig, def, requestedSnmpVersion); break DEFLOOP; } } } // end DEFLOOP if (agentConfig == null) { final Definition def = new Definition(); setSnmpAgentConfig(agentConfig, def, requestedSnmpVersion); } return agentConfig; } finally { SnmpPeerFactory.getReadLock().unlock(); } } private void setSnmpAgentConfig(final SnmpAgentConfig agentConfig, final Definition def, final int requestedSnmpVersion) { int version = determineVersion(def, requestedSnmpVersion); setCommonAttributes(agentConfig, def, version); agentConfig.setSecurityLevel(determineSecurityLevel(def)); agentConfig.setSecurityName(determineSecurityName(def)); agentConfig.setAuthProtocol(determineAuthProtocol(def)); agentConfig.setAuthPassPhrase(determineAuthPassPhrase(def)); agentConfig.setPrivPassPhrase(determinePrivPassPhrase(def)); agentConfig.setPrivProtocol(determinePrivProtocol(def)); agentConfig.setReadCommunity(determineReadCommunity(def)); agentConfig.setWriteCommunity(determineWriteCommunity(def)); agentConfig.setContextName(determineContextName(def)); agentConfig.setEngineId(determineEngineId(def)); agentConfig.setContextEngineId(determineContextEngineId(def)); } /** * This is a helper method to set all the common attributes in the agentConfig. * * @param agentConfig * @param def * @param version */ private void setCommonAttributes(final SnmpAgentConfig agentConfig, final Definition def, final int version) { agentConfig.setVersion(version); agentConfig.setPort(determinePort(def)); agentConfig.setRetries(determineRetries(def)); agentConfig.setTimeout((int)determineTimeout(def)); agentConfig.setMaxRequestSize(determineMaxRequestSize(def)); agentConfig.setMaxVarsPerPdu(determineMaxVarsPerPdu(def)); agentConfig.setMaxRepetitions(determineMaxRepetitions(def)); InetAddress proxyHost = determineProxyHost(def); if (proxyHost != null) { agentConfig.setProxyFor(agentConfig.getAddress()); agentConfig.setAddress(determineProxyHost(def)); } } private int determineMaxRepetitions(final Definition def) { return (!def.hasMaxRepetitions() ? (!m_config.hasMaxRepetitions() ? SnmpAgentConfig.DEFAULT_MAX_REPETITIONS : m_config.getMaxRepetitions()) : def.getMaxRepetitions()); } private InetAddress determineProxyHost(final Definition def) { InetAddress inetAddr = null; final String address = def.getProxyHost() == null ? (m_config.getProxyHost() == null ? null : m_config.getProxyHost()) : def.getProxyHost(); if (address != null) { try { inetAddr = InetAddressUtils.addr(address); } catch (final IllegalArgumentException e) { LogUtils.debugf(this, e, "Error while reading SNMP config proxy host: %s", address); } } return inetAddr; } private int determineMaxVarsPerPdu(final Definition def) { return (!def.hasMaxVarsPerPdu() ? (!m_config.hasMaxVarsPerPdu() ? SnmpAgentConfig.DEFAULT_MAX_VARS_PER_PDU : m_config.getMaxVarsPerPdu()) : def.getMaxVarsPerPdu()); } /** * Helper method to search the snmp-config for the appropriate read * community string. * @param def * @return */ private String determineReadCommunity(final Definition def) { return (def.getReadCommunity() == null ? (m_config.getReadCommunity() == null ? SnmpAgentConfig.DEFAULT_READ_COMMUNITY :m_config.getReadCommunity()) : def.getReadCommunity()); } /** * Helper method to search the snmp-config for the appropriate write * community string. * @param def * @return */ private String determineWriteCommunity(final Definition def) { return (def.getWriteCommunity() == null ? (m_config.getWriteCommunity() == null ? SnmpAgentConfig.DEFAULT_WRITE_COMMUNITY :m_config.getWriteCommunity()) : def.getWriteCommunity()); } /** * Helper method to search the snmp-config for the appropriate maximum * request size. The default is the minimum necessary for a request. * @param def * @return */ private int determineMaxRequestSize(final Definition def) { return (!def.hasMaxRequestSize() ? (!m_config.hasMaxRequestSize() ? SnmpAgentConfig.DEFAULT_MAX_REQUEST_SIZE : m_config.getMaxRequestSize()) : def.getMaxRequestSize()); } /** * Helper method to find a security name to use in the snmp-config. If v3 has * been specified and one can't be found, then a default is used for this * is a required option for v3 operations. * @param def * @return */ private String determineSecurityName(final Definition def) { final String securityName = (def.getSecurityName() == null ? m_config.getSecurityName() : def.getSecurityName() ); if (securityName == null) { return SnmpAgentConfig.DEFAULT_SECURITY_NAME; } return securityName; } /** * Helper method to find a security name to use in the snmp-config. If v3 has * been specified and one can't be found, then a default is used for this * is a required option for v3 operations. * @param def * @return */ private String determineAuthProtocol(final Definition def) { final String authProtocol = (def.getAuthProtocol() == null ? m_config.getAuthProtocol() : def.getAuthProtocol()); if (authProtocol == null && determineAuthPassPhrase(def) != null) { return SnmpAgentConfig.DEFAULT_AUTH_PROTOCOL; } return authProtocol; } /** * Helper method to find a authentication passphrase to use from the snmp-config. If v3 has * been specified and one can't be found, then a default is used for this * is a required option for v3 operations. * @param def * @return */ private String determineAuthPassPhrase(final Definition def) { final String authPassPhrase = (def.getAuthPassphrase() == null ? m_config.getAuthPassphrase() : def.getAuthPassphrase()); // Forcing a default is wrong, because if it is not explicitly defined, probably it means that it should not be used, and SNMP4J expect null for optional parameters. /* if (authPassPhrase == null) { return SnmpAgentConfig.DEFAULT_AUTH_PASS_PHRASE; } */ return authPassPhrase; } /** * Helper method to find a privacy passphrase to use from the snmp-config. If v3 has * been specified and one can't be found, then a default is used for this * is a required option for v3 operations. * @param def * @return */ private String determinePrivPassPhrase(final Definition def) { final String privPassPhrase = (def.getPrivacyPassphrase() == null ? m_config.getPrivacyPassphrase() : def.getPrivacyPassphrase()); // Forcing a default is wrong, because if it is not explicitly defined, probably it means that it should not be used, and SNMP4J expect null for optional parameters. /* if (privPassPhrase == null) { return SnmpAgentConfig.DEFAULT_PRIV_PASS_PHRASE; } */ return privPassPhrase; } /** * Helper method to find a privacy protocol to use from the snmp-config. If v3 has * been specified and one can't be found, then a default is used for this * is a required option for v3 operations. * @param def * @return */ private String determinePrivProtocol(final Definition def) { final String authPrivProtocol = (def.getPrivacyProtocol() == null ? m_config.getPrivacyProtocol() : def.getPrivacyProtocol()); if (authPrivProtocol == null && determinePrivPassPhrase(def) != null) { return SnmpAgentConfig.DEFAULT_PRIV_PROTOCOL; } return authPrivProtocol; } /** * Helper method to set the security level in v3 operations. The default is * noAuthNoPriv if there is no authentication passphrase. From there, if * there is a privacy passphrase supplied, then the security level is set to * authPriv else it falls out to authNoPriv. There are only these 3 possible * security levels. * default * @param def * @return */ private int determineSecurityLevel(final Definition def) { // use the def security level first if (def.hasSecurityLevel()) { return def.getSecurityLevel(); } // use a configured default security level next if (m_config.hasSecurityLevel()) { return m_config.getSecurityLevel(); } // if no security level configuration exists use int securityLevel = SnmpAgentConfig.NOAUTH_NOPRIV; final String authPassPhrase = (StringUtils.isBlank(def.getAuthPassphrase()) ? m_config.getAuthPassphrase() : def.getAuthPassphrase()); final String privPassPhrase = (StringUtils.isBlank(def.getPrivacyPassphrase()) ? m_config.getPrivacyPassphrase() : def.getPrivacyPassphrase()); if (authPassPhrase == null) { securityLevel = SnmpAgentConfig.NOAUTH_NOPRIV; } else { if (privPassPhrase == null) { securityLevel = SnmpAgentConfig.AUTH_NOPRIV; } else { securityLevel = SnmpAgentConfig.AUTH_PRIV; } } return securityLevel; } /** * Helper method to find a context name to use from the snmp-config. * @param def * @return */ private String determineContextName(final Definition def) { final String contextName = (def.getContextName() == null ? m_config.getContextName() : def.getContextName()); if (contextName == null) { return SnmpAgentConfig.DEFAULT_CONTEXT_NAME; } return contextName; } /** * Helper method to find an engine ID to use from the snmp-config. * @param def * @return */ private String determineEngineId(final Definition def) { final String engineId = (def.getEngineId() == null ? m_config.getEngineId() : def.getEngineId()); if (engineId == null) { return SnmpAgentConfig.DEFAULT_ENGINE_ID; } return engineId; } /** * Helper method to find a context engine ID to use from the snmp-config. * @param def * @return */ private String determineContextEngineId(final Definition def) { final String contextEngineId = (def.getContextEngineId() == null ? m_config.getContextEngineId() : def.getContextEngineId()); if (contextEngineId == null) { return SnmpAgentConfig.DEFAULT_CONTEXT_ENGINE_ID; } return contextEngineId; } /** * Helper method to search the snmp-config for a port * @param def * @return */ private int determinePort(final Definition def) { return (def.getPort() == 0 ? (m_config.getPort() == 0 ? DEFAULT_SNMP_PORT : m_config.getPort()) : def.getPort()); } /** * Helper method to search the snmp-config * @param def * @return */ private long determineTimeout(final Definition def) { final long timeout = SnmpAgentConfig.DEFAULT_TIMEOUT; return (def.getTimeout() == 0 ? (m_config.getTimeout() == 0 ? timeout : m_config.getTimeout()) : def.getTimeout()); } private int determineRetries(final Definition def) { final int retries = SnmpAgentConfig.DEFAULT_RETRIES; return (def.getRetry() == 0 ? (m_config.getRetry() == 0 ? retries : m_config.getRetry()) : def.getRetry()); } /** * This method determines the configured SNMP version. * the order of operations is: * 1st: return a valid requested version * 2nd: return a valid version defined in a definition within the snmp-config * 3rd: return a valid version in the snmp-config * 4th: return the default version * * @param def * @param requestedSnmpVersion * @return */ private int determineVersion(final Definition def, final int requestedSnmpVersion) { int version = SnmpAgentConfig.VERSION1; String cfgVersion = "v1"; if (requestedSnmpVersion == VERSION_UNSPECIFIED) { if (def.getVersion() == null) { if (m_config.getVersion() == null) { return version; } else { cfgVersion = m_config.getVersion(); } } else { cfgVersion = def.getVersion(); } } else { return requestedSnmpVersion; } if (cfgVersion.equals("v1")) { version = SnmpAgentConfig.VERSION1; } else if (cfgVersion.equals("v2c")) { version = SnmpAgentConfig.VERSION2C; } else if (cfgVersion.equals("v3")) { version = SnmpAgentConfig.VERSION3; } return version; } /** * <p>getSnmpConfig</p> * * @return a {@link org.opennms.netmgt.config.snmp.SnmpConfig} object. */ public static SnmpConfig getSnmpConfig() { SnmpPeerFactory.getReadLock().lock(); try { return m_config; } finally { SnmpPeerFactory.getReadLock().unlock(); } } /** * Enhancement: Allows specific or ranges to be merged into SNMP configuration * with many other attributes. Uses new classes the wrap Castor-generated code to * help with merging, comparing, and optimizing definitions. Thanks for your * initial work on this Gerald. * * Puts a specific IP address with associated read-community string into * the currently loaded snmp-config.xml. * * @param info a {@link org.opennms.netmgt.config.SnmpEventInfo} object. */ public void define(final SnmpEventInfo info) { getWriteLock().lock(); try { final SnmpConfigManager mgr = new SnmpConfigManager(m_config); mgr.mergeIntoConfig(info.createDef()); } finally { getWriteLock().unlock(); } } /** * Creates a string containing the XML of the current SnmpConfig * * @return Marshalled SnmpConfig */ public static String marshallConfig() { SnmpPeerFactory.getReadLock().lock(); try { String marshalledConfig = null; StringWriter writer = null; try { writer = new StringWriter(); JaxbUtils.marshal(m_config, writer); marshalledConfig = writer.toString(); } finally { IOUtils.closeQuietly(writer); } return marshalledConfig; } finally { SnmpPeerFactory.getReadLock().unlock(); } } }
opennms-config/src/main/java/org/opennms/netmgt/config/SnmpPeerFactory.java
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) 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. * * OpenNMS(R) 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 OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <[email protected]> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.config; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.net.InetAddress; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.opennms.core.utils.ByteArrayComparator; import org.opennms.core.utils.ConfigFileConstants; import org.opennms.core.utils.IPLike; import org.opennms.core.utils.InetAddressUtils; import org.opennms.core.utils.LogUtils; import org.opennms.core.xml.JaxbUtils; import org.opennms.netmgt.config.snmp.Definition; import org.opennms.netmgt.config.snmp.Range; import org.opennms.netmgt.config.snmp.SnmpConfig; import org.opennms.netmgt.snmp.SnmpAgentConfig; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.xml.sax.InputSource; /** * This class is the main repository for SNMP configuration information used by * the capabilities daemon. When this class is loaded it reads the snmp * configuration into memory, and uses the configuration to find the * {@link org.opennms.netmgt.snmp.SnmpAgentConfig SnmpAgentConfig} objects for specific * addresses. If an address cannot be located in the configuration then a * default peer instance is returned to the caller. * * <strong>Note: </strong>Users of this class should make sure the * <em>init()</em> is called before calling any other method to ensure the * config is loaded before accessing other convenience methods. * * @author <a href="mailto:[email protected]">David Hustace</a> * @author <a href="mailto:[email protected]">Weave</a> * @author <a href="mailto:[email protected]">Gerald Turner</a> */ public class SnmpPeerFactory implements SnmpAgentConfigFactory { private static final int DEFAULT_SNMP_PORT = 161; private static final ReadWriteLock m_globalLock = new ReentrantReadWriteLock(); private static final Lock m_readLock = m_globalLock.readLock(); private static final Lock m_writeLock = m_globalLock.writeLock(); /** * The singleton instance of this factory */ private static SnmpPeerFactory m_singleton = null; /** * The config class loaded from the config file */ private static SnmpConfig m_config; private static File m_configFile; /** * This member is set to true if the configuration file has been loaded. */ private static boolean m_loaded = false; private static final int VERSION_UNSPECIFIED = -1; /** * Private constructor * * @exception java.io.IOException * Thrown if the specified config file cannot be read * @exception org.exolab.castor.xml.MarshalException * Thrown if the file does not conform to the schema. * @exception org.exolab.castor.xml.ValidationException * Thrown if the contents do not match the required schema. */ private SnmpPeerFactory(final File configFile) throws IOException { this(new FileSystemResource(configFile)); } /** * <p>Constructor for SnmpPeerFactory.</p> * * @param resource a {@link org.springframework.core.io.Resource} object. */ public SnmpPeerFactory(final Resource resource) { SnmpPeerFactory.getWriteLock().lock(); try { m_config = JaxbUtils.unmarshal(SnmpConfig.class, resource); } finally { SnmpPeerFactory.getWriteLock().unlock(); } } /** * <p>Constructor for SnmpPeerFactory.</p> * * @param rdr a {@link java.io.Reader} object. * @throws java.io.IOException if any. * @throws org.exolab.castor.xml.MarshalException if any. * @throws org.exolab.castor.xml.ValidationException if any. * @deprecated Use code for InputStream instead to avoid character set issues */ public SnmpPeerFactory(final Reader rdr) throws IOException { SnmpPeerFactory.getWriteLock().lock(); try { m_config = JaxbUtils.unmarshal(SnmpConfig.class, rdr); } finally { SnmpPeerFactory.getWriteLock().unlock(); } } /** * A constructor that takes a config string for use mostly in tests */ public SnmpPeerFactory(final String configString) throws IOException { SnmpPeerFactory.getWriteLock().lock(); try { m_config = JaxbUtils.unmarshal(SnmpConfig.class, configString); } finally { SnmpPeerFactory.getWriteLock().unlock(); } } /** * <p>Constructor for SnmpPeerFactory.</p> * * @param stream a {@link java.io.InputStream} object. */ public SnmpPeerFactory(final InputStream stream) { SnmpPeerFactory.getWriteLock().lock(); try { m_config = JaxbUtils.unmarshal(SnmpConfig.class, new InputSource(stream), null); } finally { SnmpPeerFactory.getWriteLock().unlock(); } } public static Lock getReadLock() { return m_readLock; } public static Lock getWriteLock() { return m_writeLock; } /** * Load the config from the default config file and create the singleton * instance of this factory. * * @exception java.io.IOException * Thrown if the specified config file cannot be read * @exception org.exolab.castor.xml.MarshalException * Thrown if the file does not conform to the schema. * @exception org.exolab.castor.xml.ValidationException * Thrown if the contents do not match the required schema. * @throws java.io.IOException if any. * @throws org.exolab.castor.xml.MarshalException if any. * @throws org.exolab.castor.xml.ValidationException if any. */ public static void init() throws IOException { SnmpPeerFactory.getWriteLock().lock(); try { if (m_loaded) { // init already called - return // to reload, reload() will need to be called return; } final File cfgFile = getFile(); LogUtils.debugf(SnmpPeerFactory.class, "init: config file path: %s", cfgFile.getPath()); m_singleton = new SnmpPeerFactory(cfgFile); m_loaded = true; } finally { SnmpPeerFactory.getWriteLock().unlock(); } } /** * Saves the current settings to disk * * @throws java.io.IOException if any. * @throws org.exolab.castor.xml.MarshalException if any. * @throws org.exolab.castor.xml.ValidationException if any. */ public static void saveCurrent() throws IOException { saveToFile(getFile()); } public static void saveToFile(final File file) throws UnsupportedEncodingException, FileNotFoundException, IOException { // Marshal to a string first, then write the string to the file. This // way the original config // isn't lost if the XML from the marshal is hosed. final String marshalledConfig = marshallConfig(); SnmpPeerFactory.getWriteLock().lock(); FileOutputStream out = null; Writer fileWriter = null; try { if (marshalledConfig != null) { out = new FileOutputStream(file); fileWriter = new OutputStreamWriter(out, "UTF-8"); fileWriter.write(marshalledConfig); fileWriter.flush(); fileWriter.close(); } } finally { IOUtils.closeQuietly(fileWriter); IOUtils.closeQuietly(out); SnmpPeerFactory.getWriteLock().unlock(); } } /** * Return the singleton instance of this factory. * * @return The current factory instance. * @throws java.lang.IllegalStateException * Thrown if the factory has not yet been initialized. */ public static SnmpPeerFactory getInstance() { SnmpPeerFactory.getReadLock().lock(); try { if (!m_loaded) { throw new IllegalStateException("The factory has not been initialized"); } return m_singleton; } finally { SnmpPeerFactory.getReadLock().unlock(); } } /** * <p>setFile</p> * * @param configFile a {@link java.io.File} object. */ public static void setFile(final File configFile) { SnmpPeerFactory.getWriteLock().lock(); try { final File oldFile = m_configFile; m_configFile = configFile; // if the file changed then we need to reload the config if (oldFile == null || m_configFile == null || !oldFile.equals(m_configFile)) { m_singleton = null; m_loaded = false; } } finally { SnmpPeerFactory.getWriteLock().unlock(); } } /** * <p>getFile</p> * * @return a {@link java.io.File} object. * @throws java.io.IOException if any. */ public static File getFile() throws IOException { SnmpPeerFactory.getReadLock().lock(); try { if (m_configFile == null) { setFile(ConfigFileConstants.getFile(ConfigFileConstants.SNMP_CONF_FILE_NAME)); } return m_configFile; } finally { SnmpPeerFactory.getReadLock().unlock(); } } /** * <p>setInstance</p> * * @param singleton a {@link org.opennms.netmgt.config.SnmpPeerFactory} object. */ public static void setInstance(final SnmpPeerFactory singleton) { SnmpPeerFactory.getWriteLock().lock(); try { m_singleton = singleton; m_loaded = true; } finally { SnmpPeerFactory.getWriteLock().unlock(); } } /** {@inheritDoc} */ public SnmpAgentConfig getAgentConfig(final InetAddress agentAddress) { return getAgentConfig(agentAddress, VERSION_UNSPECIFIED); } private SnmpAgentConfig getAgentConfig(final InetAddress agentInetAddress, final int requestedSnmpVersion) { SnmpPeerFactory.getReadLock().lock(); try { if (m_config == null) { final SnmpAgentConfig agentConfig = new SnmpAgentConfig(agentInetAddress); if (requestedSnmpVersion == VERSION_UNSPECIFIED) { agentConfig.setVersion(SnmpAgentConfig.DEFAULT_VERSION); } else { agentConfig.setVersion(requestedSnmpVersion); } return agentConfig; } final SnmpAgentConfig agentConfig = new SnmpAgentConfig(agentInetAddress); // Now set the defaults from the m_config setSnmpAgentConfig(agentConfig, new Definition(), requestedSnmpVersion); // Attempt to locate the node DEFLOOP: for (final Definition def : m_config.getDefinitionCollection()) { // check the specifics first for (final String saddr : def.getSpecificCollection()) { try { final InetAddress addr = InetAddressUtils.addr(saddr); if (addr != null && addr.equals(agentConfig.getAddress())) { setSnmpAgentConfig(agentConfig, def, requestedSnmpVersion); break DEFLOOP; } } catch (final IllegalArgumentException e) { LogUtils.debugf(this, e, "Error while reading SNMP config <specific> tag: %s", saddr); } } // check the ranges // final ByteArrayComparator comparator = new ByteArrayComparator(); for (final Range rng : def.getRangeCollection()) { final byte[] addr = agentConfig.getAddress().getAddress(); final byte[] begin = InetAddressUtils.toIpAddrBytes(rng.getBegin()); final byte[] end = InetAddressUtils.toIpAddrBytes(rng.getEnd()); boolean inRange = InetAddressUtils.isInetAddressInRange(addr, begin, end); if (comparator.compare(begin, end) <= 0) { inRange = InetAddressUtils.isInetAddressInRange(addr, begin, end); } else { LogUtils.warnf(this, "%s has an 'end' that is earlier than its 'beginning'!", rng); inRange = InetAddressUtils.isInetAddressInRange(addr, end, begin); } if (inRange) { setSnmpAgentConfig(agentConfig, def, requestedSnmpVersion); break DEFLOOP; } } // check the matching ip expressions for (final String ipMatch : def.getIpMatchCollection()) { if (IPLike.matches(agentInetAddress, ipMatch)) { setSnmpAgentConfig(agentConfig, def, requestedSnmpVersion); break DEFLOOP; } } } // end DEFLOOP if (agentConfig == null) { final Definition def = new Definition(); setSnmpAgentConfig(agentConfig, def, requestedSnmpVersion); } return agentConfig; } finally { SnmpPeerFactory.getReadLock().unlock(); } } private void setSnmpAgentConfig(final SnmpAgentConfig agentConfig, final Definition def, final int requestedSnmpVersion) { int version = determineVersion(def, requestedSnmpVersion); setCommonAttributes(agentConfig, def, version); agentConfig.setSecurityLevel(determineSecurityLevel(def)); agentConfig.setSecurityName(determineSecurityName(def)); agentConfig.setAuthProtocol(determineAuthProtocol(def)); agentConfig.setAuthPassPhrase(determineAuthPassPhrase(def)); agentConfig.setPrivPassPhrase(determinePrivPassPhrase(def)); agentConfig.setPrivProtocol(determinePrivProtocol(def)); agentConfig.setReadCommunity(determineReadCommunity(def)); agentConfig.setWriteCommunity(determineWriteCommunity(def)); agentConfig.setContextName(determineContextName(def)); agentConfig.setEngineId(determineEngineId(def)); agentConfig.setContextEngineId(determineContextEngineId(def)); } /** * This is a helper method to set all the common attributes in the agentConfig. * * @param agentConfig * @param def * @param version */ private void setCommonAttributes(final SnmpAgentConfig agentConfig, final Definition def, final int version) { agentConfig.setVersion(version); agentConfig.setPort(determinePort(def)); agentConfig.setRetries(determineRetries(def)); agentConfig.setTimeout((int)determineTimeout(def)); agentConfig.setMaxRequestSize(determineMaxRequestSize(def)); agentConfig.setMaxVarsPerPdu(determineMaxVarsPerPdu(def)); agentConfig.setMaxRepetitions(determineMaxRepetitions(def)); InetAddress proxyHost = determineProxyHost(def); if (proxyHost != null) { agentConfig.setProxyFor(agentConfig.getAddress()); agentConfig.setAddress(determineProxyHost(def)); } } private int determineMaxRepetitions(final Definition def) { return (!def.hasMaxRepetitions() ? (!m_config.hasMaxRepetitions() ? SnmpAgentConfig.DEFAULT_MAX_REPETITIONS : m_config.getMaxRepetitions()) : def.getMaxRepetitions()); } private InetAddress determineProxyHost(final Definition def) { InetAddress inetAddr = null; final String address = def.getProxyHost() == null ? (m_config.getProxyHost() == null ? null : m_config.getProxyHost()) : def.getProxyHost(); if (address != null) { try { inetAddr = InetAddressUtils.addr(address); } catch (final IllegalArgumentException e) { LogUtils.debugf(this, e, "Error while reading SNMP config proxy host: %s", address); } } return inetAddr; } private int determineMaxVarsPerPdu(final Definition def) { return (!def.hasMaxVarsPerPdu() ? (!m_config.hasMaxVarsPerPdu() ? SnmpAgentConfig.DEFAULT_MAX_VARS_PER_PDU : m_config.getMaxVarsPerPdu()) : def.getMaxVarsPerPdu()); } /** * Helper method to search the snmp-config for the appropriate read * community string. * @param def * @return */ private String determineReadCommunity(final Definition def) { return (def.getReadCommunity() == null ? (m_config.getReadCommunity() == null ? SnmpAgentConfig.DEFAULT_READ_COMMUNITY :m_config.getReadCommunity()) : def.getReadCommunity()); } /** * Helper method to search the snmp-config for the appropriate write * community string. * @param def * @return */ private String determineWriteCommunity(final Definition def) { return (def.getWriteCommunity() == null ? (m_config.getWriteCommunity() == null ? SnmpAgentConfig.DEFAULT_WRITE_COMMUNITY :m_config.getWriteCommunity()) : def.getWriteCommunity()); } /** * Helper method to search the snmp-config for the appropriate maximum * request size. The default is the minimum necessary for a request. * @param def * @return */ private int determineMaxRequestSize(final Definition def) { return (!def.hasMaxRequestSize() ? (!m_config.hasMaxRequestSize() ? SnmpAgentConfig.DEFAULT_MAX_REQUEST_SIZE : m_config.getMaxRequestSize()) : def.getMaxRequestSize()); } /** * Helper method to find a security name to use in the snmp-config. If v3 has * been specified and one can't be found, then a default is used for this * is a required option for v3 operations. * @param def * @return */ private String determineSecurityName(final Definition def) { final String securityName = (def.getSecurityName() == null ? m_config.getSecurityName() : def.getSecurityName() ); if (securityName == null) { return SnmpAgentConfig.DEFAULT_SECURITY_NAME; } return securityName; } /** * Helper method to find a security name to use in the snmp-config. If v3 has * been specified and one can't be found, then a default is used for this * is a required option for v3 operations. * @param def * @return */ private String determineAuthProtocol(final Definition def) { final String authProtocol = (def.getAuthProtocol() == null ? m_config.getAuthProtocol() : def.getAuthProtocol()); // Forcing a default is wrong, because if it is not explicitly defined, probably it means that it should not be used, and SNMP4J expect null for optional parameters. /* if (authProtocol == null) { return SnmpAgentConfig.DEFAULT_AUTH_PROTOCOL; } */ return authProtocol; } /** * Helper method to find a authentication passphrase to use from the snmp-config. If v3 has * been specified and one can't be found, then a default is used for this * is a required option for v3 operations. * @param def * @return */ private String determineAuthPassPhrase(final Definition def) { final String authPassPhrase = (def.getAuthPassphrase() == null ? m_config.getAuthPassphrase() : def.getAuthPassphrase()); // Forcing a default is wrong, because if it is not explicitly defined, probably it means that it should not be used, and SNMP4J expect null for optional parameters. /* if (authPassPhrase == null) { return SnmpAgentConfig.DEFAULT_AUTH_PASS_PHRASE; } */ return authPassPhrase; } /** * Helper method to find a privacy passphrase to use from the snmp-config. If v3 has * been specified and one can't be found, then a default is used for this * is a required option for v3 operations. * @param def * @return */ private String determinePrivPassPhrase(final Definition def) { final String privPassPhrase = (def.getPrivacyPassphrase() == null ? m_config.getPrivacyPassphrase() : def.getPrivacyPassphrase()); // Forcing a default is wrong, because if it is not explicitly defined, probably it means that it should not be used, and SNMP4J expect null for optional parameters. /* if (privPassPhrase == null) { return SnmpAgentConfig.DEFAULT_PRIV_PASS_PHRASE; } */ return privPassPhrase; } /** * Helper method to find a privacy protocol to use from the snmp-config. If v3 has * been specified and one can't be found, then a default is used for this * is a required option for v3 operations. * @param def * @return */ private String determinePrivProtocol(final Definition def) { final String authPrivProtocol = (def.getPrivacyProtocol() == null ? m_config.getPrivacyProtocol() : def.getPrivacyProtocol()); // Forcing a default is wrong, because if it is not explicitly defined, probably it means that it should not be used, and SNMP4J expect null for optional parameters. /* if (authPrivProtocol == null) { return SnmpAgentConfig.DEFAULT_PRIV_PROTOCOL; } */ return authPrivProtocol; } /** * Helper method to set the security level in v3 operations. The default is * noAuthNoPriv if there is no authentication passphrase. From there, if * there is a privacy passphrase supplied, then the security level is set to * authPriv else it falls out to authNoPriv. There are only these 3 possible * security levels. * default * @param def * @return */ private int determineSecurityLevel(final Definition def) { // use the def security level first if (def.hasSecurityLevel()) { return def.getSecurityLevel(); } // use a configured default security level next if (m_config.hasSecurityLevel()) { return m_config.getSecurityLevel(); } // if no security level configuration exists use int securityLevel = SnmpAgentConfig.NOAUTH_NOPRIV; final String authPassPhrase = (StringUtils.isBlank(def.getAuthPassphrase()) ? m_config.getAuthPassphrase() : def.getAuthPassphrase()); final String privPassPhrase = (StringUtils.isBlank(def.getPrivacyPassphrase()) ? m_config.getPrivacyPassphrase() : def.getPrivacyPassphrase()); if (authPassPhrase == null) { securityLevel = SnmpAgentConfig.NOAUTH_NOPRIV; } else { if (privPassPhrase == null) { securityLevel = SnmpAgentConfig.AUTH_NOPRIV; } else { securityLevel = SnmpAgentConfig.AUTH_PRIV; } } return securityLevel; } /** * Helper method to find a context name to use from the snmp-config. * @param def * @return */ private String determineContextName(final Definition def) { final String contextName = (def.getContextName() == null ? m_config.getContextName() : def.getContextName()); if (contextName == null) { return SnmpAgentConfig.DEFAULT_CONTEXT_NAME; } return contextName; } /** * Helper method to find an engine ID to use from the snmp-config. * @param def * @return */ private String determineEngineId(final Definition def) { final String engineId = (def.getEngineId() == null ? m_config.getEngineId() : def.getEngineId()); if (engineId == null) { return SnmpAgentConfig.DEFAULT_ENGINE_ID; } return engineId; } /** * Helper method to find a context engine ID to use from the snmp-config. * @param def * @return */ private String determineContextEngineId(final Definition def) { final String contextEngineId = (def.getContextEngineId() == null ? m_config.getContextEngineId() : def.getContextEngineId()); if (contextEngineId == null) { return SnmpAgentConfig.DEFAULT_CONTEXT_ENGINE_ID; } return contextEngineId; } /** * Helper method to search the snmp-config for a port * @param def * @return */ private int determinePort(final Definition def) { return (def.getPort() == 0 ? (m_config.getPort() == 0 ? DEFAULT_SNMP_PORT : m_config.getPort()) : def.getPort()); } /** * Helper method to search the snmp-config * @param def * @return */ private long determineTimeout(final Definition def) { final long timeout = SnmpAgentConfig.DEFAULT_TIMEOUT; return (def.getTimeout() == 0 ? (m_config.getTimeout() == 0 ? timeout : m_config.getTimeout()) : def.getTimeout()); } private int determineRetries(final Definition def) { final int retries = SnmpAgentConfig.DEFAULT_RETRIES; return (def.getRetry() == 0 ? (m_config.getRetry() == 0 ? retries : m_config.getRetry()) : def.getRetry()); } /** * This method determines the configured SNMP version. * the order of operations is: * 1st: return a valid requested version * 2nd: return a valid version defined in a definition within the snmp-config * 3rd: return a valid version in the snmp-config * 4th: return the default version * * @param def * @param requestedSnmpVersion * @return */ private int determineVersion(final Definition def, final int requestedSnmpVersion) { int version = SnmpAgentConfig.VERSION1; String cfgVersion = "v1"; if (requestedSnmpVersion == VERSION_UNSPECIFIED) { if (def.getVersion() == null) { if (m_config.getVersion() == null) { return version; } else { cfgVersion = m_config.getVersion(); } } else { cfgVersion = def.getVersion(); } } else { return requestedSnmpVersion; } if (cfgVersion.equals("v1")) { version = SnmpAgentConfig.VERSION1; } else if (cfgVersion.equals("v2c")) { version = SnmpAgentConfig.VERSION2C; } else if (cfgVersion.equals("v3")) { version = SnmpAgentConfig.VERSION3; } return version; } /** * <p>getSnmpConfig</p> * * @return a {@link org.opennms.netmgt.config.snmp.SnmpConfig} object. */ public static SnmpConfig getSnmpConfig() { SnmpPeerFactory.getReadLock().lock(); try { return m_config; } finally { SnmpPeerFactory.getReadLock().unlock(); } } /** * Enhancement: Allows specific or ranges to be merged into SNMP configuration * with many other attributes. Uses new classes the wrap Castor-generated code to * help with merging, comparing, and optimizing definitions. Thanks for your * initial work on this Gerald. * * Puts a specific IP address with associated read-community string into * the currently loaded snmp-config.xml. * * @param info a {@link org.opennms.netmgt.config.SnmpEventInfo} object. */ public void define(final SnmpEventInfo info) { getWriteLock().lock(); try { final SnmpConfigManager mgr = new SnmpConfigManager(m_config); mgr.mergeIntoConfig(info.createDef()); } finally { getWriteLock().unlock(); } } /** * Creates a string containing the XML of the current SnmpConfig * * @return Marshalled SnmpConfig */ public static String marshallConfig() { SnmpPeerFactory.getReadLock().lock(); try { String marshalledConfig = null; StringWriter writer = null; try { writer = new StringWriter(); JaxbUtils.marshal(m_config, writer); marshalledConfig = writer.toString(); } finally { IOUtils.closeQuietly(writer); } return marshalledConfig; } finally { SnmpPeerFactory.getReadLock().unlock(); } } }
Fixing NMS-6108: Can't use SNMPv3 with NoAuth-NoPriv (Part II) Bamboo has reported some failures. These tests are associated with a specific use case on snmp-config.xml that was not taken in consideration by my fix. Now all the tests are passing without issues.
opennms-config/src/main/java/org/opennms/netmgt/config/SnmpPeerFactory.java
Fixing NMS-6108: Can't use SNMPv3 with NoAuth-NoPriv (Part II)
<ide><path>pennms-config/src/main/java/org/opennms/netmgt/config/SnmpPeerFactory.java <ide> */ <ide> private String determineAuthProtocol(final Definition def) { <ide> final String authProtocol = (def.getAuthProtocol() == null ? m_config.getAuthProtocol() : def.getAuthProtocol()); <del> // Forcing a default is wrong, because if it is not explicitly defined, probably it means that it should not be used, and SNMP4J expect null for optional parameters. <del> /* <del> if (authProtocol == null) { <add> if (authProtocol == null && determineAuthPassPhrase(def) != null) { <ide> return SnmpAgentConfig.DEFAULT_AUTH_PROTOCOL; <ide> } <del> */ <ide> return authProtocol; <ide> } <ide> <ide> */ <ide> private String determinePrivProtocol(final Definition def) { <ide> final String authPrivProtocol = (def.getPrivacyProtocol() == null ? m_config.getPrivacyProtocol() : def.getPrivacyProtocol()); <del> // Forcing a default is wrong, because if it is not explicitly defined, probably it means that it should not be used, and SNMP4J expect null for optional parameters. <del> /* <del> if (authPrivProtocol == null) { <add> if (authPrivProtocol == null && determinePrivPassPhrase(def) != null) { <ide> return SnmpAgentConfig.DEFAULT_PRIV_PROTOCOL; <ide> } <del> */ <ide> return authPrivProtocol; <ide> } <ide>
Java
apache-2.0
a24c5301d037897a187568ee9979778a38e2d4a2
0
lesjaw/Olmatix
package com.olmatix.service; import android.Manifest; import android.app.Activity; import android.app.ActivityManager; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.app.TaskStackBuilder; import android.app.usage.UsageStats; import android.app.usage.UsageStatsManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.media.RingtoneManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Binder; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.preference.PreferenceManager; import android.support.v4.app.ActivityCompat; import android.support.v4.app.NotificationManagerCompat; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.NotificationCompat; import android.util.Log; import android.widget.Toast; import com.olmatix.database.dbNode; import com.olmatix.database.dbNodeRepo; import com.olmatix.helper.PreferenceHelper; import com.olmatix.lesjaw.olmatix.R; import com.olmatix.model.DetailNodeModel; import com.olmatix.model.DurationModel; import com.olmatix.model.InstalledNodeModel; import com.olmatix.ui.activity.MainActivity; import com.olmatix.ui.fragment.DetailNode; import com.olmatix.utils.Connection; import com.olmatix.utils.OlmatixUtils; import org.eclipse.paho.android.service.MqttAndroidClient; import org.eclipse.paho.client.mqttv3.IMqttActionListener; import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.IMqttToken; import org.eclipse.paho.client.mqttv3.MqttAsyncClient; import org.eclipse.paho.client.mqttv3.MqttCallback; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.MqttSecurityException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.SortedMap; import java.util.TreeMap; /** * Created : Rahman on 12/2/2016. * Date Created : 12/2/2016 / 4:29 PM. * =================================================== * Package : com.olmatix.service. * Project Name : Olmatix. * Copyright : Copyright @ 2016 Indogamers. */ public class OlmatixService extends Service { public final static String MY_ACTION = "MY_ACTION"; public static dbNodeRepo mDbNodeRepo; private static String TAG = OlmatixService.class.getSimpleName(); private static boolean hasWifi = false; private static boolean hasMmobile = false; private static ArrayList<InstalledNodeModel> data; public volatile MqttAndroidClient mqttClient; HashMap<String, String> messageReceive = new HashMap<>(); HashMap<String, String> message_topic = new HashMap<>(); CharSequence text; CharSequence textNode; CharSequence titleNode; String[] textLoc; ArrayList<DetailNodeModel> data1; ArrayList<InstalledNodeModel> data2; String add_NodeID; boolean flagSub = true; boolean flagNode = false; boolean flagConn = true; boolean connSuccess = false; int notifyID = 0; String currentApp = "NULL"; String topic; String topic1; private Thread thread; private ConnectivityManager mConnMan; private String deviceId; private String stateoffMqtt = "false"; private InstalledNodeModel installedNodeModel; private DetailNodeModel detailNodeModel; private DurationModel durationModel; private dbNode dbnode; private String NodeID, Channel; private String mMessage; private NotificationManager mNM; private int NOTIFICATION = R.string.local_service_label; private String mNodeID; private String mNiceName; private String mNiceNameN; private String NodeIDSensor; private String TopicID; private String mChange = ""; final static String GROUP_KEY_NOTIF = "group_key_notif"; private ArrayList<String> notifications; public static final String BROADCAST_ACTION = "Hello World"; private static final int TWO_MINUTES = 1000 * 60 * 5; public LocationManager locationManager; public MyLocationListener listener; public Location previousBestLocation = null; private String Distance; private String dist; String adString = ""; String loc = null; Intent intent; int counter = 0; private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { add_NodeID = intent.getStringExtra("NodeID"); Log.d("DEBUG", "onReceive: " + add_NodeID); doAddNodeSub(); } }; class OlmatixBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { boolean hasConnectivity = false; boolean hasChanged = false; NetworkInfo nInfo = mConnMan.getActiveNetworkInfo(); if (nInfo != null) { if (nInfo.getType() == ConnectivityManager.TYPE_WIFI) { hasChanged = true; hasWifi = nInfo.isConnected(); } else if (nInfo.getType() == ConnectivityManager.TYPE_MOBILE) { hasChanged = true; hasMmobile = nInfo.isConnected(); } } else { //Not Connected info String msg = getString(R.string.err_internet); Toast toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT); toast.show(); stateoffMqtt = "false"; sendMessage(); text = "Disconnected"; showNotification(); flagConn = false; } hasConnectivity = hasMmobile || hasWifi; doConnect(); Log.d(TAG, "hasConn: " + hasConnectivity + " hasChange: " + hasChanged + " - " + (mqttClient == null || !mqttClient.isConnected())); if (hasConnectivity && hasChanged && (Connection.getClient() != null || Connection.getClient().isConnected())) { flagConn = false; callDis(); Log.d(TAG, "Call Disconnect first"); } else if (!hasConnectivity) { doDisconnect(); Log.d(TAG, "Disconnecting"); } } } private void callDis() { new Handler().postDelayed(new Runnable() { @Override public void run() { if (!flagConn) { doDisconnect(); callCon(); } callCon(); } }, 1000); } private void callCon() { new Handler().postDelayed(new Runnable() { @Override public void run() { if (flagConn) { doConnect(); } } }, 1000); } private void setFlagSub() { new Handler().postDelayed(new Runnable() { @Override public void run() { flagSub = true; Log.d(TAG, "run: " + flagSub); unSubIfnotForeground(); } }, 10000); } private void doDisconnect() { Log.d(TAG, "doDisconnect()" + flagConn); if (!flagConn) { try { mqttClient.disconnect(); stateoffMqtt = "false"; sendMessage(); flagConn = true; Log.d(TAG, "doDisconnect() done"); } catch (MqttException e) { e.printStackTrace(); Log.d(TAG, "onReceive: " + String.valueOf(e.getMessage())); } } } @Override public void onCreate() { IntentFilter intent = new IntentFilter(); setClientID(); intent.addAction(ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(new OlmatixBroadcastReceiver(), new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); mConnMan = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); data = new ArrayList<>(); data1 = new ArrayList<>(); data2 = new ArrayList<>(); notifications = new ArrayList<>(); Connection.setClient(mqttClient); mDbNodeRepo = new dbNodeRepo(getApplicationContext()); installedNodeModel = new InstalledNodeModel(); detailNodeModel = new DetailNodeModel(); durationModel = new DurationModel(); // Display a notification about us starting. We put an icon in the status bar. showNotification(); LocalBroadcastManager.getInstance(this).registerReceiver( mMessageReceiver, new IntentFilter("addNode")); } @Override public int onStartCommand(Intent intent, int flags, int startId) { sendMessage(); flagConn = true; locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); listener = new MyLocationListener(); if (ActivityCompat.checkSelfPermission(getApplication(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. } NetworkInfo nInfo = mConnMan.getActiveNetworkInfo(); if (nInfo != null) { if (nInfo.getType() == ConnectivityManager.TYPE_WIFI) { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, OlmatixUtils.POSITION_UPDATE_INTERVAL, OlmatixUtils.POSITION_UPDATE_MIN_DIST, listener); } else if (nInfo.getType() == ConnectivityManager.TYPE_MOBILE) { locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, OlmatixUtils.POSITION_UPDATE_INTERVAL, OlmatixUtils.POSITION_UPDATE_MIN_DIST, listener); } } return START_STICKY; } private void unSubIfnotForeground() { printForegroundTask(); Log.d("Unsubscribe", " uptime and signal"); if (!currentApp.equals("com.olmatix.lesjaw.olmatix")) { int countDB = mDbNodeRepo.getNodeList().size(); Log.d("DEBUG", "Count list Node: " + countDB); data.addAll(mDbNodeRepo.getNodeList()); if (countDB != 0) { for (int i = 0; i < countDB; i++) { final String mNodeID1 = data.get(i).getNodesID(); Log.d("DEBUG", "Count list: " + mNodeID1); for (int a = 0; a < 2; a++) { if (a == 0) { topic = "devices/" + mNodeID1 + "/$signal"; } if (a == 1) { topic = "devices/" + mNodeID1 + "/$uptime"; } try { Connection.getClient().unsubscribe(topic); } catch (MqttException e) { e.printStackTrace(); } } Log.d("Unsubscribe", " device = " + mNodeID1); } } data.clear(); } } private void showNotification() { PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0); // Set the info for the views that show in the notification panel. NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this); mBuilder.setSmallIcon(R.drawable.olmatixsmall) // the status icon .setTicker(text) // the status text .setWhen(System.currentTimeMillis()) // the time stamp .setContentTitle(getText(R.string.local_service_label)) // the label of the entry .setContentText(text) // the contents of the entry .setContentIntent(contentIntent) // The intent to send when the entry is clicked .setOngoing(true) //.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 }) .build(); // Send the notification. mNM.notify(NOTIFICATION, mBuilder.build()); } private void showNotificationNode() { //int numMessages =0; SimpleDateFormat timeformat = new SimpleDateFormat("d MMM | hh:mm"); notifications.add(String.valueOf(titleNode) + " : "+String.valueOf(textNode)+ " at " +timeformat.format(System.currentTimeMillis())); Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this); mBuilder.setContentTitle("New Olmatix status"); mBuilder.setContentText("You've received new status."); mBuilder.setTicker("Olmatix status Alert!"); mBuilder.setAutoCancel(true); mBuilder.setWhen(System.currentTimeMillis()); //mBuilder.setNumber(++numMessages); //mBuilder.setGroup(GROUP_KEY_NOTIF); //mBuilder.setGroupSummary(true); mBuilder.setSound(defaultSoundUri); mBuilder.setSmallIcon(R.drawable.olmatixsmall); NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); inboxStyle.setBigContentTitle("Olmatix status"); for (int i=0; i < notifications.size(); i++) { inboxStyle.addLine(notifications.get(i)); } mBuilder.setStyle(inboxStyle); /* Creates an explicit intent for an Activity in your app */ Intent resultIntent = new Intent(this, MainActivity.class); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(MainActivity.class); /* Adds the Intent that starts the Activity to the top of the stack */ stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent =stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); notificationManager.notify(notifyID,mBuilder.build()); } private void setClientID() { // Context mContext; WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); WifiInfo wInfo = wifiManager.getConnectionInfo(); deviceId = "OlmatixApp-" + wInfo.getMacAddress(); if (deviceId == null) { deviceId = MqttAsyncClient.generateClientId(); } } private void doConnect() { Log.d(TAG, "Check Stateof MQTT: " + stateoffMqtt); if (!stateoffMqtt.equals("true")) { stateoffMqtt = "true"; SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this); String mServerURL = sharedPref.getString("server_address", "cloud.olmatix.com"); String mServerPort = sharedPref.getString("server_port", "1883"); String mUserName = sharedPref.getString("user_name", "olmatix1"); String mPassword = sharedPref.getString("password", "olmatix"); final Boolean mSwitch_conn = sharedPref.getBoolean("switch_conn", true); final MqttConnectOptions options = new MqttConnectOptions(); options.setUserName(mUserName); options.setPassword(mPassword.toCharArray()); mqttClient = new MqttAndroidClient(getApplicationContext(), "tcp://" + mServerURL + ":" + mServerPort, deviceId); if (mSwitch_conn) { options.setCleanSession(false); } else { options.setCleanSession(true); } String topic = "status/" + deviceId + "/$online"; byte[] payload = "false".getBytes(); options.setWill(topic, payload, 1, true); options.setKeepAliveInterval(300); Connection.setClient(mqttClient); text = "Connecting to server.."; showNotification(); Log.d(TAG, "doConnect: " + deviceId); try { IMqttToken token = mqttClient.connect(options); token.setActionCallback(new IMqttActionListener() { @Override public void onSuccess(IMqttToken asyncActionToken) { text = "Connected"; showNotification(); stateoffMqtt = "true"; sendMessage(); mqttClient.setCallback(new MqttEventCallback()); try { String topic = "status/" + deviceId + "/$online"; String payload = "true"; byte[] encodedPayload = new byte[0]; try { encodedPayload = payload.getBytes("UTF-8"); MqttMessage message = new MqttMessage(encodedPayload); message.setQos(1); message.setRetained(true); Connection.getClient().publish(topic, message); } catch (UnsupportedEncodingException | MqttException e) { e.printStackTrace(); } Connection.getClient().subscribe("test", 0, getApplicationContext(), new IMqttActionListener() { @Override public void onSuccess(IMqttToken asyncActionToken) { text = "Connected"; showNotification(); stateoffMqtt = "true"; sendMessage(); Log.d(TAG, "Check FlasgConn: " + flagConn); if (flagConn) { if (stateoffMqtt.equals("true")) { if (!mSwitch_conn) { doSubAll(); } } } else { //Log.d(TAG, "Call Disconn: " + flagConn); callDis(); } } @Override public void onFailure(IMqttToken asyncActionToken, Throwable exception) { //Toast.makeText(getApplicationContext(), R.string.sub_fail, Toast.LENGTH_SHORT).show(); Log.e("error", exception.toString()); } }); } catch (MqttException e) { e.printStackTrace(); } } @Override public void onFailure(IMqttToken asyncActionToken, Throwable exception) { //Toast.makeText(getApplicationContext(), R.string.conn_fail+exception.toString(), Toast.LENGTH_SHORT).show(); Log.e("mqtt", exception.toString()); stateoffMqtt = "false"; Log.d("Sender", "After fail: " + stateoffMqtt); sendMessage(); text = "Not Connected"; showNotification(); } }); } catch (MqttSecurityException e) { e.printStackTrace(); } catch (MqttException e) { switch (e.getReasonCode()) { case MqttException.REASON_CODE_BROKER_UNAVAILABLE: Toast.makeText(getApplicationContext(), "Server Offline", Toast.LENGTH_SHORT).show(); break; case MqttException.REASON_CODE_CLIENT_TIMEOUT: Toast.makeText(getApplicationContext(), "Olmatix connect timed out", Toast.LENGTH_SHORT).show(); break; case MqttException.REASON_CODE_CONNECTION_LOST: Toast.makeText(getApplicationContext(), "Connection Lost", Toast.LENGTH_SHORT).show(); break; case MqttException.REASON_CODE_SERVER_CONNECT_ERROR: Log.v(TAG, "c" + e.getMessage()); Toast.makeText(getApplicationContext(), "Server connection error", Toast.LENGTH_SHORT).show(); e.printStackTrace(); break; case MqttException.REASON_CODE_FAILED_AUTHENTICATION: Intent i = new Intent("RAISEALLARM"); i.putExtra("ALLARM", e); Log.e(TAG, "b" + e.getMessage()); Toast.makeText(getApplicationContext(), "Failed wrong auth (bad user name or password", Toast.LENGTH_SHORT).show(); break; default: Log.e(TAG, "a" + e.getMessage()); Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); text = "Disconnected"; showNotification(); } } } } private void sendMessage() { Intent intent = new Intent("MQTTStatus"); intent.putExtra("MQTT State", stateoffMqtt); intent.putExtra("NotifyChangeNode", mChange); LocalBroadcastManager.getInstance(this).sendBroadcast(intent); } private void sendMessageDetail() { Intent intent = new Intent("MQTTStatusDetail"); intent.putExtra("ServerConn", stateoffMqtt); intent.putExtra("NotifyChangeDetail", mChange); intent.putExtra("distance", Distance); LocalBroadcastManager.getInstance(this).sendBroadcast(intent); } public String getThread() { return Long.valueOf(thread.getId()).toString(); } @Override public void onDestroy() { // Cancel the persistent notification. // Tell the user we stopped. doDisconnect(); Toast.makeText(this, R.string.service_stop, Toast.LENGTH_SHORT).show(); messageReceive.clear(); message_topic.clear(); data.clear(); super.onDestroy(); } @Override public IBinder onBind(Intent intent) { Log.i(TAG, "onBind called"); return null; } private void addNode() { String[] outputDevices = TopicID.split("/"); NodeID = outputDevices[1]; String mNodeIdSplit = mNodeID; mNodeIdSplit = mNodeIdSplit.substring(mNodeIdSplit.indexOf("$") + 1, mNodeIdSplit.length()); messageReceive.put(mNodeIdSplit, mMessage); checkValidation(); } private void checkValidation() { if (flagNode) { if (messageReceive.containsKey("online")) { Log.d("CheckValid online", "Passed"); if (mMessage.equals("true")) { Log.d("CheckValid online", " true Passed"); saveFirst(); } else { Toast.makeText(getApplicationContext(), R.string.deviceoffline, Toast.LENGTH_SHORT).show(); doUnsubscribe(); } } flagNode = false; } else { saveDatabase(); } } private void saveFirst() { if (mDbNodeRepo.getNodeList().isEmpty()) { installedNodeModel.setNodesID(NodeID); installedNodeModel.setNodes(messageReceive.get("online")); Calendar now = Calendar.getInstance(); now.setTime(new Date()); now.getTimeInMillis(); installedNodeModel.setAdding(now.getTimeInMillis()); mDbNodeRepo.insertDb(installedNodeModel); Toast.makeText(getApplicationContext(), "Add Node Successfully", Toast.LENGTH_SHORT).show(); Log.d("saveFirst", "Add Node success, "); doSub(); } else { installedNodeModel.setNodesID(NodeID); if (mDbNodeRepo.hasObject(installedNodeModel)) { Toast.makeText(getApplicationContext(), "Checking this Node ID : " + NodeID + ", its exist, we are updating Node status", Toast.LENGTH_SHORT).show(); Log.d("saveFirst", "You already have this Node, DB = " + NodeID + ", Exist, we are updating Node status"); saveDatabase(); } else { installedNodeModel.setNodesID(NodeID); installedNodeModel.setNodes(messageReceive.get("online")); Calendar now = Calendar.getInstance(); now.setTime(new Date()); now.getTimeInMillis(); installedNodeModel.setAdding(now.getTimeInMillis()); mDbNodeRepo.insertDb(installedNodeModel); Toast.makeText(getApplicationContext(), "Successfully Add Node", Toast.LENGTH_SHORT).show(); Log.d("saveFirst", "Add Node success, "); doSub(); } } } private void doSub() { for (int a = 0; a < 4; a++) { if (a == 0) { topic = "devices/" + NodeID + "/$fwname"; } if (a == 1) { topic = "devices/" + NodeID + "/$signal"; } if (a == 2) { topic = "devices/" + NodeID + "/$uptime"; } if (a == 3) { topic = "devices/" + NodeID + "/$localip"; } int qos = 2; try { IMqttToken subToken = Connection.getClient().subscribe(topic, qos); subToken.setActionCallback(new IMqttActionListener() { @Override public void onSuccess(IMqttToken asyncActionToken) { Log.d("SubscribeNode", " device = " + mNodeID); } @Override public void onFailure(IMqttToken asyncActionToken, Throwable exception) { } }); } catch (MqttException e) { e.printStackTrace(); } } messageReceive.clear(); } private void printForegroundTask() { //String currentApp = "NULL"; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { UsageStatsManager usm = (UsageStatsManager) this.getSystemService(Context.USAGE_STATS_SERVICE); long time = System.currentTimeMillis(); List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time); if (appList != null && appList.size() > 0) { SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>(); for (UsageStats usageStats : appList) { mySortedMap.put(usageStats.getLastTimeUsed(), usageStats); } if (mySortedMap != null && !mySortedMap.isEmpty()) { currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName(); } } } else { ActivityManager am = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> tasks = am.getRunningAppProcesses(); currentApp = tasks.get(0).processName; } //Log.e(TAG, "Current App in foreground is: " + currentApp); } private void toastAndNotif() { int id = Integer.parseInt(NodeID.replaceAll("[\\D]", "")); int ch = Integer.parseInt(Channel.replaceAll("[\\D]", "")); int notid = id + ch; printForegroundTask(); //checkActivityForeground(); if (!currentApp.equals("com.olmatix.lesjaw.olmatix")) { if (flagSub) { String state = ""; detailNodeModel.setNode_id(NodeID); detailNodeModel.setChannel(Channel); data1.addAll(mDbNodeRepo.getNodeDetail(NodeID, Channel)); int countDB = mDbNodeRepo.getNodeDetail(NodeID, Channel).size(); if (countDB != 0) { for (int i = 0; i < countDB; i++) { if (data1.get(i).getNice_name_d() != null) { mNiceName = data1.get(i).getNice_name_d(); } else { mNiceName = data1.get(i).getName(); } state = data1.get(i).getStatus(); } } if (state.equals("true") || state.equals("ON")) { state = "ON"; } if (state.equals("false") || state.equals("OFF")) { state = "OFF"; } if (mNiceName != null) { if (!state.equals("")) { // Toast.makeText(getApplicationContext(), mNiceName + " is " + state, Toast.LENGTH_SHORT).show(); titleNode = mNiceName; textNode = state; //notifyID = notid; notifyID = 0; showNotificationNode(); } } messageReceive.clear(); message_topic.clear(); data1.clear(); } } } protected void checkActivityForeground() { //Log.d(TAG, "start checking for Activity in foreground"); Intent intent = new Intent(); intent.setAction(DetailNode.UE_ACTION); sendOrderedBroadcast(intent, null, new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int result = getResultCode(); if (result != Activity.RESULT_CANCELED) { // Activity caught it //Log.d(TAG, "An activity caught the broadcast, result " + result); activityInForeground(); return; } //Log.d(TAG, "No activity did catch the broadcast."); noActivityInForeground(); } }, null, Activity.RESULT_CANCELED, null, null); } protected void activityInForeground() { // TODO something you want to happen when an Activity is in the foreground flagSub = true; } protected void noActivityInForeground() { // TODO something you want to happen when no Activity is in the foreground flagSub = false; //stopSelf(); // quit } private void updateSensorDoor() { if (!mNodeID.contains("light")) { detailNodeModel.setNode_id(NodeIDSensor); detailNodeModel.setChannel("0"); detailNodeModel.setStatus_sensor(mMessage); mDbNodeRepo.update_detailSensor(detailNodeModel); mChange = "2"; sendMessageDetail(); } } private void updateSensorTheft() { if (!mNodeID.contains("light")) { detailNodeModel.setNode_id(NodeIDSensor); detailNodeModel.setChannel("0"); detailNodeModel.setStatus_theft(mMessage); mDbNodeRepo.update_detailSensor(detailNodeModel); mChange = "2"; sendMessageDetail(); data1.addAll(mDbNodeRepo.getNodeDetail(NodeIDSensor, "0")); int countDB = mDbNodeRepo.getNodeDetail(NodeIDSensor, "0").size(); if (countDB != 0) { for (int i = 0; i < countDB; i++) { if (data1.get(i).getNice_name_d() != null) { mNiceName = data1.get(i).getNice_name_d(); } else { mNiceName = data1.get(i).getName(); } } } if (mMessage.equals("true")) { titleNode = mNiceName; textNode = "ALARM!!"; showNotificationNode(); } data1.clear(); } } private void updateDetail() { String[] outputDevices = TopicID.split("/"); NodeID = outputDevices[1]; Channel = outputDevices[3]; message_topic.put(Channel, mMessage); saveDatabase_Detail(); toastAndNotif(); } private void addNodeDetail() { if (installedNodeModel.getFwName() != null) { if (installedNodeModel.getFwName().equals("smartfitting")) { detailNodeModel.setNode_id(NodeID); detailNodeModel.setChannel("0"); if (mDbNodeRepo.hasDetailObject(detailNodeModel)) { saveDatabase_Detail(); } else { detailNodeModel.setNode_id(NodeID); detailNodeModel.setChannel("0"); detailNodeModel.setStatus("false"); detailNodeModel.setNice_name_d(NodeID); detailNodeModel.setSensor("light"); mDbNodeRepo.insertInstalledNode(detailNodeModel); durationModel.setNodeId(NodeID); durationModel.setChannel("0"); durationModel.setStatus("false"); durationModel.setTimeStampOn((long) 0); durationModel.setDuration((long) 0); mDbNodeRepo.insertDurationNode(durationModel); topic1 = "devices/" + NodeID + "/light/0"; int qos = 2; try { IMqttToken subToken = Connection.getClient().subscribe(topic1, qos); subToken.setActionCallback(new IMqttActionListener() { @Override public void onSuccess(IMqttToken asyncActionToken) { Log.d("SubscribeButton", " device = " + NodeID); } @Override public void onFailure(IMqttToken asyncActionToken, Throwable exception) { } }); } catch (MqttException e) { e.printStackTrace(); } } } else if (installedNodeModel.getFwName().equals("smartadapter4ch")) { detailNodeModel.setNode_id(NodeID); detailNodeModel.setChannel("0"); if (mDbNodeRepo.hasDetailObject(detailNodeModel)) { saveDatabase_Detail(); } else { for (int i = 0; i < 4; i++) { String a = String.valueOf(i); detailNodeModel.setNode_id(NodeID); detailNodeModel.setChannel(String.valueOf(i)); detailNodeModel.setStatus("false"); detailNodeModel.setNice_name_d(NodeID + " Ch " + String.valueOf(i + 1)); detailNodeModel.setSensor("light"); mDbNodeRepo.insertInstalledNode(detailNodeModel); durationModel.setNodeId(NodeID); durationModel.setChannel(String.valueOf(i)); durationModel.setStatus("false"); durationModel.setTimeStampOn((long) 0); //durationModel.setTimeStampOff((long) 0); durationModel.setDuration((long) 0); mDbNodeRepo.insertDurationNode(durationModel); topic1 = "devices/" + NodeID + "/light/" + i; int qos = 2; try { IMqttToken subToken = Connection.getClient().subscribe(topic1, qos); subToken.setActionCallback(new IMqttActionListener() { @Override public void onSuccess(IMqttToken asyncActionToken) { Log.d("SubscribeButton", " device = " + NodeID); } @Override public void onFailure(IMqttToken asyncActionToken, Throwable exception) { } }); } catch (MqttException e) { e.printStackTrace(); } } } } else if (installedNodeModel.getFwName().equals("smartsensordoor")) { detailNodeModel.setNode_id(NodeID); detailNodeModel.setChannel("0"); if (mDbNodeRepo.hasDetailObject(detailNodeModel)) { } else { detailNodeModel.setNode_id(NodeID); detailNodeModel.setChannel("0"); detailNodeModel.setSensor("close"); detailNodeModel.setStatus("false"); detailNodeModel.setStatus_sensor("false"); detailNodeModel.setStatus_theft("false"); detailNodeModel.setNice_name_d(NodeID); mDbNodeRepo.insertInstalledNode(detailNodeModel); durationModel.setNodeId(NodeID); durationModel.setChannel("0"); durationModel.setTimeStampOn((long) 0); durationModel.setTimeStampOff((long) 0); durationModel.setDuration((long) 0); mDbNodeRepo.insertDurationNode(durationModel); for (int a = 0; a < 3; a++) { if (a == 0) { topic1 = "devices/" + NodeID + "/light/0"; } if (a == 1) { topic1 = "devices/" + NodeID + "/door/close"; } if (a == 2) { topic1 = "devices/" + NodeID + "/door/theft"; } int qos = 2; try { IMqttToken subToken = Connection.getClient().subscribe(topic1, qos); subToken.setActionCallback(new IMqttActionListener() { @Override public void onSuccess(IMqttToken asyncActionToken) { Log.d("SubscribeSensor", " device = " + mNodeID); } @Override public void onFailure(IMqttToken asyncActionToken, Throwable exception) { } }); } catch (MqttException e) { e.printStackTrace(); } } } } } } private void saveDatabase() { installedNodeModel.setNodesID(NodeID); installedNodeModel.setNodes(messageReceive.get("nodes")); installedNodeModel.setName(messageReceive.get("name")); installedNodeModel.setLocalip(messageReceive.get("localip")); installedNodeModel.setFwName(messageReceive.get("fwname")); installedNodeModel.setFwVersion(messageReceive.get("fwversion")); if (installedNodeModel.getFwName() != null) { addNodeDetail(); } installedNodeModel.setOnline(messageReceive.get("online")); if (messageReceive.containsKey("online")) { //checkActivityForeground(); printForegroundTask(); if (!currentApp.equals("com.olmatix.lesjaw.olmatix")) { if (flagSub) { installedNodeModel.setNodesID(NodeID); data2.addAll(mDbNodeRepo.getNodeListbyNode(NodeID)); int countDB = mDbNodeRepo.getNodeListbyNode(NodeID).size(); if (countDB != 0) { for (int i = 0; i < countDB; i++) { if (data2.get(i).getNice_name_n() != null) { mNiceNameN = data2.get(i).getNice_name_n(); } else { mNiceNameN = data2.get(i).getFwName(); } int id = Integer.parseInt(NodeID.replaceAll("[\\D]", "")); notifyID = id + 2; if (mMessage.equals("true")) { titleNode = mNiceNameN; textNode = "ONLINE"; showNotificationNode(); } else { titleNode = mNiceNameN; textNode = "OFFLINE"; showNotificationNode(); } } } } data2.clear(); } } installedNodeModel.setSignal(messageReceive.get("signal")); installedNodeModel.setUptime(messageReceive.get("uptime")); if (messageReceive.containsKey("uptime")) { if (mMessage != null) { installedNodeModel.setOnline("true"); } } Calendar now = Calendar.getInstance(); now.setTime(new Date()); now.getTimeInMillis(); installedNodeModel.setAdding(now.getTimeInMillis()); mDbNodeRepo.update(installedNodeModel); messageReceive.clear(); data.clear(); mChange = "2"; sendMessage(); } private void saveDatabase_Detail() { if (!mNodeID.contains("door")) { detailNodeModel.setNode_id(NodeID); detailNodeModel.setChannel(Channel); if (mMessage.equals("true")) { detailNodeModel.setStatus(mMessage); saveOnTime(); } else if (mMessage.equals("false")) { detailNodeModel.setStatus(mMessage); saveOffTime(); } mDbNodeRepo.update_detail(detailNodeModel); mChange = "2"; sendMessageDetail(); data1.clear(); } } private void saveOnTime() { new Handler().post(new Runnable() { @Override public void run() { //Log.d(TAG, "run ON: "+Channel); durationModel.setNodeId(NodeID); durationModel.setChannel(Channel); durationModel.setStatus(mMessage); Calendar now = Calendar.getInstance(); now.setTime(new Date()); now.getTimeInMillis(); durationModel.setTimeStampOn(now.getTimeInMillis()); durationModel.setTimeStampOff(Long.valueOf("0")); mDbNodeRepo.insertDurationNode(durationModel); } }); } private void saveOffTime() { new Handler().post(new Runnable() { @Override public void run() { //Log.d(TAG, "run OFF: "+Channel); durationModel.setNodeId(NodeID); durationModel.setChannel(Channel); durationModel.setStatus(mMessage); Calendar now = Calendar.getInstance(); now.setTime(new Date()); now.getTimeInMillis(); durationModel.setTimeStampOff(now.getTimeInMillis()); if(durationModel.getTimeStampOn()!=null) { //Log.d(TAG, "run: " + Long.valueOf(durationModel.getTimeStampOn())); durationModel.setDuration((now.getTimeInMillis() - durationModel.getTimeStampOn())/1000); } mDbNodeRepo.updateOff(durationModel); } }); } private void doAddNodeSub() { String topic = "devices/" + add_NodeID + "/$online"; int qos = 2; try { IMqttToken subToken = Connection.getClient().subscribe(topic, qos); subToken.setActionCallback(new IMqttActionListener() { @Override public void onSuccess(IMqttToken asyncActionToken) { Log.d("Subscribe", " device = " + NodeID); } @Override public void onFailure(IMqttToken asyncActionToken, Throwable exception) { } }); } catch (MqttException e) { e.printStackTrace(); } flagNode = true; } private void doUnsubscribe() { String topic = "devices/" + NodeID + "/$online"; try { Connection.getClient().unsubscribe(topic); Log.d("Unsubscribe", " device = " + NodeID); } catch (MqttException e) { e.printStackTrace(); } } private void doSubAll() { int countDB = mDbNodeRepo.getNodeList().size(); Log.d("DEBUG", "Count list Node: " + countDB); data.addAll(mDbNodeRepo.getNodeList()); if (countDB != 0) { for (int i = 0; i < countDB; i++) { final String mNodeID = data.get(i).getNodesID(); Log.d("DEBUG", "Count list: " + mNodeID); for (int a = 0; a < 5; a++) { if (a == 0) { topic = "devices/" + mNodeID + "/$online"; } if (a == 1) { topic = "devices/" + mNodeID + "/$fwname"; } if (a == 2) { topic = "devices/" + mNodeID + "/$signal"; } if (a == 3) { topic = "devices/" + mNodeID + "/$uptime"; } if (a == 4) { topic = "devices/" + mNodeID + "/$localip"; } int qos = 2; try { IMqttToken subToken = Connection.getClient().subscribe(topic, qos); subToken.setActionCallback(new IMqttActionListener() { @Override public void onSuccess(IMqttToken asyncActionToken) { Log.d("SubscribeNode", " device = " + mNodeID); } @Override public void onFailure(IMqttToken asyncActionToken, Throwable exception) { } }); } catch (MqttException e) { e.printStackTrace(); } } } data.clear(); doSubAllDetail(); } } private void doSubAllDetail() { int countDB = mDbNodeRepo.getNodeDetailList().size(); Log.d("DEBUG", "Count list Detail: " + countDB); data1.addAll(mDbNodeRepo.getNodeDetailList()); countDB = mDbNodeRepo.getNodeDetailList().size(); if (countDB != 0) { for (int i = 0; i < countDB; i++) { final String mNodeID = data1.get(i).getNode_id(); final String mChannel = data1.get(i).getChannel(); topic1 = "devices/" + mNodeID + "/light/" + mChannel; int qos = 2; try { IMqttToken subToken = Connection.getClient().subscribe(topic1, qos); subToken.setActionCallback(new IMqttActionListener() { @Override public void onSuccess(IMqttToken asyncActionToken) { Log.d("SubscribeButton", " device = " + mNodeID); } @Override public void onFailure(IMqttToken asyncActionToken, Throwable exception) { } }); } catch (MqttException e) { e.printStackTrace(); } } doAllsubDetailSensor(); } data1.clear(); } private void doAllsubDetailSensor() { int countDB = mDbNodeRepo.getNodeDetailList().size(); Log.d("DEBUG", "Count list Sensor: " + countDB); data1.addAll(mDbNodeRepo.getNodeDetailList()); countDB = mDbNodeRepo.getNodeDetailList().size(); if (countDB != 0) { for (int i = 0; i < countDB; i++) { final String mNodeID1 = data1.get(i).getNode_id(); final String mSensorT = data1.get(i).getSensor(); Log.d("DEBUG", "Count list Sensor: " + mSensorT); if (mSensorT != null && mSensorT.equals("close")) { for (int a = 0; a < 2; a++) { if (a == 0) { topic1 = "devices/" + mNodeID1 + "/door/close"; } if (a == 1) { topic1 = "devices/" + mNodeID1 + "/door/theft"; } int qos = 2; try { IMqttToken subToken = Connection.getClient().subscribe(topic1, qos); subToken.setActionCallback(new IMqttActionListener() { @Override public void onSuccess(IMqttToken asyncActionToken) { Log.d("SubscribeSensor", " device = " + mNodeID); } @Override public void onFailure(IMqttToken asyncActionToken, Throwable exception) { } }); } catch (MqttException e) { e.printStackTrace(); } } } } flagSub = false; setFlagSub(); data1.clear(); } } public class OlmatixBinder extends Binder { public OlmatixService getService() { return OlmatixService.this; } } private class MqttEventCallback implements MqttCallback { @Override public void connectionLost(Throwable cause) { } @Override public void messageArrived(String topic, final MqttMessage message) throws Exception { Log.d("Receive MQTTMessage", " = " + topic + " message = " + message.toString()); TopicID = topic; mNodeID = topic; mMessage = message.toString(); String[] outputDevices = TopicID.split("/"); NodeIDSensor = outputDevices[1]; if (mNodeID.contains("$")) { addNode(); } else if (mNodeID.contains("close")) { updateSensorDoor(); } else if (mNodeID.contains("theft")) { updateSensorTheft(); } else { updateDetail(); } if (flagSub) { dbnode.setTopic(topic); dbnode.setMessage(mMessage); mDbNodeRepo.insertDbMqtt(dbnode); } } @Override public void deliveryComplete(IMqttDeliveryToken token) { } } public class MyLocationListener implements LocationListener { public void onLocationChanged(final Location mLocation) { Log.i("*****************", "Location changed"); if(isBetterLocation(mLocation, previousBestLocation)) { final double lat = (mLocation.getLatitude()); final double lng = (mLocation.getLongitude()); if (lat!=0 && lng!=0) { new Thread(new Runnable() { @Override public void run() { final Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault()); try { List<Address> list; list = geocoder.getFromLocation(lat, lng, 1); if (list != null && list.size() > 0) { Address address = list.get(0); loc = address.getLocality(); if (address.getAddressLine(0) != null) adString = ", " + address.getAddressLine(0); } } catch (final IOException e) { ((MainActivity) getApplicationContext()).runOnUiThread(new Runnable() { @Override public void run() { Log.e("DEBUG", "Geocoder ERROR", e); } }); loc = OlmatixUtils.gpsDecimalFormat.format(lat) + " : " + OlmatixUtils.gpsDecimalFormat.format(lng); } final float[] res = new float[3]; final PreferenceHelper mPrefHelper = new PreferenceHelper(getApplicationContext()); Location.distanceBetween(lat, lng, mPrefHelper.getHomeLatitude(), mPrefHelper.getHomeLongitude(), res); if (mPrefHelper.getHomeLatitude() != 0) { String unit = " m"; if (res[0] > 2000) {// uuse km unit = " km"; res[0] = res[0] / 1000; } Distance = loc +", it's "+ (int) res[0] + unit ; Log.d("DEBUG", "Distance SERVICE 1: " + Distance); titleNode = "Current Location is "; textNode = Distance + " from home"; notifyID = 5; showNotificationLoc(); sendMessageDetail(); } } }).start(); } } } public void onProviderDisabled(String provider) { Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show(); } public void onProviderEnabled(String provider) { Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show(); } public void onStatusChanged(String provider, int status, Bundle extras) { } } protected boolean isBetterLocation(Location location, Location currentBestLocation) { if (currentBestLocation == null) { // A new location is always better than no location return true; } // Check whether the new location fix is newer or older long timeDelta = location.getTime() - currentBestLocation.getTime(); boolean isSignificantlyNewer = timeDelta > TWO_MINUTES; boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES; boolean isNewer = timeDelta > 0; // If it's been more than two minutes since the current location, use the new location // because the user has likely moved if (isSignificantlyNewer) { return true; // If the new location is more than two minutes older, it must be worse } else if (isSignificantlyOlder) { return false; } // Check whether the new location fix is more or less accurate int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy()); boolean isLessAccurate = accuracyDelta > 0; boolean isMoreAccurate = accuracyDelta < 0; boolean isSignificantlyLessAccurate = accuracyDelta > 200; // Check if the old and new location are from the same provider boolean isFromSameProvider = isSameProvider(location.getProvider(), currentBestLocation.getProvider()); // Determine location quality using a combination of timeliness and accuracy if (isMoreAccurate) { return true; } else if (isNewer && !isLessAccurate) { return true; } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) { return true; } return false; } /** Checks whether two providers are the same */ private boolean isSameProvider(String provider1, String provider2) { if (provider1 == null) { return provider2 == null; } return provider1.equals(provider2); } private void showNotificationLoc(){ PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0); // Set the info for the views that show in the notification panel. Notification notification = new Notification.Builder(this) .setSmallIcon(R.drawable.olmatixlogo) // the status icon .setTicker(textNode) // the status text .setWhen(System.currentTimeMillis()) // the time stamp .setContentTitle(getText(R.string.local_service_label_loc)) // the label of the entry .setContentText(textNode) // the contents of the entry .setContentIntent(contentIntent) // The intent to send when the entry is clicked .setAutoCancel(true) .build(); // Add as notification NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); manager.notify(5, notification); } }
olmatix/src/main/java/com/olmatix/service/OlmatixService.java
package com.olmatix.service; import android.Manifest; import android.app.Activity; import android.app.ActivityManager; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.app.TaskStackBuilder; import android.app.usage.UsageStats; import android.app.usage.UsageStatsManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.media.RingtoneManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Binder; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.preference.PreferenceManager; import android.support.v4.app.ActivityCompat; import android.support.v4.app.NotificationManagerCompat; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.NotificationCompat; import android.util.Log; import android.widget.Toast; import com.olmatix.database.dbNode; import com.olmatix.database.dbNodeRepo; import com.olmatix.helper.PreferenceHelper; import com.olmatix.lesjaw.olmatix.R; import com.olmatix.model.DetailNodeModel; import com.olmatix.model.DurationModel; import com.olmatix.model.InstalledNodeModel; import com.olmatix.ui.activity.MainActivity; import com.olmatix.ui.fragment.DetailNode; import com.olmatix.utils.Connection; import com.olmatix.utils.OlmatixUtils; import org.eclipse.paho.android.service.MqttAndroidClient; import org.eclipse.paho.client.mqttv3.IMqttActionListener; import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.IMqttToken; import org.eclipse.paho.client.mqttv3.MqttAsyncClient; import org.eclipse.paho.client.mqttv3.MqttCallback; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.MqttSecurityException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.SortedMap; import java.util.TreeMap; /** * Created : Rahman on 12/2/2016. * Date Created : 12/2/2016 / 4:29 PM. * =================================================== * Package : com.olmatix.service. * Project Name : Olmatix. * Copyright : Copyright @ 2016 Indogamers. */ public class OlmatixService extends Service { public final static String MY_ACTION = "MY_ACTION"; public static dbNodeRepo mDbNodeRepo; private static String TAG = OlmatixService.class.getSimpleName(); private static boolean hasWifi = false; private static boolean hasMmobile = false; private static ArrayList<InstalledNodeModel> data; public volatile MqttAndroidClient mqttClient; HashMap<String, String> messageReceive = new HashMap<>(); HashMap<String, String> message_topic = new HashMap<>(); CharSequence text; CharSequence textNode; CharSequence titleNode; String[] textLoc; ArrayList<DetailNodeModel> data1; ArrayList<InstalledNodeModel> data2; String add_NodeID; boolean flagSub = true; boolean flagNode = false; boolean flagConn = true; boolean connSuccess = false; int notifyID = 0; String currentApp = "NULL"; String topic; String topic1; private Thread thread; private ConnectivityManager mConnMan; private String deviceId; private String stateoffMqtt = "false"; private InstalledNodeModel installedNodeModel; private DetailNodeModel detailNodeModel; private DurationModel durationModel; private dbNode dbnode; private String NodeID, Channel; private String mMessage; private NotificationManager mNM; private int NOTIFICATION = R.string.local_service_label; private String mNodeID; private String mNiceName; private String mNiceNameN; private String NodeIDSensor; private String TopicID; private String mChange = ""; final static String GROUP_KEY_NOTIF = "group_key_notif"; private ArrayList<String> notifications; public static final String BROADCAST_ACTION = "Hello World"; private static final int TWO_MINUTES = 1000 * 60 * 5; public LocationManager locationManager; public MyLocationListener listener; public Location previousBestLocation = null; private String Distance; private String dist; String adString = ""; String loc = null; Intent intent; int counter = 0; private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { add_NodeID = intent.getStringExtra("NodeID"); Log.d("DEBUG", "onReceive: " + add_NodeID); doAddNodeSub(); } }; class OlmatixBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { boolean hasConnectivity = false; boolean hasChanged = false; NetworkInfo nInfo = mConnMan.getActiveNetworkInfo(); if (nInfo != null) { if (nInfo.getType() == ConnectivityManager.TYPE_WIFI) { hasChanged = true; hasWifi = nInfo.isConnected(); } else if (nInfo.getType() == ConnectivityManager.TYPE_MOBILE) { hasChanged = true; hasMmobile = nInfo.isConnected(); } } else { //Not Connected info String msg = getString(R.string.err_internet); Toast toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT); toast.show(); stateoffMqtt = "false"; sendMessage(); text = "Disconnected"; showNotification(); flagConn = false; } hasConnectivity = hasMmobile || hasWifi; doConnect(); Log.d(TAG, "hasConn: " + hasConnectivity + " hasChange: " + hasChanged + " - " + (mqttClient == null || !mqttClient.isConnected())); if (hasConnectivity && hasChanged && (Connection.getClient() != null || Connection.getClient().isConnected())) { flagConn = false; callDis(); Log.d(TAG, "Call Disconnect first"); } else if (!hasConnectivity) { doDisconnect(); Log.d(TAG, "Disconnecting"); } } } private void callDis() { new Handler().postDelayed(new Runnable() { @Override public void run() { if (!flagConn) { doDisconnect(); callCon(); } callCon(); } }, 1000); } private void callCon() { new Handler().postDelayed(new Runnable() { @Override public void run() { if (flagConn) { doConnect(); } } }, 1000); } private void setFlagSub() { new Handler().postDelayed(new Runnable() { @Override public void run() { flagSub = true; Log.d(TAG, "run: " + flagSub); unSubIfnotForeground(); } }, 10000); } private void doDisconnect() { Log.d(TAG, "doDisconnect()" + flagConn); if (!flagConn) { try { mqttClient.disconnect(); stateoffMqtt = "false"; sendMessage(); flagConn = true; Log.d(TAG, "doDisconnect() done"); } catch (MqttException e) { e.printStackTrace(); Log.d(TAG, "onReceive: " + String.valueOf(e.getMessage())); } } } @Override public void onCreate() { IntentFilter intent = new IntentFilter(); setClientID(); intent.addAction(ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(new OlmatixBroadcastReceiver(), new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); mConnMan = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); data = new ArrayList<>(); data1 = new ArrayList<>(); data2 = new ArrayList<>(); notifications = new ArrayList<>(); Connection.setClient(mqttClient); mDbNodeRepo = new dbNodeRepo(getApplicationContext()); installedNodeModel = new InstalledNodeModel(); detailNodeModel = new DetailNodeModel(); durationModel = new DurationModel(); // Display a notification about us starting. We put an icon in the status bar. showNotification(); LocalBroadcastManager.getInstance(this).registerReceiver( mMessageReceiver, new IntentFilter("addNode")); } @Override public int onStartCommand(Intent intent, int flags, int startId) { sendMessage(); flagConn = true; locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); listener = new MyLocationListener(); if (ActivityCompat.checkSelfPermission(getApplication(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. } NetworkInfo nInfo = mConnMan.getActiveNetworkInfo(); if (nInfo != null) { if (nInfo.getType() == ConnectivityManager.TYPE_WIFI) { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, OlmatixUtils.POSITION_UPDATE_INTERVAL, OlmatixUtils.POSITION_UPDATE_MIN_DIST, listener); } else if (nInfo.getType() == ConnectivityManager.TYPE_MOBILE) { locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, OlmatixUtils.POSITION_UPDATE_INTERVAL, OlmatixUtils.POSITION_UPDATE_MIN_DIST, listener); } } return START_STICKY; } private void unSubIfnotForeground() { printForegroundTask(); Log.d("Unsubscribe", " uptime and signal"); if (!currentApp.equals("com.olmatix.lesjaw.olmatix")) { int countDB = mDbNodeRepo.getNodeList().size(); Log.d("DEBUG", "Count list Node: " + countDB); data.addAll(mDbNodeRepo.getNodeList()); if (countDB != 0) { for (int i = 0; i < countDB; i++) { final String mNodeID1 = data.get(i).getNodesID(); Log.d("DEBUG", "Count list: " + mNodeID1); for (int a = 0; a < 2; a++) { if (a == 0) { topic = "devices/" + mNodeID1 + "/$signal"; } if (a == 1) { topic = "devices/" + mNodeID1 + "/$uptime"; } try { Connection.getClient().unsubscribe(topic); } catch (MqttException e) { e.printStackTrace(); } } Log.d("Unsubscribe", " device = " + mNodeID1); } } data.clear(); } } private void showNotification() { PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0); // Set the info for the views that show in the notification panel. NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this); mBuilder.setSmallIcon(R.drawable.olmatixsmall) // the status icon .setTicker(text) // the status text .setWhen(System.currentTimeMillis()) // the time stamp .setContentTitle(getText(R.string.local_service_label)) // the label of the entry .setContentText(text) // the contents of the entry .setContentIntent(contentIntent) // The intent to send when the entry is clicked .setOngoing(true) //.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 }) .build(); // Send the notification. mNM.notify(NOTIFICATION, mBuilder.build()); } private void showNotificationNode() { //int numMessages =0; SimpleDateFormat timeformat = new SimpleDateFormat("d MMM | hh:mm"); notifications.add(String.valueOf(titleNode) + " : "+String.valueOf(textNode)+ " at " +timeformat.format(System.currentTimeMillis())); Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this); mBuilder.setContentTitle("New Olmatix status"); mBuilder.setContentText("You've received new status."); mBuilder.setTicker("Olmatix status Alert!"); mBuilder.setAutoCancel(true); mBuilder.setWhen(System.currentTimeMillis()); //mBuilder.setNumber(++numMessages); //mBuilder.setGroup(GROUP_KEY_NOTIF); //mBuilder.setGroupSummary(true); mBuilder.setSound(defaultSoundUri); mBuilder.setSmallIcon(R.drawable.olmatixsmall); NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); inboxStyle.setBigContentTitle("Olmatix status"); for (int i=0; i < notifications.size(); i++) { inboxStyle.addLine(notifications.get(i)); } mBuilder.setStyle(inboxStyle); /* Creates an explicit intent for an Activity in your app */ Intent resultIntent = new Intent(this, MainActivity.class); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(MainActivity.class); /* Adds the Intent that starts the Activity to the top of the stack */ stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent =stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); notificationManager.notify(notifyID,mBuilder.build()); } private void setClientID() { // Context mContext; WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); WifiInfo wInfo = wifiManager.getConnectionInfo(); deviceId = "OlmatixApp-" + wInfo.getMacAddress(); if (deviceId == null) { deviceId = MqttAsyncClient.generateClientId(); } } private void doConnect() { Log.d(TAG, "Check Stateof MQTT: " + stateoffMqtt); if (!stateoffMqtt.equals("true")) { stateoffMqtt = "true"; SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this); String mServerURL = sharedPref.getString("server_address", "cloud.olmatix.com"); String mServerPort = sharedPref.getString("server_port", "1883"); String mUserName = sharedPref.getString("user_name", "olmatix1"); String mPassword = sharedPref.getString("password", "olmatix"); final Boolean mSwitch_conn = sharedPref.getBoolean("switch_conn", true); final MqttConnectOptions options = new MqttConnectOptions(); options.setUserName(mUserName); options.setPassword(mPassword.toCharArray()); mqttClient = new MqttAndroidClient(getApplicationContext(), "tcp://" + mServerURL + ":" + mServerPort, deviceId); if (mSwitch_conn) { options.setCleanSession(false); } else { options.setCleanSession(true); } String topic = "status/" + deviceId + "/$online"; byte[] payload = "false".getBytes(); options.setWill(topic, payload, 1, true); options.setKeepAliveInterval(300); Connection.setClient(mqttClient); text = "Connecting to server.."; showNotification(); Log.d(TAG, "doConnect: " + deviceId); try { IMqttToken token = mqttClient.connect(options); token.setActionCallback(new IMqttActionListener() { @Override public void onSuccess(IMqttToken asyncActionToken) { text = "Connected"; showNotification(); stateoffMqtt = "true"; sendMessage(); mqttClient.setCallback(new MqttEventCallback()); try { String topic = "status/" + deviceId + "/$online"; String payload = "true"; byte[] encodedPayload = new byte[0]; try { encodedPayload = payload.getBytes("UTF-8"); MqttMessage message = new MqttMessage(encodedPayload); message.setQos(1); message.setRetained(true); Connection.getClient().publish(topic, message); } catch (UnsupportedEncodingException | MqttException e) { e.printStackTrace(); } Connection.getClient().subscribe("test", 0, getApplicationContext(), new IMqttActionListener() { @Override public void onSuccess(IMqttToken asyncActionToken) { text = "Connected"; showNotification(); stateoffMqtt = "true"; sendMessage(); Log.d(TAG, "Check FlasgConn: " + flagConn); if (flagConn) { if (stateoffMqtt.equals("true")) { if (!mSwitch_conn) { doSubAll(); } } } else { //Log.d(TAG, "Call Disconn: " + flagConn); callDis(); } } @Override public void onFailure(IMqttToken asyncActionToken, Throwable exception) { //Toast.makeText(getApplicationContext(), R.string.sub_fail, Toast.LENGTH_SHORT).show(); Log.e("error", exception.toString()); } }); } catch (MqttException e) { e.printStackTrace(); } } @Override public void onFailure(IMqttToken asyncActionToken, Throwable exception) { //Toast.makeText(getApplicationContext(), R.string.conn_fail+exception.toString(), Toast.LENGTH_SHORT).show(); Log.e("mqtt", exception.toString()); stateoffMqtt = "false"; Log.d("Sender", "After fail: " + stateoffMqtt); sendMessage(); text = "Not Connected"; showNotification(); } }); } catch (MqttSecurityException e) { e.printStackTrace(); } catch (MqttException e) { switch (e.getReasonCode()) { case MqttException.REASON_CODE_BROKER_UNAVAILABLE: Toast.makeText(getApplicationContext(), "Server Offline", Toast.LENGTH_SHORT).show(); break; case MqttException.REASON_CODE_CLIENT_TIMEOUT: Toast.makeText(getApplicationContext(), "Olmatix connect timed out", Toast.LENGTH_SHORT).show(); break; case MqttException.REASON_CODE_CONNECTION_LOST: Toast.makeText(getApplicationContext(), "Connection Lost", Toast.LENGTH_SHORT).show(); break; case MqttException.REASON_CODE_SERVER_CONNECT_ERROR: Log.v(TAG, "c" + e.getMessage()); Toast.makeText(getApplicationContext(), "Server connection error", Toast.LENGTH_SHORT).show(); e.printStackTrace(); break; case MqttException.REASON_CODE_FAILED_AUTHENTICATION: Intent i = new Intent("RAISEALLARM"); i.putExtra("ALLARM", e); Log.e(TAG, "b" + e.getMessage()); Toast.makeText(getApplicationContext(), "Failed wrong auth (bad user name or password", Toast.LENGTH_SHORT).show(); break; default: Log.e(TAG, "a" + e.getMessage()); Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); text = "Disconnected"; showNotification(); } } } } private void sendMessage() { Intent intent = new Intent("MQTTStatus"); intent.putExtra("MQTT State", stateoffMqtt); intent.putExtra("NotifyChangeNode", mChange); LocalBroadcastManager.getInstance(this).sendBroadcast(intent); } private void sendMessageDetail() { Intent intent = new Intent("MQTTStatusDetail"); intent.putExtra("ServerConn", stateoffMqtt); intent.putExtra("NotifyChangeDetail", mChange); intent.putExtra("distance", Distance); LocalBroadcastManager.getInstance(this).sendBroadcast(intent); } public String getThread() { return Long.valueOf(thread.getId()).toString(); } @Override public void onDestroy() { // Cancel the persistent notification. // Tell the user we stopped. doDisconnect(); Toast.makeText(this, R.string.service_stop, Toast.LENGTH_SHORT).show(); messageReceive.clear(); message_topic.clear(); data.clear(); super.onDestroy(); } @Override public IBinder onBind(Intent intent) { Log.i(TAG, "onBind called"); return null; } private void addNode() { String[] outputDevices = TopicID.split("/"); NodeID = outputDevices[1]; String mNodeIdSplit = mNodeID; mNodeIdSplit = mNodeIdSplit.substring(mNodeIdSplit.indexOf("$") + 1, mNodeIdSplit.length()); messageReceive.put(mNodeIdSplit, mMessage); checkValidation(); } private void checkValidation() { if (flagNode) { if (messageReceive.containsKey("online")) { Log.d("CheckValid online", "Passed"); if (mMessage.equals("true")) { Log.d("CheckValid online", " true Passed"); saveFirst(); } else { Toast.makeText(getApplicationContext(), R.string.deviceoffline, Toast.LENGTH_SHORT).show(); doUnsubscribe(); } } flagNode = false; } else { saveDatabase(); } } private void saveFirst() { if (mDbNodeRepo.getNodeList().isEmpty()) { installedNodeModel.setNodesID(NodeID); installedNodeModel.setNodes(messageReceive.get("online")); Calendar now = Calendar.getInstance(); now.setTime(new Date()); now.getTimeInMillis(); installedNodeModel.setAdding(now.getTimeInMillis()); mDbNodeRepo.insertDb(installedNodeModel); Toast.makeText(getApplicationContext(), "Add Node Successfully", Toast.LENGTH_SHORT).show(); Log.d("saveFirst", "Add Node success, "); doSub(); } else { installedNodeModel.setNodesID(NodeID); if (mDbNodeRepo.hasObject(installedNodeModel)) { Toast.makeText(getApplicationContext(), "Checking this Node ID : " + NodeID + ", its exist, we are updating Node status", Toast.LENGTH_SHORT).show(); Log.d("saveFirst", "You already have this Node, DB = " + NodeID + ", Exist, we are updating Node status"); saveDatabase(); } else { installedNodeModel.setNodesID(NodeID); installedNodeModel.setNodes(messageReceive.get("online")); Calendar now = Calendar.getInstance(); now.setTime(new Date()); now.getTimeInMillis(); installedNodeModel.setAdding(now.getTimeInMillis()); mDbNodeRepo.insertDb(installedNodeModel); Toast.makeText(getApplicationContext(), "Successfully Add Node", Toast.LENGTH_SHORT).show(); Log.d("saveFirst", "Add Node success, "); doSub(); } } } private void doSub() { for (int a = 0; a < 4; a++) { if (a == 0) { topic = "devices/" + NodeID + "/$fwname"; } if (a == 1) { topic = "devices/" + NodeID + "/$signal"; } if (a == 2) { topic = "devices/" + NodeID + "/$uptime"; } if (a == 3) { topic = "devices/" + NodeID + "/$localip"; } int qos = 2; try { IMqttToken subToken = Connection.getClient().subscribe(topic, qos); subToken.setActionCallback(new IMqttActionListener() { @Override public void onSuccess(IMqttToken asyncActionToken) { Log.d("SubscribeNode", " device = " + mNodeID); } @Override public void onFailure(IMqttToken asyncActionToken, Throwable exception) { } }); } catch (MqttException e) { e.printStackTrace(); } } messageReceive.clear(); } private void printForegroundTask() { //String currentApp = "NULL"; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { UsageStatsManager usm = (UsageStatsManager) this.getSystemService(Context.USAGE_STATS_SERVICE); long time = System.currentTimeMillis(); List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time); if (appList != null && appList.size() > 0) { SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>(); for (UsageStats usageStats : appList) { mySortedMap.put(usageStats.getLastTimeUsed(), usageStats); } if (mySortedMap != null && !mySortedMap.isEmpty()) { currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName(); } } } else { ActivityManager am = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> tasks = am.getRunningAppProcesses(); currentApp = tasks.get(0).processName; } //Log.e(TAG, "Current App in foreground is: " + currentApp); } private void toastAndNotif() { int id = Integer.parseInt(NodeID.replaceAll("[\\D]", "")); int ch = Integer.parseInt(Channel.replaceAll("[\\D]", "")); int notid = id + ch; printForegroundTask(); //checkActivityForeground(); if (!currentApp.equals("com.olmatix.lesjaw.olmatix")) { if (flagSub) { String state = ""; detailNodeModel.setNode_id(NodeID); detailNodeModel.setChannel(Channel); data1.addAll(mDbNodeRepo.getNodeDetail(NodeID, Channel)); int countDB = mDbNodeRepo.getNodeDetail(NodeID, Channel).size(); if (countDB != 0) { for (int i = 0; i < countDB; i++) { if (data1.get(i).getNice_name_d() != null) { mNiceName = data1.get(i).getNice_name_d(); } else { mNiceName = data1.get(i).getName(); } state = data1.get(i).getStatus(); } } if (state.equals("true") || state.equals("ON")) { state = "ON"; } if (state.equals("false") || state.equals("OFF")) { state = "OFF"; } if (mNiceName != null) { if (!state.equals("")) { // Toast.makeText(getApplicationContext(), mNiceName + " is " + state, Toast.LENGTH_SHORT).show(); titleNode = mNiceName; textNode = state; //notifyID = notid; notifyID = 0; showNotificationNode(); } } messageReceive.clear(); message_topic.clear(); data1.clear(); } } } protected void checkActivityForeground() { //Log.d(TAG, "start checking for Activity in foreground"); Intent intent = new Intent(); intent.setAction(DetailNode.UE_ACTION); sendOrderedBroadcast(intent, null, new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int result = getResultCode(); if (result != Activity.RESULT_CANCELED) { // Activity caught it //Log.d(TAG, "An activity caught the broadcast, result " + result); activityInForeground(); return; } //Log.d(TAG, "No activity did catch the broadcast."); noActivityInForeground(); } }, null, Activity.RESULT_CANCELED, null, null); } protected void activityInForeground() { // TODO something you want to happen when an Activity is in the foreground flagSub = true; } protected void noActivityInForeground() { // TODO something you want to happen when no Activity is in the foreground flagSub = false; //stopSelf(); // quit } private void updateSensorDoor() { if (!mNodeID.contains("light")) { detailNodeModel.setNode_id(NodeIDSensor); detailNodeModel.setChannel("0"); detailNodeModel.setStatus_sensor(mMessage); mDbNodeRepo.update_detailSensor(detailNodeModel); mChange = "2"; sendMessageDetail(); } } private void updateSensorTheft() { if (!mNodeID.contains("light")) { detailNodeModel.setNode_id(NodeIDSensor); detailNodeModel.setChannel("0"); detailNodeModel.setStatus_theft(mMessage); mDbNodeRepo.update_detailSensor(detailNodeModel); mChange = "2"; sendMessageDetail(); data1.addAll(mDbNodeRepo.getNodeDetail(NodeIDSensor, "0")); int countDB = mDbNodeRepo.getNodeDetail(NodeIDSensor, "0").size(); if (countDB != 0) { for (int i = 0; i < countDB; i++) { if (data1.get(i).getNice_name_d() != null) { mNiceName = data1.get(i).getNice_name_d(); } else { mNiceName = data1.get(i).getName(); } } } if (mMessage.equals("true")) { titleNode = mNiceName; textNode = "ALARM!!"; showNotificationNode(); } data1.clear(); } } private void updateDetail() { String[] outputDevices = TopicID.split("/"); NodeID = outputDevices[1]; Channel = outputDevices[3]; message_topic.put(Channel, mMessage); saveDatabase_Detail(); toastAndNotif(); } private void addNodeDetail() { if (installedNodeModel.getFwName() != null) { if (installedNodeModel.getFwName().equals("smartfitting")) { detailNodeModel.setNode_id(NodeID); detailNodeModel.setChannel("0"); if (mDbNodeRepo.hasDetailObject(detailNodeModel)) { saveDatabase_Detail(); } else { detailNodeModel.setNode_id(NodeID); detailNodeModel.setChannel("0"); detailNodeModel.setStatus("false"); detailNodeModel.setNice_name_d(NodeID); detailNodeModel.setSensor("light"); mDbNodeRepo.insertInstalledNode(detailNodeModel); durationModel.setNodeId(NodeID); durationModel.setChannel("0"); durationModel.setStatus("false"); durationModel.setTimeStampOn((long) 0); durationModel.setDuration((long) 0); mDbNodeRepo.insertDurationNode(durationModel); topic1 = "devices/" + NodeID + "/light/0"; int qos = 2; try { IMqttToken subToken = Connection.getClient().subscribe(topic1, qos); subToken.setActionCallback(new IMqttActionListener() { @Override public void onSuccess(IMqttToken asyncActionToken) { Log.d("SubscribeButton", " device = " + NodeID); } @Override public void onFailure(IMqttToken asyncActionToken, Throwable exception) { } }); } catch (MqttException e) { e.printStackTrace(); } } } else if (installedNodeModel.getFwName().equals("smartadapter4ch")) { detailNodeModel.setNode_id(NodeID); detailNodeModel.setChannel("0"); if (mDbNodeRepo.hasDetailObject(detailNodeModel)) { saveDatabase_Detail(); } else { for (int i = 0; i < 4; i++) { String a = String.valueOf(i); detailNodeModel.setNode_id(NodeID); detailNodeModel.setChannel(String.valueOf(i)); detailNodeModel.setStatus("false"); detailNodeModel.setNice_name_d(NodeID + " Ch " + String.valueOf(i + 1)); detailNodeModel.setSensor("light"); mDbNodeRepo.insertInstalledNode(detailNodeModel); durationModel.setNodeId(NodeID); durationModel.setChannel(String.valueOf(i)); durationModel.setStatus("false"); durationModel.setTimeStampOn((long) 0); //durationModel.setTimeStampOff((long) 0); durationModel.setDuration((long) 0); mDbNodeRepo.insertDurationNode(durationModel); topic1 = "devices/" + NodeID + "/light/" + i; int qos = 2; try { IMqttToken subToken = Connection.getClient().subscribe(topic1, qos); subToken.setActionCallback(new IMqttActionListener() { @Override public void onSuccess(IMqttToken asyncActionToken) { Log.d("SubscribeButton", " device = " + NodeID); } @Override public void onFailure(IMqttToken asyncActionToken, Throwable exception) { } }); } catch (MqttException e) { e.printStackTrace(); } } } } else if (installedNodeModel.getFwName().equals("smartsensordoor")) { detailNodeModel.setNode_id(NodeID); detailNodeModel.setChannel("0"); if (mDbNodeRepo.hasDetailObject(detailNodeModel)) { } else { detailNodeModel.setNode_id(NodeID); detailNodeModel.setChannel("0"); detailNodeModel.setSensor("close"); detailNodeModel.setStatus("false"); detailNodeModel.setStatus_sensor("false"); detailNodeModel.setStatus_theft("false"); detailNodeModel.setNice_name_d(NodeID); mDbNodeRepo.insertInstalledNode(detailNodeModel); durationModel.setNodeId(NodeID); durationModel.setChannel("0"); durationModel.setTimeStampOn((long) 0); durationModel.setTimeStampOff((long) 0); durationModel.setDuration((long) 0); mDbNodeRepo.insertDurationNode(durationModel); for (int a = 0; a < 3; a++) { if (a == 0) { topic1 = "devices/" + NodeID + "/light/0"; } if (a == 1) { topic1 = "devices/" + NodeID + "/door/close"; } if (a == 2) { topic1 = "devices/" + NodeID + "/door/theft"; } int qos = 2; try { IMqttToken subToken = Connection.getClient().subscribe(topic1, qos); subToken.setActionCallback(new IMqttActionListener() { @Override public void onSuccess(IMqttToken asyncActionToken) { Log.d("SubscribeSensor", " device = " + mNodeID); } @Override public void onFailure(IMqttToken asyncActionToken, Throwable exception) { } }); } catch (MqttException e) { e.printStackTrace(); } } } } } } private void saveDatabase() { installedNodeModel.setNodesID(NodeID); installedNodeModel.setNodes(messageReceive.get("nodes")); installedNodeModel.setName(messageReceive.get("name")); installedNodeModel.setLocalip(messageReceive.get("localip")); installedNodeModel.setFwName(messageReceive.get("fwname")); installedNodeModel.setFwVersion(messageReceive.get("fwversion")); if (installedNodeModel.getFwName() != null) { addNodeDetail(); } installedNodeModel.setOnline(messageReceive.get("online")); if (messageReceive.containsKey("online")) { //checkActivityForeground(); printForegroundTask(); if (!currentApp.equals("com.olmatix.lesjaw.olmatix")) { if (flagSub) { installedNodeModel.setNodesID(NodeID); data2.addAll(mDbNodeRepo.getNodeListbyNode(NodeID)); int countDB = mDbNodeRepo.getNodeListbyNode(NodeID).size(); if (countDB != 0) { for (int i = 0; i < countDB; i++) { if (data2.get(i).getNice_name_n() != null) { mNiceNameN = data2.get(i).getNice_name_n(); } else { mNiceNameN = data2.get(i).getFwName(); } int id = Integer.parseInt(NodeID.replaceAll("[\\D]", "")); notifyID = id + 2; if (mMessage.equals("true")) { titleNode = mNiceNameN; textNode = "ONLINE"; showNotificationNode(); } else { titleNode = mNiceNameN; textNode = "OFFLINE"; showNotificationNode(); } } } } data2.clear(); } } installedNodeModel.setSignal(messageReceive.get("signal")); installedNodeModel.setUptime(messageReceive.get("uptime")); if (messageReceive.containsKey("uptime")) { if (mMessage != null) { installedNodeModel.setOnline("true"); } } Calendar now = Calendar.getInstance(); now.setTime(new Date()); now.getTimeInMillis(); installedNodeModel.setAdding(now.getTimeInMillis()); mDbNodeRepo.update(installedNodeModel); messageReceive.clear(); data.clear(); mChange = "2"; sendMessage(); } private void saveDatabase_Detail() { if (!mNodeID.contains("door")) { detailNodeModel.setNode_id(NodeID); detailNodeModel.setChannel(Channel); if (mMessage.equals("true")) { detailNodeModel.setStatus(mMessage); saveOnTime(); } else if (mMessage.equals("false")) { detailNodeModel.setStatus(mMessage); saveOffTime(); } mDbNodeRepo.update_detail(detailNodeModel); mChange = "2"; sendMessageDetail(); data1.clear(); } } private void saveOnTime() { new Handler().post(new Runnable() { @Override public void run() { //Log.d(TAG, "run ON: "+Channel); durationModel.setNodeId(NodeID); durationModel.setChannel(Channel); durationModel.setStatus(mMessage); Calendar now = Calendar.getInstance(); now.setTime(new Date()); now.getTimeInMillis(); durationModel.setTimeStampOn(now.getTimeInMillis()); durationModel.setTimeStampOff(Long.valueOf("0")); mDbNodeRepo.insertDurationNode(durationModel); } }); } private void saveOffTime() { new Handler().post(new Runnable() { @Override public void run() { //Log.d(TAG, "run OFF: "+Channel); durationModel.setNodeId(NodeID); durationModel.setChannel(Channel); durationModel.setStatus(mMessage); Calendar now = Calendar.getInstance(); now.setTime(new Date()); now.getTimeInMillis(); durationModel.setTimeStampOff(now.getTimeInMillis()); if(durationModel.getTimeStampOn()!=null) { //Log.d(TAG, "run: " + Long.valueOf(durationModel.getTimeStampOn())); durationModel.setDuration((now.getTimeInMillis() - durationModel.getTimeStampOn())/1000); } mDbNodeRepo.updateOff(durationModel); } }); } private void doAddNodeSub() { String topic = "devices/" + add_NodeID + "/$online"; int qos = 2; try { IMqttToken subToken = Connection.getClient().subscribe(topic, qos); subToken.setActionCallback(new IMqttActionListener() { @Override public void onSuccess(IMqttToken asyncActionToken) { Log.d("Subscribe", " device = " + NodeID); } @Override public void onFailure(IMqttToken asyncActionToken, Throwable exception) { } }); } catch (MqttException e) { e.printStackTrace(); } flagNode = true; } private void doUnsubscribe() { String topic = "devices/" + NodeID + "/$online"; try { Connection.getClient().unsubscribe(topic); Log.d("Unsubscribe", " device = " + NodeID); } catch (MqttException e) { e.printStackTrace(); } } private void doSubAll() { int countDB = mDbNodeRepo.getNodeList().size(); Log.d("DEBUG", "Count list Node: " + countDB); data.addAll(mDbNodeRepo.getNodeList()); if (countDB != 0) { for (int i = 0; i < countDB; i++) { final String mNodeID = data.get(i).getNodesID(); Log.d("DEBUG", "Count list: " + mNodeID); for (int a = 0; a < 5; a++) { if (a == 0) { topic = "devices/" + mNodeID + "/$online"; } if (a == 1) { topic = "devices/" + mNodeID + "/$fwname"; } if (a == 2) { topic = "devices/" + mNodeID + "/$signal"; } if (a == 3) { topic = "devices/" + mNodeID + "/$uptime"; } if (a == 4) { topic = "devices/" + mNodeID + "/$localip"; } int qos = 2; try { IMqttToken subToken = Connection.getClient().subscribe(topic, qos); subToken.setActionCallback(new IMqttActionListener() { @Override public void onSuccess(IMqttToken asyncActionToken) { Log.d("SubscribeNode", " device = " + mNodeID); } @Override public void onFailure(IMqttToken asyncActionToken, Throwable exception) { } }); } catch (MqttException e) { e.printStackTrace(); } } } data.clear(); doSubAllDetail(); } } private void doSubAllDetail() { int countDB = mDbNodeRepo.getNodeDetailList().size(); Log.d("DEBUG", "Count list Detail: " + countDB); data1.addAll(mDbNodeRepo.getNodeDetailList()); countDB = mDbNodeRepo.getNodeDetailList().size(); if (countDB != 0) { for (int i = 0; i < countDB; i++) { final String mNodeID = data1.get(i).getNode_id(); final String mChannel = data1.get(i).getChannel(); topic1 = "devices/" + mNodeID + "/light/" + mChannel; int qos = 2; try { IMqttToken subToken = Connection.getClient().subscribe(topic1, qos); subToken.setActionCallback(new IMqttActionListener() { @Override public void onSuccess(IMqttToken asyncActionToken) { Log.d("SubscribeButton", " device = " + mNodeID); } @Override public void onFailure(IMqttToken asyncActionToken, Throwable exception) { } }); } catch (MqttException e) { e.printStackTrace(); } } doAllsubDetailSensor(); } data1.clear(); } private void doAllsubDetailSensor() { int countDB = mDbNodeRepo.getNodeDetailList().size(); Log.d("DEBUG", "Count list Sensor: " + countDB); data1.addAll(mDbNodeRepo.getNodeDetailList()); countDB = mDbNodeRepo.getNodeDetailList().size(); if (countDB != 0) { for (int i = 0; i < countDB; i++) { final String mNodeID1 = data1.get(i).getNode_id(); final String mSensorT = data1.get(i).getSensor(); Log.d("DEBUG", "Count list Sensor: " + mSensorT); if (mSensorT != null && mSensorT.equals("close")) { for (int a = 0; a < 2; a++) { if (a == 0) { topic1 = "devices/" + mNodeID1 + "/door/close"; } if (a == 1) { topic1 = "devices/" + mNodeID1 + "/door/theft"; } int qos = 2; try { IMqttToken subToken = Connection.getClient().subscribe(topic1, qos); subToken.setActionCallback(new IMqttActionListener() { @Override public void onSuccess(IMqttToken asyncActionToken) { Log.d("SubscribeSensor", " device = " + mNodeID); } @Override public void onFailure(IMqttToken asyncActionToken, Throwable exception) { } }); } catch (MqttException e) { e.printStackTrace(); } } } } flagSub = false; setFlagSub(); data1.clear(); } } public class OlmatixBinder extends Binder { public OlmatixService getService() { return OlmatixService.this; } } private class MqttEventCallback implements MqttCallback { @Override public void connectionLost(Throwable cause) { } @Override public void messageArrived(String topic, final MqttMessage message) throws Exception { Log.d("Receive MQTTMessage", " = " + topic + " message = " + message.toString()); TopicID = topic; mNodeID = topic; mMessage = message.toString(); String[] outputDevices = TopicID.split("/"); NodeIDSensor = outputDevices[1]; if (mNodeID.contains("$")) { addNode(); } else if (mNodeID.contains("close")) { updateSensorDoor(); } else if (mNodeID.contains("theft")) { updateSensorTheft(); } else { updateDetail(); } if (flagSub) { dbnode.setTopic(topic); dbnode.setMessage(mMessage); mDbNodeRepo.insertDbMqtt(dbnode); } } @Override public void deliveryComplete(IMqttDeliveryToken token) { } } public class MyLocationListener implements LocationListener { public void onLocationChanged(final Location mLocation) { Log.i("*****************", "Location changed"); if(isBetterLocation(mLocation, previousBestLocation)) { final double lat = (mLocation.getLatitude()); final double lng = (mLocation.getLongitude()); if (lat!=0 && lng!=0) { new Thread(new Runnable() { @Override public void run() { final Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault()); try { List<Address> list; list = geocoder.getFromLocation(lat, lng, 1); if (list != null && list.size() > 0) { Address address = list.get(0); loc = address.getLocality(); if (address.getAddressLine(0) != null) adString = ", " + address.getAddressLine(0); } } catch (final IOException e) { ((MainActivity) getApplicationContext()).runOnUiThread(new Runnable() { @Override public void run() { Log.e("DEBUG", "Geocoder ERROR", e); } }); loc = OlmatixUtils.gpsDecimalFormat.format(lat) + " : " + OlmatixUtils.gpsDecimalFormat.format(lng); } final float[] res = new float[3]; final PreferenceHelper mPrefHelper = new PreferenceHelper(getApplicationContext()); Location.distanceBetween(lat, lng, mPrefHelper.getHomeLatitude(), mPrefHelper.getHomeLongitude(), res); if (mPrefHelper.getHomeLatitude() != 0) { String unit = " m"; if (res[0] > 2000) {// uuse km unit = " km"; res[0] = res[0] / 1000; } Distance = loc +", it's "+ (int) res[0] + unit ; } } }).start(); } Log.d("DEBUG", "Distance SERVICE 2: " + Distance); if (String.valueOf(Distance).trim().equals(null)) { } else { titleNode = "Current Location is "; textNode = Distance + " from home"; notifyID = 5; showNotificationLoc(); sendMessageDetail(); } } } public void onProviderDisabled(String provider) { Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show(); } public void onProviderEnabled(String provider) { Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show(); } public void onStatusChanged(String provider, int status, Bundle extras) { } } protected boolean isBetterLocation(Location location, Location currentBestLocation) { if (currentBestLocation == null) { // A new location is always better than no location return true; } // Check whether the new location fix is newer or older long timeDelta = location.getTime() - currentBestLocation.getTime(); boolean isSignificantlyNewer = timeDelta > TWO_MINUTES; boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES; boolean isNewer = timeDelta > 0; // If it's been more than two minutes since the current location, use the new location // because the user has likely moved if (isSignificantlyNewer) { return true; // If the new location is more than two minutes older, it must be worse } else if (isSignificantlyOlder) { return false; } // Check whether the new location fix is more or less accurate int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy()); boolean isLessAccurate = accuracyDelta > 0; boolean isMoreAccurate = accuracyDelta < 0; boolean isSignificantlyLessAccurate = accuracyDelta > 200; // Check if the old and new location are from the same provider boolean isFromSameProvider = isSameProvider(location.getProvider(), currentBestLocation.getProvider()); // Determine location quality using a combination of timeliness and accuracy if (isMoreAccurate) { return true; } else if (isNewer && !isLessAccurate) { return true; } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) { return true; } return false; } /** Checks whether two providers are the same */ private boolean isSameProvider(String provider1, String provider2) { if (provider1 == null) { return provider2 == null; } return provider1.equals(provider2); } private void showNotificationLoc(){ PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0); // Set the info for the views that show in the notification panel. Notification notification = new Notification.Builder(this) .setSmallIcon(R.drawable.olmatixlogo) // the status icon .setTicker(textNode) // the status text .setWhen(System.currentTimeMillis()) // the time stamp .setContentTitle(getText(R.string.local_service_label_loc)) // the label of the entry .setContentText(textNode) // the contents of the entry .setContentIntent(contentIntent) // The intent to send when the entry is clicked .setAutoCancel(true) .build(); // Add as notification NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); manager.notify(5, notification); } }
fix layout dashboard, fix gps location
olmatix/src/main/java/com/olmatix/service/OlmatixService.java
fix layout dashboard, fix gps location
<ide><path>lmatix/src/main/java/com/olmatix/service/OlmatixService.java <ide> private String dist; <ide> String adString = ""; <ide> String loc = null; <del> <ide> Intent intent; <ide> int counter = 0; <ide> <ide> <ide> } <ide> Distance = loc +", it's "+ (int) res[0] + unit ; <del> } <add> Log.d("DEBUG", "Distance SERVICE 1: " + Distance); <add> titleNode = "Current Location is "; <add> textNode = Distance + " from home"; <add> notifyID = 5; <add> showNotificationLoc(); <add> sendMessageDetail(); <add> <add> } <ide> } <ide> }).start(); <ide> <ide> } <del> Log.d("DEBUG", "Distance SERVICE 2: " + Distance); <del> if (String.valueOf(Distance).trim().equals(null)) { <del> <del> } else { <del> titleNode = "Current Location is "; <del> textNode = Distance + " from home"; <del> notifyID = 5; <del> showNotificationLoc(); <del> sendMessageDetail(); <del> <del> } <add> <ide> } <ide> } <ide>
Java
agpl-3.0
69005ade4ea9fb02c86c28f272050f77ca7cb93a
0
rdkgit/opennms,roskens/opennms-pre-github,aihua/opennms,rdkgit/opennms,aihua/opennms,tdefilip/opennms,rdkgit/opennms,rdkgit/opennms,aihua/opennms,tdefilip/opennms,aihua/opennms,tdefilip/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,roskens/opennms-pre-github,aihua/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,roskens/opennms-pre-github,tdefilip/opennms,tdefilip/opennms,aihua/opennms,tdefilip/opennms,aihua/opennms,rdkgit/opennms,rdkgit/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,tdefilip/opennms,rdkgit/opennms,tdefilip/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,rdkgit/opennms,tdefilip/opennms,aihua/opennms,rdkgit/opennms,rdkgit/opennms,aihua/opennms
// // This file is part of the OpenNMS(R) Application. // // OpenNMS(R) is Copyright (C) 2006 The OpenNMS Group, Inc. All rights // reserved. // OpenNMS(R) is a derivative work, containing both original code, included // code and modified // code that was published under the GNU General Public License. Copyrights // for modified // and included code are below. // // OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. // // Original code base Copyright (C) 1999-2001 Oculan Corp. All rights // reserved. // // This program 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 2 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, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // For more information contact: // OpenNMS Licensing <[email protected]> // http://www.opennms.org/ // http://www.opennms.com/ // package org.opennms.netmgt.model; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.SequenceGenerator; import javax.persistence.Table; @Entity @Table(name = "applications") public class OnmsApplication implements Comparable<OnmsApplication> { private Integer m_id; private String m_name; private Set<OnmsMonitoredService> m_memberServices; @Id @SequenceGenerator(name = "opennmsSequence", sequenceName = "opennmsNxtId") @GeneratedValue(generator = "opennmsSequence") public Integer getId() { return m_id; } public void setId(Integer id) { m_id = id; } @Column(name = "name", length=32, nullable=false, unique=true) public String getName() { return m_name; } public void setName(String name) { m_name = name; } @ManyToMany @JoinTable( name="application_service_map", joinColumns={@JoinColumn(name="appId")}, inverseJoinColumns={@JoinColumn(name="ifserviceId")} ) public Set<OnmsMonitoredService> getMemberServices() { return m_memberServices; } public void setMemberServices(Set<OnmsMonitoredService> memberServices) { m_memberServices = memberServices; } public int compareTo(OnmsApplication o) { return getName().compareToIgnoreCase(o.getName()); } }
opennms-model/src/main/java/org/opennms/netmgt/model/OnmsApplication.java
// // This file is part of the OpenNMS(R) Application. // // OpenNMS(R) is Copyright (C) 2006 The OpenNMS Group, Inc. All rights // reserved. // OpenNMS(R) is a derivative work, containing both original code, included // code and modified // code that was published under the GNU General Public License. Copyrights // for modified // and included code are below. // // OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. // // Original code base Copyright (C) 1999-2001 Oculan Corp. All rights // reserved. // // This program 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 2 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, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // For more information contact: // OpenNMS Licensing <[email protected]> // http://www.opennms.org/ // http://www.opennms.com/ // package org.opennms.netmgt.model; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.SequenceGenerator; import javax.persistence.Table; @Entity @Table(name = "applications") public class OnmsApplication { private Integer m_id; private String m_name; private Set<OnmsMonitoredService> m_memberServices; @Id @SequenceGenerator(name = "opennmsSequence", sequenceName = "opennmsNxtId") @GeneratedValue(generator = "opennmsSequence") public Integer getId() { return m_id; } public void setId(Integer id) { m_id = id; } @Column(name = "name", length=32, nullable=false, unique=true) public String getName() { return m_name; } public void setName(String name) { m_name = name; } @ManyToMany @JoinTable( name="application_service_map", joinColumns={@JoinColumn(name="appId")}, inverseJoinColumns={@JoinColumn(name="ifserviceId")} ) public Set<OnmsMonitoredService> getMemberServices() { return m_memberServices; } public void setMemberServices(Set<OnmsMonitoredService> memberServices) { m_memberServices = memberServices; } }
Implement Comparable interface
opennms-model/src/main/java/org/opennms/netmgt/model/OnmsApplication.java
Implement Comparable interface
<ide><path>pennms-model/src/main/java/org/opennms/netmgt/model/OnmsApplication.java <ide> <ide> @Entity <ide> @Table(name = "applications") <del>public class OnmsApplication { <add>public class OnmsApplication implements Comparable<OnmsApplication> { <ide> <ide> private Integer m_id; <ide> <ide> m_memberServices = memberServices; <ide> } <ide> <add> public int compareTo(OnmsApplication o) { <add> return getName().compareToIgnoreCase(o.getName()); <add> } <add> <ide> }
Java
mit
c8dbbf04215c7779cd7f8a27b3eb72359fd89e87
0
Iterable/iterable-android-sdk,Iterable/iterable-android-sdk,Iterable/iterable-android-sdk
package com.iterable.iterableapi; import android.app.Activity; import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; import android.support.annotation.VisibleForTesting; import android.support.v4.app.NotificationManagerCompat; import com.iterable.iterableapi.ddl.DeviceInfo; import com.iterable.iterableapi.ddl.MatchFpResponse; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.TimeZone; import java.util.UUID; /** * Created by David Truong [email protected] */ public class IterableApi { //region Variables //--------------------------------------------------------------------------------------- static final String TAG = "IterableApi"; /** * {@link IterableApi} singleton instance */ static volatile IterableApi sharedInstance = new IterableApi(); private Context _applicationContext; IterableConfig config; boolean sdkCompatEnabled; private String _apiKey; private String _email; private String _userId; private boolean _debugMode; private Bundle _payloadData; private IterableNotificationData _notificationData; private String _deviceId; private IterableInAppManager inAppManager; //--------------------------------------------------------------------------------------- //endregion //region Constructor //--------------------------------------------------------------------------------------- IterableApi() { config = new IterableConfig.Builder().build(); } @VisibleForTesting IterableApi(IterableInAppManager inAppManager) { config = new IterableConfig.Builder().build(); this.inAppManager = inAppManager; } //--------------------------------------------------------------------------------------- //endregion //region Getters/Setters //--------------------------------------------------------------------------------------- /** * Sets the icon to be displayed in notifications. * The icon name should match the resource name stored in the /res/drawable directory. * @param iconName */ public void setNotificationIcon(String iconName) { setNotificationIcon(_applicationContext, iconName); } /** * Retrieves the payload string for a given key. * Used for deeplinking and retrieving extra data passed down along with a campaign. * @param key * @return Returns the requested payload data from the current push campaign if it exists. */ public String getPayloadData(String key) { return (_payloadData != null) ? _payloadData.getString(key, null): null; } /** * Retrieves all of the payload as a single Bundle Object * @return Bundle */ public Bundle getPayloadData() { return _payloadData; } /** * Returns an {@link IterableInAppManager} that can be used to manage in-app messages. * Make sure the Iterable API is initialized before calling this method. * @return {@link IterableInAppManager} instance */ public IterableInAppManager getInAppManager() { if (inAppManager == null) { inAppManager = new IterableInAppManager(this, config.inAppHandler, config.inAppDisplayInterval); inAppManager.syncInApp(); } return inAppManager; } /** * Returns the attribution information ({@link IterableAttributionInfo}) for last push open * or app link click from an email. * @return {@link IterableAttributionInfo} Object containing */ public IterableAttributionInfo getAttributionInfo() { return IterableAttributionInfo.fromJSONObject( IterableUtil.retrieveExpirableJsonObject(getPreferences(), IterableConstants.SHARED_PREFS_ATTRIBUTION_INFO_KEY) ); } /** * Stores attribution information. * @param attributionInfo Attribution information object */ void setAttributionInfo(IterableAttributionInfo attributionInfo) { if (_applicationContext == null) { IterableLogger.e(TAG, "setAttributionInfo: Iterable SDK is not initialized with a context."); return; } IterableUtil.saveExpirableJsonObject( getPreferences(), IterableConstants.SHARED_PREFS_ATTRIBUTION_INFO_KEY, attributionInfo.toJSONObject(), 3600 * IterableConstants.SHARED_PREFS_ATTRIBUTION_INFO_EXPIRATION_HOURS * 1000 ); } /** * Returns the current context for the application. * @return */ Context getMainActivityContext() { return _applicationContext; } /** * Sets debug mode. * @param debugMode */ void setDebugMode(boolean debugMode) { _debugMode = debugMode; } /** * Gets the current state of the debug mode. * @return */ boolean getDebugMode() { return _debugMode; } /** * Set the payload for a given intent if it is from Iterable. * @param intent */ void setPayloadData(Intent intent) { Bundle extras = intent.getExtras(); if (extras != null && extras.containsKey(IterableConstants.ITERABLE_DATA_KEY) && !IterableNotificationHelper.isGhostPush(extras)) { setPayloadData(extras); } } /** * Sets the payload bundle. * @param bundle */ void setPayloadData(Bundle bundle) { _payloadData = bundle; } /** * Sets the IterableNotification data * @param data */ void setNotificationData(IterableNotificationData data) { _notificationData = data; if (data != null) { setAttributionInfo(new IterableAttributionInfo(data.getCampaignId(), data.getTemplateId(), data.getMessageId())); } } //--------------------------------------------------------------------------------------- //endregion //region Public Functions //--------------------------------------------------------------------------------------- /** * Get {@link IterableApi} singleton instance * @return {@link IterableApi} singleton instance */ public static IterableApi getInstance() { return sharedInstance; } /** * Initializes IterableApi * This method must be called from {@link Application#onCreate()} * Note: Make sure you also call {@link #setEmail(String)} or {@link #setUserId(String)} before calling other methods * * @param context Application context * @param apiKey Iterable Mobile API key */ public static void initialize(Context context, String apiKey) { initialize(context, apiKey, null); } /** * Initializes IterableApi * This method must be called from {@link Application#onCreate()} * Note: Make sure you also call {@link #setEmail(String)} or {@link #setUserId(String)} before calling other methods * * @param context Application context * @param apiKey Iterable Mobile API key * @param config {@link IterableConfig} object holding SDK configuration options */ public static void initialize(Context context, String apiKey, IterableConfig config) { sharedInstance._applicationContext = context.getApplicationContext(); sharedInstance._apiKey = apiKey; sharedInstance.config = config; if (sharedInstance.config == null) { sharedInstance.config = new IterableConfig.Builder().build(); } sharedInstance.sdkCompatEnabled = false; sharedInstance.retrieveEmailAndUserId(); sharedInstance.checkForDeferredDeeplink(); IterableActivityMonitor.getInstance().registerLifecycleCallbacks(context); if (sharedInstance.config.autoPushRegistration && sharedInstance.isInitialized()) { sharedInstance.registerForPush(); } } /** * Returns a shared instance of IterableApi. Updates the client data if an instance already exists. * Should be called whenever the app is opened. * @param currentActivity The current activity * @param userId The current userId * @return stored instance of IterableApi * * @deprecated Initialize the SDK with {@link #initialize(Context, String, IterableConfig)} instead */ @Deprecated public static IterableApi sharedInstanceWithApiKeyWithUserId(Activity currentActivity, String apiKey, String userId) { return sharedInstanceWithApiKeyWithUserId(currentActivity, apiKey, userId, false); } /** * Returns a shared instance of IterableApi. Updates the client data if an instance already exists. * Should be called whenever the app is opened. * Allows the IterableApi to be intialized with debugging enabled * @param currentActivity The current activity * @param userId The current userId@return stored instance of IterableApi * * @deprecated Initialize the SDK with {@link #initialize(Context, String, IterableConfig)} instead */ @Deprecated public static IterableApi sharedInstanceWithApiKeyWithUserId(Activity currentActivity, String apiKey, String userId, boolean debugMode) { return sharedInstanceWithApiKeyWithUserId((Context) currentActivity, apiKey, userId, debugMode); } /** * Returns a shared instance of IterableApi. Updates the client data if an instance already exists. * Should be called whenever the app is opened. * @param currentContext The current context * @param userId The current userId * @return stored instance of IterableApi * * @deprecated Initialize the SDK with {@link #initialize(Context, String, IterableConfig)} instead */ @Deprecated public static IterableApi sharedInstanceWithApiKeyWithUserId(Context currentContext, String apiKey, String userId) { return sharedInstanceWithApiKey(currentContext, apiKey, null, userId, false); } /** * Returns a shared instance of IterableApi. Updates the client data if an instance already exists. * Should be called whenever the app is opened. * Allows the IterableApi to be intialized with debugging enabled * @param currentContext The current context * @return stored instance of IterableApi * * @deprecated Initialize the SDK with {@link #initialize(Context, String, IterableConfig)} instead */ @Deprecated public static IterableApi sharedInstanceWithApiKeyWithUserId(Context currentContext, String apiKey, String userId, boolean debugMode) { return sharedInstanceWithApiKey(currentContext, apiKey, null, userId, debugMode); } /** * Returns a shared instance of IterableApi. Updates the client data if an instance already exists. * Should be called whenever the app is opened. * @param currentActivity The current activity * @param email The current email * @return stored instance of IterableApi * * @deprecated Initialize the SDK with {@link #initialize(Context, String, IterableConfig)} instead */ @Deprecated public static IterableApi sharedInstanceWithApiKey(Activity currentActivity, String apiKey, String email) { return sharedInstanceWithApiKey(currentActivity, apiKey, email, false); } /** * Returns a shared instance of IterableApi. Updates the client data if an instance already exists. * Should be called whenever the app is opened. * Allows the IterableApi to be intialized with debugging enabled * @param currentActivity The current activity * @param email The current email * @return stored instance of IterableApi */ @Deprecated public static IterableApi sharedInstanceWithApiKey(Activity currentActivity, String apiKey, String email, boolean debugMode) { return sharedInstanceWithApiKey((Context) currentActivity, apiKey, email, debugMode); } /** * Returns a shared instance of IterableApi. Updates the client data if an instance already exists. * Should be called whenever the app is opened. * @param currentContext The current context * @param email The current email * @return stored instance of IterableApi * * @deprecated Initialize the SDK with {@link #initialize(Context, String, IterableConfig)} instead */ @Deprecated public static IterableApi sharedInstanceWithApiKey(Context currentContext, String apiKey, String email) { return sharedInstanceWithApiKey(currentContext, apiKey, email, false); } /** * Returns a shared instance of IterableApi. Updates the client data if an instance already exists. * Should be called whenever the app is opened. * Allows the IterableApi to be intialized with debugging enabled * @param currentContext The current context * @param email The current email * @return stored instance of IterableApi * * @deprecated Initialize the SDK with {@link #initialize(Context, String, IterableConfig)} instead */ @Deprecated public static IterableApi sharedInstanceWithApiKey(Context currentContext, String apiKey, String email, boolean debugMode) { return sharedInstanceWithApiKey(currentContext, apiKey, email, null, debugMode); } private static IterableApi sharedInstanceWithApiKey(Context currentContext, String apiKey, String email, String userId, boolean debugMode) { sharedInstance.updateData(currentContext.getApplicationContext(), apiKey, email, userId); sharedInstance.setDebugMode(debugMode); sharedInstance.sdkCompatEnabled = true; return sharedInstance; } /** * Set user email used for API calls * Calling this or `setUserId:` is required before making any API calls. * * Note: This clears userId and persists the user email so you only need to call this once when the user logs in. * @param email User email */ public void setEmail(String email) { if (_email != null && _email.equals(email)) { return; } if (_email == null && _userId == null && email == null) { return; } onLogOut(); _email = email; _userId = null; storeEmailAndUserId(); onLogIn(); } /** * Set user ID used for API calls * Calling this or `setEmail:` is required before making any API calls. * * Note: This clears user email and persists the user ID so you only need to call this once when the user logs in. * @param userId User ID */ public void setUserId(String userId) { if (_userId != null && _userId.equals(userId)) { return; } if (_email == null && _userId == null && userId == null) { return; } onLogOut(); _email = null; _userId = userId; storeEmailAndUserId(); onLogIn(); } /** * Tracks a click on the uri if it is an iterable link. * @param uri the * @param onCallback Calls the callback handler with the destination location * or the original url if it is not a interable link. */ public static void getAndTrackDeeplink(String uri, IterableHelper.IterableActionHandler onCallback) { IterableDeeplinkManager.getAndTrackDeeplink(uri, onCallback); } /** * Handles an App Link * For Iterable links, it will track the click and retrieve the original URL, pass it to * {@link IterableUrlHandler} for handling * If it's not an Iterable link, it just passes the same URL to {@link IterableUrlHandler} * * Call this from {@link Activity#onCreate(Bundle)} and {@link Activity#onNewIntent(Intent)} * in your deep link handler activity * @param uri the URL obtained from {@link Intent#getData()} in your deep link * handler activity * @return */ public static boolean handleAppLink(String uri) { if (IterableDeeplinkManager.isIterableDeeplink(uri)) { IterableDeeplinkManager.getAndTrackDeeplink(uri, new IterableHelper.IterableActionHandler() { @Override public void execute(String originalUrl) { IterableAction action = IterableAction.actionOpenUrl(originalUrl); IterableActionRunner.executeAction(getInstance().getMainActivityContext(), action, IterableActionSource.APP_LINK); } }); return true; } else { IterableAction action = IterableAction.actionOpenUrl(uri); return IterableActionRunner.executeAction(getInstance().getMainActivityContext(), action, IterableActionSource.APP_LINK); } } /** * Debugging function to send API calls to different url endpoints. * @param url */ public static void overrideURLEndpointPath(String url) { IterableRequest.overrideUrl = url; } /** * Call onNewIntent to set the payload data and track pushOpens directly if * sharedInstanceWithApiKey was called with a Context rather than an Activity. * @deprecated Push opens are now tracked automatically. */ @Deprecated public void onNewIntent(Intent intent) { } /** * Returns whether or not the intent was sent from Iterable. */ public boolean isIterableIntent(Intent intent) { if (intent != null) { Bundle extras = intent.getExtras(); return (extras != null && extras.containsKey(IterableConstants.ITERABLE_DATA_KEY)); } return false; } /** * Registers a device token with Iterable. * Make sure {@link IterableConfig#pushIntegrationName} is set before calling this. * @param token Push token obtained from GCM or FCM */ public void registerDeviceToken(String token) { if (config.pushIntegrationName == null) { IterableLogger.e(TAG, "registerDeviceToken: pushIntegrationName is not set"); return; } registerDeviceToken(config.pushIntegrationName, token); } /** * Registers a device token with Iterable. * @param applicationName * @param token * @deprecated Call {@link #registerDeviceToken(String)} instead and specify the push * integration name in {@link IterableConfig#pushIntegrationName} */ @Deprecated public void registerDeviceToken(String applicationName, String token) { registerDeviceToken(applicationName, token, IterableConstants.MESSAGING_PLATFORM_FIREBASE); } /** * Registers a device token with Iterable. * @param applicationName * @param token * @param pushServicePlatform * @deprecated Call {@link #registerDeviceToken(String)} instead and specify the push * integration name in {@link IterableConfig#pushIntegrationName} */ @Deprecated public void registerDeviceToken(final String applicationName, final String token, final String pushServicePlatform) { registerDeviceToken(_email, _userId, applicationName, token, pushServicePlatform); } protected void registerDeviceToken(final String email, final String userId, final String applicationName, final String token, final String pushServicePlatform) { if (!IterableConstants.MESSAGING_PLATFORM_FIREBASE.equals(pushServicePlatform)) { IterableLogger.e(TAG, "registerDeviceToken: only MESSAGING_PLATFORM_FIREBASE is supported."); return; } if (token != null) { final Thread registrationThread = new Thread(new Runnable() { public void run() { registerDeviceToken(email, userId, applicationName, token, IterableConstants.MESSAGING_PLATFORM_FIREBASE, null); } }); registrationThread.start(); } } /** * Track an event. * @param eventName */ public void track(String eventName) { track(eventName, 0, 0, null); } /** * Track an event. * @param eventName * @param dataFields */ public void track(String eventName, JSONObject dataFields) { track(eventName, 0, 0, dataFields); } /** * Track an event. * @param eventName * @param campaignId * @param templateId */ public void track(String eventName, int campaignId, int templateId) { track(eventName, campaignId, templateId, null); } /** * Track an event. * @param eventName * @param campaignId * @param templateId * @param dataFields */ public void track(String eventName, int campaignId, int templateId, JSONObject dataFields) { if (!checkSDKInitialization()) { return; } JSONObject requestJSON = new JSONObject(); try { addEmailOrUserIdToJson(requestJSON); requestJSON.put(IterableConstants.KEY_EVENT_NAME, eventName); if (campaignId != 0) { requestJSON.put(IterableConstants.KEY_CAMPAIGN_ID, campaignId); } if (templateId != 0) { requestJSON.put(IterableConstants.KEY_TEMPLATE_ID, templateId); } requestJSON.put(IterableConstants.KEY_DATA_FIELDS, dataFields); sendPostRequest(IterableConstants.ENDPOINT_TRACK, requestJSON); } catch (JSONException e) { e.printStackTrace(); } } /** * Tracks a purchase. * @param total total purchase amount * @param items list of purchased items */ public void trackPurchase(double total, List<CommerceItem> items) { trackPurchase(total, items, null); } /** * Tracks a purchase. * @param total total purchase amount * @param items list of purchased items * @param dataFields a `JSONObject` containing any additional information to save along with the event */ public void trackPurchase(double total, List<CommerceItem> items, JSONObject dataFields) { if (!checkSDKInitialization()) { return; } JSONObject requestJSON = new JSONObject(); try { JSONArray itemsArray = new JSONArray(); for (CommerceItem item : items) { itemsArray.put(item.toJSONObject()); } JSONObject userObject = new JSONObject(); addEmailOrUserIdToJson(userObject); requestJSON.put(IterableConstants.KEY_USER, userObject); requestJSON.put(IterableConstants.KEY_ITEMS, itemsArray); requestJSON.put(IterableConstants.KEY_TOTAL, total); if (dataFields != null) { requestJSON.put(IterableConstants.KEY_DATA_FIELDS, dataFields); } sendPostRequest(IterableConstants.ENDPOINT_TRACK_PURCHASE, requestJSON); } catch (JSONException e) { e.printStackTrace(); } } public void sendPush(String email, int campaignId) { sendPush(email, campaignId, null, null); } /** * Sends a push campaign to an email address at the given time. * @param sendAt Schedule the message for up to 365 days in the future. * If set in the past, message is sent immediately. * Format is YYYY-MM-DD HH:MM:SS in UTC */ public void sendPush(String email, int campaignId, Date sendAt) { sendPush(email, campaignId, sendAt, null); } /** * Sends a push campaign to an email address. * @param email * @param campaignId * @param dataFields */ public void sendPush(String email, int campaignId, JSONObject dataFields) { sendPush(email, campaignId, null, dataFields); } /** * Sends a push campaign to an email address at the given time. * @param sendAt Schedule the message for up to 365 days in the future. * If set in the past, message is sent immediately. * Format is YYYY-MM-DD HH:MM:SS in UTC */ public void sendPush(String email, int campaignId, Date sendAt, JSONObject dataFields) { if (!checkSDKInitialization()) { return; } JSONObject requestJSON = new JSONObject(); try { requestJSON.put(IterableConstants.KEY_RECIPIENT_EMAIL, email); requestJSON.put(IterableConstants.KEY_CAMPAIGN_ID, campaignId); if (sendAt != null){ SimpleDateFormat sdf = new SimpleDateFormat(IterableConstants.DATEFORMAT); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); String dateString = sdf.format(sendAt); requestJSON.put(IterableConstants.KEY_SEND_AT, dateString); } sendPostRequest(IterableConstants.ENDPOINT_PUSH_TARGET, requestJSON); } catch (JSONException e) { e.printStackTrace(); } } /** * Updates the current user's email. * Also updates the current email in this IterableAPI instance if the API call was successful. * @param newEmail New email */ public void updateEmail(final String newEmail) { updateEmail(newEmail, null, null); } /** * Updates the current user's email. * Also updates the current email in this IterableAPI instance if the API call was successful. * @param newEmail New email * @param successHandler Success handler. Called when the server returns a success code. * @param failureHandler Failure handler. Called when the server call failed. */ public void updateEmail(final String newEmail, final IterableHelper.SuccessHandler successHandler, IterableHelper.FailureHandler failureHandler) { if (!checkSDKInitialization()) { IterableLogger.e(TAG, "The Iterable SDK must be initialized with email or userId before "+ "calling updateEmail"); if (failureHandler != null) { failureHandler.onFailure("The Iterable SDK must be initialized with email or "+ "userId before calling updateEmail", null); } return; } JSONObject requestJSON = new JSONObject(); try { if (_email != null) { requestJSON.put(IterableConstants.KEY_CURRENT_EMAIL, _email); } else { requestJSON.put(IterableConstants.KEY_CURRENT_USERID, _userId); } requestJSON.put(IterableConstants.KEY_NEW_EMAIL, newEmail); sendPostRequest(IterableConstants.ENDPOINT_UPDATE_EMAIL, requestJSON, new IterableHelper.SuccessHandler() { @Override public void onSuccess(JSONObject data) { if (_email != null) { _email = newEmail; } storeEmailAndUserId(); if (successHandler != null) { successHandler.onSuccess(data); } } }, failureHandler); } catch (JSONException e) { e.printStackTrace(); } } /** * Updates the current user. * @param dataFields */ public void updateUser(JSONObject dataFields) { if (!checkSDKInitialization()) { return; } JSONObject requestJSON = new JSONObject(); try { addEmailOrUserIdToJson(requestJSON); // Create the user by userId if it doesn't exist if (_email == null && _userId != null) { requestJSON.put(IterableConstants.KEY_PREFER_USER_ID, true); } requestJSON.put(IterableConstants.KEY_DATA_FIELDS, dataFields); sendPostRequest(IterableConstants.ENDPOINT_UPDATE_USER, requestJSON); } catch (JSONException e) { e.printStackTrace(); } } /** * Registers for push notifications. * Make sure the API is initialized with {@link IterableConfig#pushIntegrationName} defined, and * user email or user ID is set before calling this method. */ public void registerForPush() { if (!checkSDKInitialization()) { return; } if (config.pushIntegrationName == null) { IterableLogger.e(TAG, "registerForPush: pushIntegrationName is not set"); return; } IterablePushRegistrationData data = new IterablePushRegistrationData(_email, _userId, config.pushIntegrationName, IterablePushRegistrationData.PushRegistrationAction.ENABLE); new IterablePushRegistration().execute(data); } /** * Registers for push notifications. * @param pushIntegrationName * @param gcmProjectNumber * @deprecated Call {@link #registerForPush()} instead and specify the push * integration name in {@link IterableConfig#pushIntegrationName} */ @Deprecated public void registerForPush(String pushIntegrationName, String gcmProjectNumber) { registerForPush(pushIntegrationName, gcmProjectNumber, IterableConstants.MESSAGING_PLATFORM_FIREBASE); } /** * Registers for push notifications. * @param pushIntegrationName * @param projectNumber * @param pushServicePlatform * @deprecated Call {@link #registerForPush()} instead and specify the push * integration name in {@link IterableConfig#pushIntegrationName} */ @Deprecated public void registerForPush(String pushIntegrationName, String projectNumber, String pushServicePlatform) { if (!IterableConstants.MESSAGING_PLATFORM_FIREBASE.equals(pushServicePlatform)) { IterableLogger.e(TAG, "registerDeviceToken: only MESSAGING_PLATFORM_FIREBASE is supported."); return; } IterablePushRegistrationData data = new IterablePushRegistrationData(_email, _userId, pushIntegrationName, projectNumber, pushServicePlatform, IterablePushRegistrationData.PushRegistrationAction.ENABLE); new IterablePushRegistration().execute(data); } /** * Registers for push notifications. * @param pushIntegrationName * @deprecated Call {@link #registerForPush()} instead and specify the push * integration name in {@link IterableConfig#pushIntegrationName} */ @Deprecated public void registerForPush(String pushIntegrationName) { IterablePushRegistrationData data = new IterablePushRegistrationData(_email, _userId, pushIntegrationName, IterablePushRegistrationData.PushRegistrationAction.ENABLE); new IterablePushRegistration().execute(data); } /** * Disables the device from push notifications */ public void disablePush() { if (config.pushIntegrationName == null) { IterableLogger.e(TAG, "disablePush: pushIntegrationName is not set"); return; } IterablePushRegistrationData data = new IterablePushRegistrationData(_email, _userId, config.pushIntegrationName, IterablePushRegistrationData.PushRegistrationAction.DISABLE); new IterablePushRegistration().execute(data); } /** * Disables the device from push notifications * @param iterableAppId * @param gcmProjectNumber * @deprecated Call {@link #disablePush()} instead and specify the push * integration name in {@link IterableConfig#pushIntegrationName} */ @Deprecated public void disablePush(String iterableAppId, String gcmProjectNumber) { disablePush(iterableAppId, gcmProjectNumber, IterableConstants.MESSAGING_PLATFORM_FIREBASE); } /** * Disables the device from push notifications * @param iterableAppId * @param projectNumber * @param pushServicePlatform * @deprecated Call {@link #disablePush()} instead and specify the push * integration name in {@link IterableConfig#pushIntegrationName} */ @Deprecated public void disablePush(String iterableAppId, String projectNumber, String pushServicePlatform) { if (!IterableConstants.MESSAGING_PLATFORM_FIREBASE.equals(pushServicePlatform)) { IterableLogger.e(TAG, "registerDeviceToken: only MESSAGING_PLATFORM_FIREBASE is supported."); return; } IterablePushRegistrationData data = new IterablePushRegistrationData(_email, _userId, iterableAppId, projectNumber, pushServicePlatform, IterablePushRegistrationData.PushRegistrationAction.DISABLE); new IterablePushRegistration().execute(data); } /** * Updates the user subscription preferences. Passing in an empty array will clear the list, passing in null will not modify the list * @param emailListIds * @param unsubscribedChannelIds * @param unsubscribedMessageTypeIds */ public void updateSubscriptions(Integer[] emailListIds, Integer[] unsubscribedChannelIds, Integer[] unsubscribedMessageTypeIds) { if (!checkSDKInitialization()) { return; } JSONObject requestJSON = new JSONObject(); addEmailOrUserIdToJson(requestJSON); tryAddArrayToJSON(requestJSON, IterableConstants.KEY_EMAIL_LIST_IDS, emailListIds); tryAddArrayToJSON(requestJSON, IterableConstants.KEY_UNSUB_CHANNEL, unsubscribedChannelIds); tryAddArrayToJSON(requestJSON, IterableConstants.KEY_UNSUB_MESSAGE, unsubscribedMessageTypeIds); sendPostRequest(IterableConstants.ENDPOINT_UPDATE_USER_SUBS, requestJSON); } /** * Attempts to add an array as a JSONArray to a JSONObject * @param requestJSON * @param key * @param value */ void tryAddArrayToJSON(JSONObject requestJSON, String key, Object[] value) { if (requestJSON != null && key != null && value != null) try { JSONArray mJSONArray = new JSONArray(Arrays.asList(value)); requestJSON.put(key, mJSONArray); } catch (JSONException e) { IterableLogger.e(TAG, e.toString()); } } /** * In-app messages are now shown automatically, and you can customize it via {@link IterableInAppHandler} * If you need to show messages manually, see {@link IterableInAppManager#getMessages()} and * {@link IterableInAppManager#showMessage(IterableInAppMessage)} * * @deprecated Please check our migration guide here: * https://github.com/iterable/iterable-android-sdk/#migrating-in-app-messages-from-the-previous-version-of-the-sdk */ @Deprecated void spawnInAppNotification(final Context context, final IterableHelper.IterableActionHandler clickCallback) { } /** * Gets a list of InAppNotifications from Iterable; passes the result to the callback. * @deprecated Use {@link IterableInAppManager#getMessages()} instead * @param count the number of messages to fetch * @param onCallback */ @Deprecated public void getInAppMessages(int count, IterableHelper.IterableActionHandler onCallback) { if (!checkSDKInitialization()) { return; } JSONObject requestJSON = new JSONObject(); addEmailOrUserIdToJson(requestJSON); try { addEmailOrUserIdToJson(requestJSON); requestJSON.put(IterableConstants.ITERABLE_IN_APP_COUNT, count); requestJSON.put(IterableConstants.KEY_PLATFORM, IterableConstants.ITBL_PLATFORM_ANDROID); requestJSON.put(IterableConstants.ITBL_KEY_SDK_VERSION, IterableConstants.ITBL_KEY_SDK_VERSION_NUMBER); requestJSON.put(IterableConstants.KEY_PACKAGE_NAME, _applicationContext.getPackageName()); sendGetRequest(IterableConstants.ENDPOINT_GET_INAPP_MESSAGES, requestJSON, onCallback); } catch (JSONException e) { e.printStackTrace(); } } /** * Tracks an InApp open. * @param messageId */ public void trackInAppOpen(String messageId) { if (!checkSDKInitialization()) { return; } JSONObject requestJSON = new JSONObject(); try { addEmailOrUserIdToJson(requestJSON); requestJSON.put(IterableConstants.KEY_MESSAGE_ID, messageId); sendPostRequest(IterableConstants.ENDPOINT_TRACK_INAPP_OPEN, requestJSON); } catch (JSONException e) { e.printStackTrace(); } } /** * Tracks an InApp click. * @param messageId * @param clickedUrl */ public void trackInAppClick(String messageId, String clickedUrl) { if (!checkSDKInitialization()) { return; } JSONObject requestJSON = new JSONObject(); try { addEmailOrUserIdToJson(requestJSON); requestJSON.put(IterableConstants.KEY_MESSAGE_ID, messageId); requestJSON.put(IterableConstants.ITERABLE_IN_APP_CLICKED_URL, clickedUrl); sendPostRequest(IterableConstants.ENDPOINT_TRACK_INAPP_CLICK, requestJSON); } catch (JSONException e) { e.printStackTrace(); } } /** * Consumes an InApp message. * @param messageId */ public void inAppConsume(String messageId) { if (!checkSDKInitialization()) { return; } JSONObject requestJSON = new JSONObject(); try { addEmailOrUserIdToJson(requestJSON); requestJSON.put(IterableConstants.KEY_MESSAGE_ID, messageId); sendPostRequest(IterableConstants.ENDPOINT_INAPP_CONSUME, requestJSON); } catch (JSONException e) { e.printStackTrace(); } } //--------------------------------------------------------------------------------------- //endregion //region Package-Protected Fuctions //--------------------------------------------------------------------------------------- /** * Get user email * @return user email */ String getEmail() { return _email; } /** * Get user ID * @return user ID */ String getUserId() { return _userId; } //--------------------------------------------------------------------------------------- //endregion //region Protected Fuctions //--------------------------------------------------------------------------------------- /** * Set the notification icon with the given iconName. * @param context * @param iconName */ static void setNotificationIcon(Context context, String iconName) { SharedPreferences sharedPref = context.getSharedPreferences(IterableConstants.NOTIFICATION_ICON_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putString(IterableConstants.NOTIFICATION_ICON_NAME, iconName); editor.commit(); } /** * Returns the stored notification icon. * @param context * @return */ static String getNotificationIcon(Context context) { SharedPreferences sharedPref = context.getSharedPreferences(IterableConstants.NOTIFICATION_ICON_NAME, Context.MODE_PRIVATE); String iconName = sharedPref.getString(IterableConstants.NOTIFICATION_ICON_NAME, ""); return iconName; } protected void trackPushOpen(int campaignId, int templateId, String messageId) { trackPushOpen(campaignId, templateId, messageId, null); } /** * Tracks when a push notification is opened on device. * @param campaignId * @param templateId */ protected void trackPushOpen(int campaignId, int templateId, String messageId, JSONObject dataFields) { JSONObject requestJSON = new JSONObject(); try { if (dataFields == null) { dataFields = new JSONObject(); } addEmailOrUserIdToJson(requestJSON); requestJSON.put(IterableConstants.KEY_CAMPAIGN_ID, campaignId); requestJSON.put(IterableConstants.KEY_TEMPLATE_ID, templateId); requestJSON.put(IterableConstants.KEY_MESSAGE_ID, messageId); requestJSON.putOpt(IterableConstants.KEY_DATA_FIELDS, dataFields); sendPostRequest(IterableConstants.ENDPOINT_TRACK_PUSH_OPEN, requestJSON); } catch (JSONException e) { e.printStackTrace(); } } protected void disableToken(String email, String userId, String token) { disableToken(email, userId, token, null, null); } /** * Internal api call made from IterablePushRegistration after a registrationToken is obtained. * @param token */ protected void disableToken(String email, String userId, String token, IterableHelper.SuccessHandler onSuccess, IterableHelper.FailureHandler onFailure) { JSONObject requestJSON = new JSONObject(); try { requestJSON.put(IterableConstants.KEY_TOKEN, token); if (email != null) { requestJSON.put(IterableConstants.KEY_EMAIL, email); } else { requestJSON.put(IterableConstants.KEY_USER_ID, userId); } sendPostRequest(IterableConstants.ENDPOINT_DISABLE_DEVICE, requestJSON, onSuccess, onFailure); } catch (JSONException e) { e.printStackTrace(); } } /** * Registers the GCM registration ID with Iterable. * @param applicationName * @param token * @param pushServicePlatform * @param dataFields */ protected void registerDeviceToken(String email, String userId, String applicationName, String token, String pushServicePlatform, JSONObject dataFields) { if (!checkSDKInitialization()) { return; } if (token == null) { IterableLogger.e(TAG, "registerDeviceToken: token is null"); return; } if (applicationName == null) { IterableLogger.e(TAG, "registerDeviceToken: applicationName is null, check that pushIntegrationName is set in IterableConfig"); } JSONObject requestJSON = new JSONObject(); try { addEmailOrUserIdToJson(requestJSON); if (dataFields == null) { dataFields = new JSONObject(); } dataFields.put(IterableConstants.FIREBASE_TOKEN_TYPE, IterableConstants.MESSAGING_PLATFORM_FIREBASE); dataFields.put(IterableConstants.FIREBASE_COMPATIBLE, true); dataFields.put(IterableConstants.DEVICE_BRAND, Build.BRAND); //brand: google dataFields.put(IterableConstants.DEVICE_MANUFACTURER, Build.MANUFACTURER); //manufacturer: samsung dataFields.putOpt(IterableConstants.DEVICE_ADID, getAdvertisingId()); //ADID: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" dataFields.put(IterableConstants.DEVICE_SYSTEM_NAME, Build.DEVICE); //device name: toro dataFields.put(IterableConstants.DEVICE_SYSTEM_VERSION, Build.VERSION.RELEASE); //version: 4.0.4 dataFields.put(IterableConstants.DEVICE_MODEL, Build.MODEL); //device model: Galaxy Nexus dataFields.put(IterableConstants.DEVICE_SDK_VERSION, Build.VERSION.SDK_INT); //sdk version/api level: 15 dataFields.put(IterableConstants.DEVICE_ID, getDeviceId()); // Random UUID dataFields.put(IterableConstants.DEVICE_APP_PACKAGE_NAME, _applicationContext.getPackageName()); dataFields.put(IterableConstants.DEVICE_APP_VERSION, IterableUtil.getAppVersion(_applicationContext)); dataFields.put(IterableConstants.DEVICE_APP_BUILD, IterableUtil.getAppVersionCode(_applicationContext)); dataFields.put(IterableConstants.DEVICE_ITERABLE_SDK_VERSION, IterableConstants.ITBL_KEY_SDK_VERSION_NUMBER); dataFields.put(IterableConstants.DEVICE_NOTIFICATIONS_ENABLED, NotificationManagerCompat.from(_applicationContext).areNotificationsEnabled()); JSONObject device = new JSONObject(); device.put(IterableConstants.KEY_TOKEN, token); device.put(IterableConstants.KEY_PLATFORM, IterableConstants.MESSAGING_PLATFORM_GOOGLE); device.put(IterableConstants.KEY_APPLICATION_NAME, applicationName); device.putOpt(IterableConstants.KEY_DATA_FIELDS, dataFields); requestJSON.put(IterableConstants.KEY_DEVICE, device); // Create the user by userId if it doesn't exist if (email == null && userId != null) { requestJSON.put(IterableConstants.KEY_PREFER_USER_ID, true); } sendPostRequest(IterableConstants.ENDPOINT_REGISTER_DEVICE_TOKEN, requestJSON); } catch (JSONException e) { IterableLogger.e(TAG, "registerDeviceToken: exception", e); } } //--------------------------------------------------------------------------------------- //endregion //region Private Fuctions //--------------------------------------------------------------------------------------- /** * Updates the data for the current user. * @param context * @param apiKey * @param email * @param userId */ private void updateData(Context context, String apiKey, String email, String userId) { this._applicationContext = context; this._apiKey = apiKey; this._email = email; this._userId = userId; } private boolean isInitialized() { return _apiKey != null && (_email != null || _userId != null); } private boolean checkSDKInitialization() { if (!isInitialized()) { IterableLogger.e(TAG, "Iterable SDK must be initialized with an API key and user email/userId before calling SDK methods"); return false; } return true; } private SharedPreferences getPreferences() { return _applicationContext.getSharedPreferences(IterableConstants.SHARED_PREFS_FILE, Context.MODE_PRIVATE); } /** * Sends the POST request to Iterable. * Performs network operations on an async thread instead of the main thread. * @param resourcePath * @param json */ void sendPostRequest(String resourcePath, JSONObject json) { IterableApiRequest request = new IterableApiRequest(_apiKey, resourcePath, json, IterableApiRequest.POST, null, null); new IterableRequest().execute(request); } void sendPostRequest(String resourcePath, JSONObject json, IterableHelper.SuccessHandler onSuccess, IterableHelper.FailureHandler onFailure) { IterableApiRequest request = new IterableApiRequest(_apiKey, resourcePath, json, IterableApiRequest.POST, onSuccess, onFailure); new IterableRequest().execute(request); } /** * Sends a GET request to Iterable. * Performs network operations on an async thread instead of the main thread. * @param resourcePath * @param json */ void sendGetRequest(String resourcePath, JSONObject json, IterableHelper.IterableActionHandler onCallback) { IterableApiRequest request = new IterableApiRequest(_apiKey, resourcePath, json, IterableApiRequest.GET, onCallback); new IterableRequest().execute(request); } /** * Adds the current email or userID to the json request. * @param requestJSON */ private void addEmailOrUserIdToJson(JSONObject requestJSON) { try { if (_email != null) { requestJSON.put(IterableConstants.KEY_EMAIL, _email); } else { requestJSON.put(IterableConstants.KEY_USER_ID, _userId); } } catch (JSONException e) { e.printStackTrace(); } } /** * Gets the advertisingId if available * @return */ private String getAdvertisingId() { String advertisingId = null; try { Class adClass = Class.forName("com.google.android.gms.ads.identifier.AdvertisingIdClient"); if (adClass != null) { Object advertisingIdInfo = adClass.getMethod("getAdvertisingIdInfo", Context.class).invoke(null, _applicationContext); if (advertisingIdInfo != null) { advertisingId = (String) advertisingIdInfo.getClass().getMethod("getId").invoke(advertisingIdInfo); } } } catch (ClassNotFoundException e) { IterableLogger.d(TAG, "ClassNotFoundException: Can't track ADID. " + "Check that play-services-ads is added to the dependencies.", e); } catch (Exception e) { IterableLogger.w(TAG, e.getMessage()); } return advertisingId; } private String getDeviceId() { if (_deviceId == null) { _deviceId = getPreferences().getString(IterableConstants.SHARED_PREFS_DEVICEID_KEY, null); if (_deviceId == null) { _deviceId = UUID.randomUUID().toString(); getPreferences().edit().putString(IterableConstants.SHARED_PREFS_DEVICEID_KEY, _deviceId).apply(); } } return _deviceId; } private void storeEmailAndUserId() { try { SharedPreferences.Editor editor = getPreferences().edit(); editor.putString(IterableConstants.SHARED_PREFS_EMAIL_KEY, _email); editor.putString(IterableConstants.SHARED_PREFS_USERID_KEY, _userId); editor.commit(); } catch (Exception e) { IterableLogger.e(TAG, "Error while persisting email/userId", e); } } private void retrieveEmailAndUserId() { try { SharedPreferences prefs = getPreferences(); _email = prefs.getString(IterableConstants.SHARED_PREFS_EMAIL_KEY, null); _userId = prefs.getString(IterableConstants.SHARED_PREFS_USERID_KEY, null); } catch (Exception e) { IterableLogger.e(TAG, "Error while retrieving email/userId", e); } } private void onLogOut() { if (config.autoPushRegistration && isInitialized()) { disablePush(); } } private void onLogIn() { if (config.autoPushRegistration && isInitialized()) { registerForPush(); } getInAppManager().syncInApp(); } private boolean getDDLChecked() { return getPreferences().getBoolean(IterableConstants.SHARED_PREFS_DDL_CHECKED_KEY, false); } private void setDDLChecked(boolean value) { getPreferences().edit().putBoolean(IterableConstants.SHARED_PREFS_DDL_CHECKED_KEY, value).apply(); } private void checkForDeferredDeeplink() { if (!config.checkForDeferredDeeplink) { return; } try { if (getDDLChecked()) { return; } JSONObject requestJSON = DeviceInfo.createDeviceInfo(_applicationContext).toJSONObject(); IterableApiRequest request = new IterableApiRequest(_apiKey, IterableConstants.BASE_URL_LINKS, IterableConstants.ENDPOINT_DDL_MATCH, requestJSON, IterableApiRequest.POST, new IterableHelper.SuccessHandler() { @Override public void onSuccess(JSONObject data) { handleDDL(data); } }, new IterableHelper.FailureHandler() { @Override public void onFailure(String reason, JSONObject data) { IterableLogger.e(TAG, "Error while checking deferred deep link: " + reason + ", response: " + data); } }); new IterableRequest().execute(request); } catch (Exception e) { IterableLogger.e(TAG, "Error while checking deferred deep link", e); } } private void handleDDL(JSONObject response) { IterableLogger.d(TAG, "handleDDL: " + response); try { MatchFpResponse matchFpResponse = MatchFpResponse.fromJSONObject(response); if (matchFpResponse.isMatch) { IterableAction action = IterableAction.actionOpenUrl(matchFpResponse.destinationUrl); IterableActionRunner.executeAction(getMainActivityContext(), action, IterableActionSource.APP_LINK); } } catch (JSONException e) { IterableLogger.e(TAG, "Error while handling deferred deep link", e); } setDDLChecked(true); } //--------------------------------------------------------------------------------------- //endregion }
iterableapi/src/main/java/com/iterable/iterableapi/IterableApi.java
package com.iterable.iterableapi; import android.app.Activity; import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; import android.support.annotation.VisibleForTesting; import android.support.v4.app.NotificationManagerCompat; import com.google.android.gms.ads.identifier.AdvertisingIdClient; import com.iterable.iterableapi.ddl.DeviceInfo; import com.iterable.iterableapi.ddl.MatchFpResponse; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.TimeZone; import java.util.UUID; /** * Created by David Truong [email protected] */ public class IterableApi { //region Variables //--------------------------------------------------------------------------------------- static final String TAG = "IterableApi"; /** * {@link IterableApi} singleton instance */ static volatile IterableApi sharedInstance = new IterableApi(); private Context _applicationContext; IterableConfig config; boolean sdkCompatEnabled; private String _apiKey; private String _email; private String _userId; private boolean _debugMode; private Bundle _payloadData; private IterableNotificationData _notificationData; private String _deviceId; private IterableInAppManager inAppManager; //--------------------------------------------------------------------------------------- //endregion //region Constructor //--------------------------------------------------------------------------------------- IterableApi() { config = new IterableConfig.Builder().build(); } @VisibleForTesting IterableApi(IterableInAppManager inAppManager) { config = new IterableConfig.Builder().build(); this.inAppManager = inAppManager; } //--------------------------------------------------------------------------------------- //endregion //region Getters/Setters //--------------------------------------------------------------------------------------- /** * Sets the icon to be displayed in notifications. * The icon name should match the resource name stored in the /res/drawable directory. * @param iconName */ public void setNotificationIcon(String iconName) { setNotificationIcon(_applicationContext, iconName); } /** * Retrieves the payload string for a given key. * Used for deeplinking and retrieving extra data passed down along with a campaign. * @param key * @return Returns the requested payload data from the current push campaign if it exists. */ public String getPayloadData(String key) { return (_payloadData != null) ? _payloadData.getString(key, null): null; } /** * Retrieves all of the payload as a single Bundle Object * @return Bundle */ public Bundle getPayloadData() { return _payloadData; } /** * Returns an {@link IterableInAppManager} that can be used to manage in-app messages. * Make sure the Iterable API is initialized before calling this method. * @return {@link IterableInAppManager} instance */ public IterableInAppManager getInAppManager() { if (inAppManager == null) { inAppManager = new IterableInAppManager(this, config.inAppHandler, config.inAppDisplayInterval); inAppManager.syncInApp(); } return inAppManager; } /** * Returns the attribution information ({@link IterableAttributionInfo}) for last push open * or app link click from an email. * @return {@link IterableAttributionInfo} Object containing */ public IterableAttributionInfo getAttributionInfo() { return IterableAttributionInfo.fromJSONObject( IterableUtil.retrieveExpirableJsonObject(getPreferences(), IterableConstants.SHARED_PREFS_ATTRIBUTION_INFO_KEY) ); } /** * Stores attribution information. * @param attributionInfo Attribution information object */ void setAttributionInfo(IterableAttributionInfo attributionInfo) { if (_applicationContext == null) { IterableLogger.e(TAG, "setAttributionInfo: Iterable SDK is not initialized with a context."); return; } IterableUtil.saveExpirableJsonObject( getPreferences(), IterableConstants.SHARED_PREFS_ATTRIBUTION_INFO_KEY, attributionInfo.toJSONObject(), 3600 * IterableConstants.SHARED_PREFS_ATTRIBUTION_INFO_EXPIRATION_HOURS * 1000 ); } /** * Returns the current context for the application. * @return */ Context getMainActivityContext() { return _applicationContext; } /** * Sets debug mode. * @param debugMode */ void setDebugMode(boolean debugMode) { _debugMode = debugMode; } /** * Gets the current state of the debug mode. * @return */ boolean getDebugMode() { return _debugMode; } /** * Set the payload for a given intent if it is from Iterable. * @param intent */ void setPayloadData(Intent intent) { Bundle extras = intent.getExtras(); if (extras != null && extras.containsKey(IterableConstants.ITERABLE_DATA_KEY) && !IterableNotificationHelper.isGhostPush(extras)) { setPayloadData(extras); } } /** * Sets the payload bundle. * @param bundle */ void setPayloadData(Bundle bundle) { _payloadData = bundle; } /** * Sets the IterableNotification data * @param data */ void setNotificationData(IterableNotificationData data) { _notificationData = data; if (data != null) { setAttributionInfo(new IterableAttributionInfo(data.getCampaignId(), data.getTemplateId(), data.getMessageId())); } } //--------------------------------------------------------------------------------------- //endregion //region Public Functions //--------------------------------------------------------------------------------------- /** * Get {@link IterableApi} singleton instance * @return {@link IterableApi} singleton instance */ public static IterableApi getInstance() { return sharedInstance; } /** * Initializes IterableApi * This method must be called from {@link Application#onCreate()} * Note: Make sure you also call {@link #setEmail(String)} or {@link #setUserId(String)} before calling other methods * * @param context Application context * @param apiKey Iterable Mobile API key */ public static void initialize(Context context, String apiKey) { initialize(context, apiKey, null); } /** * Initializes IterableApi * This method must be called from {@link Application#onCreate()} * Note: Make sure you also call {@link #setEmail(String)} or {@link #setUserId(String)} before calling other methods * * @param context Application context * @param apiKey Iterable Mobile API key * @param config {@link IterableConfig} object holding SDK configuration options */ public static void initialize(Context context, String apiKey, IterableConfig config) { sharedInstance._applicationContext = context.getApplicationContext(); sharedInstance._apiKey = apiKey; sharedInstance.config = config; if (sharedInstance.config == null) { sharedInstance.config = new IterableConfig.Builder().build(); } sharedInstance.sdkCompatEnabled = false; sharedInstance.retrieveEmailAndUserId(); sharedInstance.checkForDeferredDeeplink(); IterableActivityMonitor.getInstance().registerLifecycleCallbacks(context); if (sharedInstance.config.autoPushRegistration && sharedInstance.isInitialized()) { sharedInstance.registerForPush(); } } /** * Returns a shared instance of IterableApi. Updates the client data if an instance already exists. * Should be called whenever the app is opened. * @param currentActivity The current activity * @param userId The current userId * @return stored instance of IterableApi * * @deprecated Initialize the SDK with {@link #initialize(Context, String, IterableConfig)} instead */ @Deprecated public static IterableApi sharedInstanceWithApiKeyWithUserId(Activity currentActivity, String apiKey, String userId) { return sharedInstanceWithApiKeyWithUserId(currentActivity, apiKey, userId, false); } /** * Returns a shared instance of IterableApi. Updates the client data if an instance already exists. * Should be called whenever the app is opened. * Allows the IterableApi to be intialized with debugging enabled * @param currentActivity The current activity * @param userId The current userId@return stored instance of IterableApi * * @deprecated Initialize the SDK with {@link #initialize(Context, String, IterableConfig)} instead */ @Deprecated public static IterableApi sharedInstanceWithApiKeyWithUserId(Activity currentActivity, String apiKey, String userId, boolean debugMode) { return sharedInstanceWithApiKeyWithUserId((Context) currentActivity, apiKey, userId, debugMode); } /** * Returns a shared instance of IterableApi. Updates the client data if an instance already exists. * Should be called whenever the app is opened. * @param currentContext The current context * @param userId The current userId * @return stored instance of IterableApi * * @deprecated Initialize the SDK with {@link #initialize(Context, String, IterableConfig)} instead */ @Deprecated public static IterableApi sharedInstanceWithApiKeyWithUserId(Context currentContext, String apiKey, String userId) { return sharedInstanceWithApiKey(currentContext, apiKey, null, userId, false); } /** * Returns a shared instance of IterableApi. Updates the client data if an instance already exists. * Should be called whenever the app is opened. * Allows the IterableApi to be intialized with debugging enabled * @param currentContext The current context * @return stored instance of IterableApi * * @deprecated Initialize the SDK with {@link #initialize(Context, String, IterableConfig)} instead */ @Deprecated public static IterableApi sharedInstanceWithApiKeyWithUserId(Context currentContext, String apiKey, String userId, boolean debugMode) { return sharedInstanceWithApiKey(currentContext, apiKey, null, userId, debugMode); } /** * Returns a shared instance of IterableApi. Updates the client data if an instance already exists. * Should be called whenever the app is opened. * @param currentActivity The current activity * @param email The current email * @return stored instance of IterableApi * * @deprecated Initialize the SDK with {@link #initialize(Context, String, IterableConfig)} instead */ @Deprecated public static IterableApi sharedInstanceWithApiKey(Activity currentActivity, String apiKey, String email) { return sharedInstanceWithApiKey(currentActivity, apiKey, email, false); } /** * Returns a shared instance of IterableApi. Updates the client data if an instance already exists. * Should be called whenever the app is opened. * Allows the IterableApi to be intialized with debugging enabled * @param currentActivity The current activity * @param email The current email * @return stored instance of IterableApi */ @Deprecated public static IterableApi sharedInstanceWithApiKey(Activity currentActivity, String apiKey, String email, boolean debugMode) { return sharedInstanceWithApiKey((Context) currentActivity, apiKey, email, debugMode); } /** * Returns a shared instance of IterableApi. Updates the client data if an instance already exists. * Should be called whenever the app is opened. * @param currentContext The current context * @param email The current email * @return stored instance of IterableApi * * @deprecated Initialize the SDK with {@link #initialize(Context, String, IterableConfig)} instead */ @Deprecated public static IterableApi sharedInstanceWithApiKey(Context currentContext, String apiKey, String email) { return sharedInstanceWithApiKey(currentContext, apiKey, email, false); } /** * Returns a shared instance of IterableApi. Updates the client data if an instance already exists. * Should be called whenever the app is opened. * Allows the IterableApi to be intialized with debugging enabled * @param currentContext The current context * @param email The current email * @return stored instance of IterableApi * * @deprecated Initialize the SDK with {@link #initialize(Context, String, IterableConfig)} instead */ @Deprecated public static IterableApi sharedInstanceWithApiKey(Context currentContext, String apiKey, String email, boolean debugMode) { return sharedInstanceWithApiKey(currentContext, apiKey, email, null, debugMode); } private static IterableApi sharedInstanceWithApiKey(Context currentContext, String apiKey, String email, String userId, boolean debugMode) { sharedInstance.updateData(currentContext.getApplicationContext(), apiKey, email, userId); sharedInstance.setDebugMode(debugMode); sharedInstance.sdkCompatEnabled = true; return sharedInstance; } /** * Set user email used for API calls * Calling this or `setUserId:` is required before making any API calls. * * Note: This clears userId and persists the user email so you only need to call this once when the user logs in. * @param email User email */ public void setEmail(String email) { if (_email != null && _email.equals(email)) { return; } if (_email == null && _userId == null && email == null) { return; } onLogOut(); _email = email; _userId = null; storeEmailAndUserId(); onLogIn(); } /** * Set user ID used for API calls * Calling this or `setEmail:` is required before making any API calls. * * Note: This clears user email and persists the user ID so you only need to call this once when the user logs in. * @param userId User ID */ public void setUserId(String userId) { if (_userId != null && _userId.equals(userId)) { return; } if (_email == null && _userId == null && userId == null) { return; } onLogOut(); _email = null; _userId = userId; storeEmailAndUserId(); onLogIn(); } /** * Tracks a click on the uri if it is an iterable link. * @param uri the * @param onCallback Calls the callback handler with the destination location * or the original url if it is not a interable link. */ public static void getAndTrackDeeplink(String uri, IterableHelper.IterableActionHandler onCallback) { IterableDeeplinkManager.getAndTrackDeeplink(uri, onCallback); } /** * Handles an App Link * For Iterable links, it will track the click and retrieve the original URL, pass it to * {@link IterableUrlHandler} for handling * If it's not an Iterable link, it just passes the same URL to {@link IterableUrlHandler} * * Call this from {@link Activity#onCreate(Bundle)} and {@link Activity#onNewIntent(Intent)} * in your deep link handler activity * @param uri the URL obtained from {@link Intent#getData()} in your deep link * handler activity * @return */ public static boolean handleAppLink(String uri) { if (IterableDeeplinkManager.isIterableDeeplink(uri)) { IterableDeeplinkManager.getAndTrackDeeplink(uri, new IterableHelper.IterableActionHandler() { @Override public void execute(String originalUrl) { IterableAction action = IterableAction.actionOpenUrl(originalUrl); IterableActionRunner.executeAction(getInstance().getMainActivityContext(), action, IterableActionSource.APP_LINK); } }); return true; } else { IterableAction action = IterableAction.actionOpenUrl(uri); return IterableActionRunner.executeAction(getInstance().getMainActivityContext(), action, IterableActionSource.APP_LINK); } } /** * Debugging function to send API calls to different url endpoints. * @param url */ public static void overrideURLEndpointPath(String url) { IterableRequest.overrideUrl = url; } /** * Call onNewIntent to set the payload data and track pushOpens directly if * sharedInstanceWithApiKey was called with a Context rather than an Activity. * @deprecated Push opens are now tracked automatically. */ @Deprecated public void onNewIntent(Intent intent) { } /** * Returns whether or not the intent was sent from Iterable. */ public boolean isIterableIntent(Intent intent) { if (intent != null) { Bundle extras = intent.getExtras(); return (extras != null && extras.containsKey(IterableConstants.ITERABLE_DATA_KEY)); } return false; } /** * Registers a device token with Iterable. * Make sure {@link IterableConfig#pushIntegrationName} is set before calling this. * @param token Push token obtained from GCM or FCM */ public void registerDeviceToken(String token) { if (config.pushIntegrationName == null) { IterableLogger.e(TAG, "registerDeviceToken: pushIntegrationName is not set"); return; } registerDeviceToken(config.pushIntegrationName, token); } /** * Registers a device token with Iterable. * @param applicationName * @param token * @deprecated Call {@link #registerDeviceToken(String)} instead and specify the push * integration name in {@link IterableConfig#pushIntegrationName} */ @Deprecated public void registerDeviceToken(String applicationName, String token) { registerDeviceToken(applicationName, token, IterableConstants.MESSAGING_PLATFORM_FIREBASE); } /** * Registers a device token with Iterable. * @param applicationName * @param token * @param pushServicePlatform * @deprecated Call {@link #registerDeviceToken(String)} instead and specify the push * integration name in {@link IterableConfig#pushIntegrationName} */ @Deprecated public void registerDeviceToken(final String applicationName, final String token, final String pushServicePlatform) { registerDeviceToken(_email, _userId, applicationName, token, pushServicePlatform); } protected void registerDeviceToken(final String email, final String userId, final String applicationName, final String token, final String pushServicePlatform) { if (!IterableConstants.MESSAGING_PLATFORM_FIREBASE.equals(pushServicePlatform)) { IterableLogger.e(TAG, "registerDeviceToken: only MESSAGING_PLATFORM_FIREBASE is supported."); return; } if (token != null) { final Thread registrationThread = new Thread(new Runnable() { public void run() { registerDeviceToken(email, userId, applicationName, token, IterableConstants.MESSAGING_PLATFORM_FIREBASE, null); } }); registrationThread.start(); } } /** * Track an event. * @param eventName */ public void track(String eventName) { track(eventName, 0, 0, null); } /** * Track an event. * @param eventName * @param dataFields */ public void track(String eventName, JSONObject dataFields) { track(eventName, 0, 0, dataFields); } /** * Track an event. * @param eventName * @param campaignId * @param templateId */ public void track(String eventName, int campaignId, int templateId) { track(eventName, campaignId, templateId, null); } /** * Track an event. * @param eventName * @param campaignId * @param templateId * @param dataFields */ public void track(String eventName, int campaignId, int templateId, JSONObject dataFields) { if (!checkSDKInitialization()) { return; } JSONObject requestJSON = new JSONObject(); try { addEmailOrUserIdToJson(requestJSON); requestJSON.put(IterableConstants.KEY_EVENT_NAME, eventName); if (campaignId != 0) { requestJSON.put(IterableConstants.KEY_CAMPAIGN_ID, campaignId); } if (templateId != 0) { requestJSON.put(IterableConstants.KEY_TEMPLATE_ID, templateId); } requestJSON.put(IterableConstants.KEY_DATA_FIELDS, dataFields); sendPostRequest(IterableConstants.ENDPOINT_TRACK, requestJSON); } catch (JSONException e) { e.printStackTrace(); } } /** * Tracks a purchase. * @param total total purchase amount * @param items list of purchased items */ public void trackPurchase(double total, List<CommerceItem> items) { trackPurchase(total, items, null); } /** * Tracks a purchase. * @param total total purchase amount * @param items list of purchased items * @param dataFields a `JSONObject` containing any additional information to save along with the event */ public void trackPurchase(double total, List<CommerceItem> items, JSONObject dataFields) { if (!checkSDKInitialization()) { return; } JSONObject requestJSON = new JSONObject(); try { JSONArray itemsArray = new JSONArray(); for (CommerceItem item : items) { itemsArray.put(item.toJSONObject()); } JSONObject userObject = new JSONObject(); addEmailOrUserIdToJson(userObject); requestJSON.put(IterableConstants.KEY_USER, userObject); requestJSON.put(IterableConstants.KEY_ITEMS, itemsArray); requestJSON.put(IterableConstants.KEY_TOTAL, total); if (dataFields != null) { requestJSON.put(IterableConstants.KEY_DATA_FIELDS, dataFields); } sendPostRequest(IterableConstants.ENDPOINT_TRACK_PURCHASE, requestJSON); } catch (JSONException e) { e.printStackTrace(); } } public void sendPush(String email, int campaignId) { sendPush(email, campaignId, null, null); } /** * Sends a push campaign to an email address at the given time. * @param sendAt Schedule the message for up to 365 days in the future. * If set in the past, message is sent immediately. * Format is YYYY-MM-DD HH:MM:SS in UTC */ public void sendPush(String email, int campaignId, Date sendAt) { sendPush(email, campaignId, sendAt, null); } /** * Sends a push campaign to an email address. * @param email * @param campaignId * @param dataFields */ public void sendPush(String email, int campaignId, JSONObject dataFields) { sendPush(email, campaignId, null, dataFields); } /** * Sends a push campaign to an email address at the given time. * @param sendAt Schedule the message for up to 365 days in the future. * If set in the past, message is sent immediately. * Format is YYYY-MM-DD HH:MM:SS in UTC */ public void sendPush(String email, int campaignId, Date sendAt, JSONObject dataFields) { if (!checkSDKInitialization()) { return; } JSONObject requestJSON = new JSONObject(); try { requestJSON.put(IterableConstants.KEY_RECIPIENT_EMAIL, email); requestJSON.put(IterableConstants.KEY_CAMPAIGN_ID, campaignId); if (sendAt != null){ SimpleDateFormat sdf = new SimpleDateFormat(IterableConstants.DATEFORMAT); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); String dateString = sdf.format(sendAt); requestJSON.put(IterableConstants.KEY_SEND_AT, dateString); } sendPostRequest(IterableConstants.ENDPOINT_PUSH_TARGET, requestJSON); } catch (JSONException e) { e.printStackTrace(); } } /** * Updates the current user's email. * Also updates the current email in this IterableAPI instance if the API call was successful. * @param newEmail New email */ public void updateEmail(final String newEmail) { updateEmail(newEmail, null, null); } /** * Updates the current user's email. * Also updates the current email in this IterableAPI instance if the API call was successful. * @param newEmail New email * @param successHandler Success handler. Called when the server returns a success code. * @param failureHandler Failure handler. Called when the server call failed. */ public void updateEmail(final String newEmail, final IterableHelper.SuccessHandler successHandler, IterableHelper.FailureHandler failureHandler) { if (!checkSDKInitialization()) { IterableLogger.e(TAG, "The Iterable SDK must be initialized with email or userId before "+ "calling updateEmail"); if (failureHandler != null) { failureHandler.onFailure("The Iterable SDK must be initialized with email or "+ "userId before calling updateEmail", null); } return; } JSONObject requestJSON = new JSONObject(); try { if (_email != null) { requestJSON.put(IterableConstants.KEY_CURRENT_EMAIL, _email); } else { requestJSON.put(IterableConstants.KEY_CURRENT_USERID, _userId); } requestJSON.put(IterableConstants.KEY_NEW_EMAIL, newEmail); sendPostRequest(IterableConstants.ENDPOINT_UPDATE_EMAIL, requestJSON, new IterableHelper.SuccessHandler() { @Override public void onSuccess(JSONObject data) { if (_email != null) { _email = newEmail; } storeEmailAndUserId(); if (successHandler != null) { successHandler.onSuccess(data); } } }, failureHandler); } catch (JSONException e) { e.printStackTrace(); } } /** * Updates the current user. * @param dataFields */ public void updateUser(JSONObject dataFields) { if (!checkSDKInitialization()) { return; } JSONObject requestJSON = new JSONObject(); try { addEmailOrUserIdToJson(requestJSON); // Create the user by userId if it doesn't exist if (_email == null && _userId != null) { requestJSON.put(IterableConstants.KEY_PREFER_USER_ID, true); } requestJSON.put(IterableConstants.KEY_DATA_FIELDS, dataFields); sendPostRequest(IterableConstants.ENDPOINT_UPDATE_USER, requestJSON); } catch (JSONException e) { e.printStackTrace(); } } /** * Registers for push notifications. * Make sure the API is initialized with {@link IterableConfig#pushIntegrationName} defined, and * user email or user ID is set before calling this method. */ public void registerForPush() { if (!checkSDKInitialization()) { return; } if (config.pushIntegrationName == null) { IterableLogger.e(TAG, "registerForPush: pushIntegrationName is not set"); return; } IterablePushRegistrationData data = new IterablePushRegistrationData(_email, _userId, config.pushIntegrationName, IterablePushRegistrationData.PushRegistrationAction.ENABLE); new IterablePushRegistration().execute(data); } /** * Registers for push notifications. * @param pushIntegrationName * @param gcmProjectNumber * @deprecated Call {@link #registerForPush()} instead and specify the push * integration name in {@link IterableConfig#pushIntegrationName} */ @Deprecated public void registerForPush(String pushIntegrationName, String gcmProjectNumber) { registerForPush(pushIntegrationName, gcmProjectNumber, IterableConstants.MESSAGING_PLATFORM_FIREBASE); } /** * Registers for push notifications. * @param pushIntegrationName * @param projectNumber * @param pushServicePlatform * @deprecated Call {@link #registerForPush()} instead and specify the push * integration name in {@link IterableConfig#pushIntegrationName} */ @Deprecated public void registerForPush(String pushIntegrationName, String projectNumber, String pushServicePlatform) { if (!IterableConstants.MESSAGING_PLATFORM_FIREBASE.equals(pushServicePlatform)) { IterableLogger.e(TAG, "registerDeviceToken: only MESSAGING_PLATFORM_FIREBASE is supported."); return; } IterablePushRegistrationData data = new IterablePushRegistrationData(_email, _userId, pushIntegrationName, projectNumber, pushServicePlatform, IterablePushRegistrationData.PushRegistrationAction.ENABLE); new IterablePushRegistration().execute(data); } /** * Registers for push notifications. * @param pushIntegrationName * @deprecated Call {@link #registerForPush()} instead and specify the push * integration name in {@link IterableConfig#pushIntegrationName} */ @Deprecated public void registerForPush(String pushIntegrationName) { IterablePushRegistrationData data = new IterablePushRegistrationData(_email, _userId, pushIntegrationName, IterablePushRegistrationData.PushRegistrationAction.ENABLE); new IterablePushRegistration().execute(data); } /** * Disables the device from push notifications */ public void disablePush() { if (config.pushIntegrationName == null) { IterableLogger.e(TAG, "disablePush: pushIntegrationName is not set"); return; } IterablePushRegistrationData data = new IterablePushRegistrationData(_email, _userId, config.pushIntegrationName, IterablePushRegistrationData.PushRegistrationAction.DISABLE); new IterablePushRegistration().execute(data); } /** * Disables the device from push notifications * @param iterableAppId * @param gcmProjectNumber * @deprecated Call {@link #disablePush()} instead and specify the push * integration name in {@link IterableConfig#pushIntegrationName} */ @Deprecated public void disablePush(String iterableAppId, String gcmProjectNumber) { disablePush(iterableAppId, gcmProjectNumber, IterableConstants.MESSAGING_PLATFORM_FIREBASE); } /** * Disables the device from push notifications * @param iterableAppId * @param projectNumber * @param pushServicePlatform * @deprecated Call {@link #disablePush()} instead and specify the push * integration name in {@link IterableConfig#pushIntegrationName} */ @Deprecated public void disablePush(String iterableAppId, String projectNumber, String pushServicePlatform) { if (!IterableConstants.MESSAGING_PLATFORM_FIREBASE.equals(pushServicePlatform)) { IterableLogger.e(TAG, "registerDeviceToken: only MESSAGING_PLATFORM_FIREBASE is supported."); return; } IterablePushRegistrationData data = new IterablePushRegistrationData(_email, _userId, iterableAppId, projectNumber, pushServicePlatform, IterablePushRegistrationData.PushRegistrationAction.DISABLE); new IterablePushRegistration().execute(data); } /** * Updates the user subscription preferences. Passing in an empty array will clear the list, passing in null will not modify the list * @param emailListIds * @param unsubscribedChannelIds * @param unsubscribedMessageTypeIds */ public void updateSubscriptions(Integer[] emailListIds, Integer[] unsubscribedChannelIds, Integer[] unsubscribedMessageTypeIds) { if (!checkSDKInitialization()) { return; } JSONObject requestJSON = new JSONObject(); addEmailOrUserIdToJson(requestJSON); tryAddArrayToJSON(requestJSON, IterableConstants.KEY_EMAIL_LIST_IDS, emailListIds); tryAddArrayToJSON(requestJSON, IterableConstants.KEY_UNSUB_CHANNEL, unsubscribedChannelIds); tryAddArrayToJSON(requestJSON, IterableConstants.KEY_UNSUB_MESSAGE, unsubscribedMessageTypeIds); sendPostRequest(IterableConstants.ENDPOINT_UPDATE_USER_SUBS, requestJSON); } /** * Attempts to add an array as a JSONArray to a JSONObject * @param requestJSON * @param key * @param value */ void tryAddArrayToJSON(JSONObject requestJSON, String key, Object[] value) { if (requestJSON != null && key != null && value != null) try { JSONArray mJSONArray = new JSONArray(Arrays.asList(value)); requestJSON.put(key, mJSONArray); } catch (JSONException e) { IterableLogger.e(TAG, e.toString()); } } /** * In-app messages are now shown automatically, and you can customize it via {@link IterableInAppHandler} * If you need to show messages manually, see {@link IterableInAppManager#getMessages()} and * {@link IterableInAppManager#showMessage(IterableInAppMessage)} * * @deprecated Please check our migration guide here: * https://github.com/iterable/iterable-android-sdk/#migrating-in-app-messages-from-the-previous-version-of-the-sdk */ @Deprecated void spawnInAppNotification(final Context context, final IterableHelper.IterableActionHandler clickCallback) { } /** * Gets a list of InAppNotifications from Iterable; passes the result to the callback. * @deprecated Use {@link IterableInAppManager#getMessages()} instead * @param count the number of messages to fetch * @param onCallback */ @Deprecated public void getInAppMessages(int count, IterableHelper.IterableActionHandler onCallback) { if (!checkSDKInitialization()) { return; } JSONObject requestJSON = new JSONObject(); addEmailOrUserIdToJson(requestJSON); try { addEmailOrUserIdToJson(requestJSON); requestJSON.put(IterableConstants.ITERABLE_IN_APP_COUNT, count); requestJSON.put(IterableConstants.KEY_PLATFORM, IterableConstants.ITBL_PLATFORM_ANDROID); requestJSON.put(IterableConstants.ITBL_KEY_SDK_VERSION, IterableConstants.ITBL_KEY_SDK_VERSION_NUMBER); requestJSON.put(IterableConstants.KEY_PACKAGE_NAME, _applicationContext.getPackageName()); sendGetRequest(IterableConstants.ENDPOINT_GET_INAPP_MESSAGES, requestJSON, onCallback); } catch (JSONException e) { e.printStackTrace(); } } /** * Tracks an InApp open. * @param messageId */ public void trackInAppOpen(String messageId) { if (!checkSDKInitialization()) { return; } JSONObject requestJSON = new JSONObject(); try { addEmailOrUserIdToJson(requestJSON); requestJSON.put(IterableConstants.KEY_MESSAGE_ID, messageId); sendPostRequest(IterableConstants.ENDPOINT_TRACK_INAPP_OPEN, requestJSON); } catch (JSONException e) { e.printStackTrace(); } } /** * Tracks an InApp click. * @param messageId * @param clickedUrl */ public void trackInAppClick(String messageId, String clickedUrl) { if (!checkSDKInitialization()) { return; } JSONObject requestJSON = new JSONObject(); try { addEmailOrUserIdToJson(requestJSON); requestJSON.put(IterableConstants.KEY_MESSAGE_ID, messageId); requestJSON.put(IterableConstants.ITERABLE_IN_APP_CLICKED_URL, clickedUrl); sendPostRequest(IterableConstants.ENDPOINT_TRACK_INAPP_CLICK, requestJSON); } catch (JSONException e) { e.printStackTrace(); } } /** * Consumes an InApp message. * @param messageId */ public void inAppConsume(String messageId) { if (!checkSDKInitialization()) { return; } JSONObject requestJSON = new JSONObject(); try { addEmailOrUserIdToJson(requestJSON); requestJSON.put(IterableConstants.KEY_MESSAGE_ID, messageId); sendPostRequest(IterableConstants.ENDPOINT_INAPP_CONSUME, requestJSON); } catch (JSONException e) { e.printStackTrace(); } } //--------------------------------------------------------------------------------------- //endregion //region Package-Protected Fuctions //--------------------------------------------------------------------------------------- /** * Get user email * @return user email */ String getEmail() { return _email; } /** * Get user ID * @return user ID */ String getUserId() { return _userId; } //--------------------------------------------------------------------------------------- //endregion //region Protected Fuctions //--------------------------------------------------------------------------------------- /** * Set the notification icon with the given iconName. * @param context * @param iconName */ static void setNotificationIcon(Context context, String iconName) { SharedPreferences sharedPref = context.getSharedPreferences(IterableConstants.NOTIFICATION_ICON_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putString(IterableConstants.NOTIFICATION_ICON_NAME, iconName); editor.commit(); } /** * Returns the stored notification icon. * @param context * @return */ static String getNotificationIcon(Context context) { SharedPreferences sharedPref = context.getSharedPreferences(IterableConstants.NOTIFICATION_ICON_NAME, Context.MODE_PRIVATE); String iconName = sharedPref.getString(IterableConstants.NOTIFICATION_ICON_NAME, ""); return iconName; } protected void trackPushOpen(int campaignId, int templateId, String messageId) { trackPushOpen(campaignId, templateId, messageId, null); } /** * Tracks when a push notification is opened on device. * @param campaignId * @param templateId */ protected void trackPushOpen(int campaignId, int templateId, String messageId, JSONObject dataFields) { JSONObject requestJSON = new JSONObject(); try { if (dataFields == null) { dataFields = new JSONObject(); } addEmailOrUserIdToJson(requestJSON); requestJSON.put(IterableConstants.KEY_CAMPAIGN_ID, campaignId); requestJSON.put(IterableConstants.KEY_TEMPLATE_ID, templateId); requestJSON.put(IterableConstants.KEY_MESSAGE_ID, messageId); requestJSON.putOpt(IterableConstants.KEY_DATA_FIELDS, dataFields); sendPostRequest(IterableConstants.ENDPOINT_TRACK_PUSH_OPEN, requestJSON); } catch (JSONException e) { e.printStackTrace(); } } protected void disableToken(String email, String userId, String token) { disableToken(email, userId, token, null, null); } /** * Internal api call made from IterablePushRegistration after a registrationToken is obtained. * @param token */ protected void disableToken(String email, String userId, String token, IterableHelper.SuccessHandler onSuccess, IterableHelper.FailureHandler onFailure) { JSONObject requestJSON = new JSONObject(); try { requestJSON.put(IterableConstants.KEY_TOKEN, token); if (email != null) { requestJSON.put(IterableConstants.KEY_EMAIL, email); } else { requestJSON.put(IterableConstants.KEY_USER_ID, userId); } sendPostRequest(IterableConstants.ENDPOINT_DISABLE_DEVICE, requestJSON, onSuccess, onFailure); } catch (JSONException e) { e.printStackTrace(); } } /** * Registers the GCM registration ID with Iterable. * @param applicationName * @param token * @param pushServicePlatform * @param dataFields */ protected void registerDeviceToken(String email, String userId, String applicationName, String token, String pushServicePlatform, JSONObject dataFields) { if (!checkSDKInitialization()) { return; } if (token == null) { IterableLogger.e(TAG, "registerDeviceToken: token is null"); return; } if (applicationName == null) { IterableLogger.e(TAG, "registerDeviceToken: applicationName is null, check that pushIntegrationName is set in IterableConfig"); } JSONObject requestJSON = new JSONObject(); try { addEmailOrUserIdToJson(requestJSON); if (dataFields == null) { dataFields = new JSONObject(); } dataFields.put(IterableConstants.FIREBASE_TOKEN_TYPE, IterableConstants.MESSAGING_PLATFORM_FIREBASE); dataFields.put(IterableConstants.FIREBASE_COMPATIBLE, true); dataFields.put(IterableConstants.DEVICE_BRAND, Build.BRAND); //brand: google dataFields.put(IterableConstants.DEVICE_MANUFACTURER, Build.MANUFACTURER); //manufacturer: samsung dataFields.putOpt(IterableConstants.DEVICE_ADID, getAdvertisingId()); //ADID: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" dataFields.put(IterableConstants.DEVICE_SYSTEM_NAME, Build.DEVICE); //device name: toro dataFields.put(IterableConstants.DEVICE_SYSTEM_VERSION, Build.VERSION.RELEASE); //version: 4.0.4 dataFields.put(IterableConstants.DEVICE_MODEL, Build.MODEL); //device model: Galaxy Nexus dataFields.put(IterableConstants.DEVICE_SDK_VERSION, Build.VERSION.SDK_INT); //sdk version/api level: 15 dataFields.put(IterableConstants.DEVICE_ID, getDeviceId()); // Random UUID dataFields.put(IterableConstants.DEVICE_APP_PACKAGE_NAME, _applicationContext.getPackageName()); dataFields.put(IterableConstants.DEVICE_APP_VERSION, IterableUtil.getAppVersion(_applicationContext)); dataFields.put(IterableConstants.DEVICE_APP_BUILD, IterableUtil.getAppVersionCode(_applicationContext)); dataFields.put(IterableConstants.DEVICE_ITERABLE_SDK_VERSION, IterableConstants.ITBL_KEY_SDK_VERSION_NUMBER); dataFields.put(IterableConstants.DEVICE_NOTIFICATIONS_ENABLED, NotificationManagerCompat.from(_applicationContext).areNotificationsEnabled()); JSONObject device = new JSONObject(); device.put(IterableConstants.KEY_TOKEN, token); device.put(IterableConstants.KEY_PLATFORM, IterableConstants.MESSAGING_PLATFORM_GOOGLE); device.put(IterableConstants.KEY_APPLICATION_NAME, applicationName); device.putOpt(IterableConstants.KEY_DATA_FIELDS, dataFields); requestJSON.put(IterableConstants.KEY_DEVICE, device); // Create the user by userId if it doesn't exist if (email == null && userId != null) { requestJSON.put(IterableConstants.KEY_PREFER_USER_ID, true); } sendPostRequest(IterableConstants.ENDPOINT_REGISTER_DEVICE_TOKEN, requestJSON); } catch (JSONException e) { IterableLogger.e(TAG, "registerDeviceToken: exception", e); } } //--------------------------------------------------------------------------------------- //endregion //region Private Fuctions //--------------------------------------------------------------------------------------- /** * Updates the data for the current user. * @param context * @param apiKey * @param email * @param userId */ private void updateData(Context context, String apiKey, String email, String userId) { this._applicationContext = context; this._apiKey = apiKey; this._email = email; this._userId = userId; } private boolean isInitialized() { return _apiKey != null && (_email != null || _userId != null); } private boolean checkSDKInitialization() { if (!isInitialized()) { IterableLogger.e(TAG, "Iterable SDK must be initialized with an API key and user email/userId before calling SDK methods"); return false; } return true; } private SharedPreferences getPreferences() { return _applicationContext.getSharedPreferences(IterableConstants.SHARED_PREFS_FILE, Context.MODE_PRIVATE); } /** * Sends the POST request to Iterable. * Performs network operations on an async thread instead of the main thread. * @param resourcePath * @param json */ void sendPostRequest(String resourcePath, JSONObject json) { IterableApiRequest request = new IterableApiRequest(_apiKey, resourcePath, json, IterableApiRequest.POST, null, null); new IterableRequest().execute(request); } void sendPostRequest(String resourcePath, JSONObject json, IterableHelper.SuccessHandler onSuccess, IterableHelper.FailureHandler onFailure) { IterableApiRequest request = new IterableApiRequest(_apiKey, resourcePath, json, IterableApiRequest.POST, onSuccess, onFailure); new IterableRequest().execute(request); } /** * Sends a GET request to Iterable. * Performs network operations on an async thread instead of the main thread. * @param resourcePath * @param json */ void sendGetRequest(String resourcePath, JSONObject json, IterableHelper.IterableActionHandler onCallback) { IterableApiRequest request = new IterableApiRequest(_apiKey, resourcePath, json, IterableApiRequest.GET, onCallback); new IterableRequest().execute(request); } /** * Adds the current email or userID to the json request. * @param requestJSON */ private void addEmailOrUserIdToJson(JSONObject requestJSON) { try { if (_email != null) { requestJSON.put(IterableConstants.KEY_EMAIL, _email); } else { requestJSON.put(IterableConstants.KEY_USER_ID, _userId); } } catch (JSONException e) { e.printStackTrace(); } } /** * Gets the advertisingId if available * @return */ private String getAdvertisingId() { String advertisingId = null; try { Class adClass = Class.forName("com.google.android.gms.ads.identifier.AdvertisingIdClient"); if (adClass != null) { AdvertisingIdClient.Info advertisingIdInfo = AdvertisingIdClient.getAdvertisingIdInfo(_applicationContext); if (advertisingIdInfo != null) { advertisingId = advertisingIdInfo.getId(); } } } catch (ClassNotFoundException e) { IterableLogger.d(TAG, "ClassNotFoundException: Can't track ADID. " + "Check that play-services-ads is added to the dependencies.", e); } catch (Exception e) { IterableLogger.w(TAG, e.getMessage()); } return advertisingId; } private String getDeviceId() { if (_deviceId == null) { _deviceId = getPreferences().getString(IterableConstants.SHARED_PREFS_DEVICEID_KEY, null); if (_deviceId == null) { _deviceId = UUID.randomUUID().toString(); getPreferences().edit().putString(IterableConstants.SHARED_PREFS_DEVICEID_KEY, _deviceId).apply(); } } return _deviceId; } private void storeEmailAndUserId() { try { SharedPreferences.Editor editor = getPreferences().edit(); editor.putString(IterableConstants.SHARED_PREFS_EMAIL_KEY, _email); editor.putString(IterableConstants.SHARED_PREFS_USERID_KEY, _userId); editor.commit(); } catch (Exception e) { IterableLogger.e(TAG, "Error while persisting email/userId", e); } } private void retrieveEmailAndUserId() { try { SharedPreferences prefs = getPreferences(); _email = prefs.getString(IterableConstants.SHARED_PREFS_EMAIL_KEY, null); _userId = prefs.getString(IterableConstants.SHARED_PREFS_USERID_KEY, null); } catch (Exception e) { IterableLogger.e(TAG, "Error while retrieving email/userId", e); } } private void onLogOut() { if (config.autoPushRegistration && isInitialized()) { disablePush(); } } private void onLogIn() { if (config.autoPushRegistration && isInitialized()) { registerForPush(); } getInAppManager().syncInApp(); } private boolean getDDLChecked() { return getPreferences().getBoolean(IterableConstants.SHARED_PREFS_DDL_CHECKED_KEY, false); } private void setDDLChecked(boolean value) { getPreferences().edit().putBoolean(IterableConstants.SHARED_PREFS_DDL_CHECKED_KEY, value).apply(); } private void checkForDeferredDeeplink() { if (!config.checkForDeferredDeeplink) { return; } try { if (getDDLChecked()) { return; } JSONObject requestJSON = DeviceInfo.createDeviceInfo(_applicationContext).toJSONObject(); IterableApiRequest request = new IterableApiRequest(_apiKey, IterableConstants.BASE_URL_LINKS, IterableConstants.ENDPOINT_DDL_MATCH, requestJSON, IterableApiRequest.POST, new IterableHelper.SuccessHandler() { @Override public void onSuccess(JSONObject data) { handleDDL(data); } }, new IterableHelper.FailureHandler() { @Override public void onFailure(String reason, JSONObject data) { IterableLogger.e(TAG, "Error while checking deferred deep link: " + reason + ", response: " + data); } }); new IterableRequest().execute(request); } catch (Exception e) { IterableLogger.e(TAG, "Error while checking deferred deep link", e); } } private void handleDDL(JSONObject response) { IterableLogger.d(TAG, "handleDDL: " + response); try { MatchFpResponse matchFpResponse = MatchFpResponse.fromJSONObject(response); if (matchFpResponse.isMatch) { IterableAction action = IterableAction.actionOpenUrl(matchFpResponse.destinationUrl); IterableActionRunner.executeAction(getMainActivityContext(), action, IterableActionSource.APP_LINK); } } catch (JSONException e) { IterableLogger.e(TAG, "Error while handling deferred deep link", e); } setDDLChecked(true); } //--------------------------------------------------------------------------------------- //endregion }
Remove dependency on AdvertisingIdClient, use reflection instead
iterableapi/src/main/java/com/iterable/iterableapi/IterableApi.java
Remove dependency on AdvertisingIdClient, use reflection instead
<ide><path>terableapi/src/main/java/com/iterable/iterableapi/IterableApi.java <ide> import android.support.annotation.VisibleForTesting; <ide> import android.support.v4.app.NotificationManagerCompat; <ide> <del>import com.google.android.gms.ads.identifier.AdvertisingIdClient; <ide> import com.iterable.iterableapi.ddl.DeviceInfo; <ide> import com.iterable.iterableapi.ddl.MatchFpResponse; <ide> <ide> try { <ide> Class adClass = Class.forName("com.google.android.gms.ads.identifier.AdvertisingIdClient"); <ide> if (adClass != null) { <del> AdvertisingIdClient.Info advertisingIdInfo = AdvertisingIdClient.getAdvertisingIdInfo(_applicationContext); <add> Object advertisingIdInfo = adClass.getMethod("getAdvertisingIdInfo", Context.class).invoke(null, _applicationContext); <ide> if (advertisingIdInfo != null) { <del> advertisingId = advertisingIdInfo.getId(); <add> advertisingId = (String) advertisingIdInfo.getClass().getMethod("getId").invoke(advertisingIdInfo); <ide> } <ide> } <ide> } catch (ClassNotFoundException e) {
JavaScript
mit
3f064009025e780595670faecba107ca3cdcab61
0
demetris-manikas/com.crypho.plugins.securestorage,Crypho/com.crypho.plugins.securestorage,Crypho/com.crypho.plugins.securestorage,Crypho/cordova-plugin-secure-storage,yyfearth/cordova-plugin-secure-storage,Crypho/cordova-plugin-secure-storage,yyfearth/cordova-plugin-secure-storage,demetris-manikas/com.crypho.plugins.securestorage
var SecureStorage, SecureStorageiOS, SecureStorageAndroid, SecureStorageWindows, SecureStorageBrowser; var sjcl_ss = cordova.require('cordova-plugin-secure-storage.sjcl_ss'); var _AES_PARAM = { ks: 256, ts: 128, mode: 'ccm', cipher: 'aes' }; var _checkCallbacks = function (success, error) { if (typeof success != 'function') { throw new Error('SecureStorage failure: success callback parameter must be a function'); } if (typeof error != 'function') { throw new Error('SecureStorage failure: error callback parameter must be a function'); } }; //Taken from undescore.js var _isString = function isString(x) { return Object.prototype.toString.call(x) === '[object String]'; }; var _checkIsString = function(value){ if (!_isString(value)) { throw new Error('Value is not a String'); } }; var _merge_options = function (defaults, options){ var res = {}; var attrname; for (attrname in defaults) { res[attrname] = defaults[attrname]; } for (attrname in options) { if (res.hasOwnProperty(attrname)) { res[attrname] = options[attrname]; } else { throw new Error('SecureStorage failure: invalid option ' + attrname); } } return res; }; /** * Helper method to execute Cordova native method * * @param {String} nativeMethodName Method to execute. * @param {Array} args Execution arguments. * @param {Function} success Called when returning successful result from an action. * @param {Function} error Called when returning error result from an action. * */ var _executeNativeMethod = function (success, error, nativeMethodName, args) { var fail; // args checking _checkCallbacks(success, error); // By convention a failure callback should always receive an instance // of a JavaScript Error object. fail = function(err) { // provide default message if no details passed to callback if (typeof err === 'undefined') { error(new Error('Error occured while executing native method.')); } else { // wrap string to Error instance if necessary error(_isString(err) ? new Error(err) : err); } }; cordova.exec(success, fail, 'SecureStorage', nativeMethodName, args); }; SecureStorageiOS = function (success, error, service) { this.service = service; setTimeout(success, 0); return this; }; SecureStorageiOS.prototype = { get: function (success, error, key) { try { _executeNativeMethod(success, error, 'get', [this.service, key]); } catch (e) { error(e); } }, set: function (success, error, key, value) { try { _checkIsString(value); _executeNativeMethod(success, error, 'set', [this.service, key, value]); } catch (e) { error(e); } }, remove: function (success, error, key) { try { _executeNativeMethod(success, error, 'remove', [this.service, key]); } catch (e) { error(e); } }, keys: function (success, error) { try { _executeNativeMethod(success, error, 'keys', [this.service]); } catch (e) { error(e); } }, clear: function (success, error) { try { _executeNativeMethod(success, error, 'clear', [this.service]); } catch (e) { error(e); } } }; // SecureStorage for Windows web interface and proxy parameters are the same as on iOS // so we don't create own definition for Windows and simply re-use iOS SecureStorageWindows = SecureStorageiOS; SecureStorageAndroid = function (success, error, service, options) { var self = this; if (options) { this.options = _merge_options(this.options, options); } this.service = service; try { _executeNativeMethod( function (native_aes_supported) { var checkMigrateToNativeAES; checkMigrateToNativeAES = function () { self.options.native = native_aes_supported && self.options.native; if (!self.options.native){ success(); } else { _executeNativeMethod( function () { success(); }, function() { self._migrate_to_native_aes(success); }, 'fetch', ['_SS_MIGRATED_TO_NATIVE'] ); } }; if (self.options.migrateLocalStorage){ self._migrate_to_native_storage(checkMigrateToNativeAES); } else { _executeNativeMethod( function () { checkMigrateToNativeAES(); }, function() { self._migrate_to_native_storage(checkMigrateToNativeAES); }, 'fetch', ['_SS_MIGRATED_TO_NATIVE_STORAGE'] ); } }, error, 'init', [this.service] ); } catch (e) { error(e); } return this; }; SecureStorageAndroid.prototype = { options: { native: true, migrateLocalStorage: false }, get: function (success, error, key) { try { if (this.options.native) { this._native_get(success, error, key); } else { this._sjcl_get(success, error, key); } } catch (e) { error(e); } }, set: function (success, error, key, value) { try { _checkIsString(value); if (this.options.native) { this._native_set(success, error, key, value); } else { this._sjcl_set(success, error, key, value); } } catch (e) { error(e); } }, keys: function (success, error) { try { _executeNativeMethod( function (ret) { var i, len = ret.length, keys = []; for (i = 0; i < len; ++i) { if (ret[i] && ret[i].slice(0, 4) === '_SS_') { keys.push(ret[i].slice(4)); } } success(keys); }, error, 'keys', [] ); } catch (e) { error(e); } }, remove: function (success, error, key) { try { _executeNativeMethod( function () { success(key); }, error, 'remove', ['_SS_' + key] ); } catch (e) { error(e); } }, secureDevice: function (success, error) { try { _executeNativeMethod( success, error, 'secureDevice', [] ); } catch (e) { error(e); } }, clear: function (success, error) { try { _executeNativeMethod( success, error, 'clear', [] ); } catch (e) { error(e); } }, _fetch: function (success, error, key) { _executeNativeMethod( function (value) { success(value); }, error, 'fetch', ['_SS_' + key] ); }, _sjcl_get: function (success, error, key) { var payload; _executeNativeMethod( function (value) { payload = JSON.parse(value); _executeNativeMethod( function (AESKey) { var value, AESKeyBits; try { AESKeyBits = sjcl_ss.codec.base64.toBits(AESKey); value = sjcl_ss.decrypt(AESKeyBits, payload.value); success(value); } catch (e) { error(e); } }, error, 'decrypt_rsa', [payload.key] ); }, error, 'fetch', ['_SS_' + key] ); }, _sjcl_set: function (success, error, key, value) { var AESKey, encValue; AESKey = sjcl_ss.random.randomWords(8); _AES_PARAM.adata = this.service; encValue = sjcl_ss.encrypt(AESKey, value, _AES_PARAM); // Encrypt the AES key _executeNativeMethod( function (encKey) { _executeNativeMethod( function () { success(key); }, error, 'store', ['_SS_' + key, JSON.stringify({key: encKey, value: encValue})] ); }, error, 'encrypt_rsa', [sjcl_ss.codec.base64.fromBits(AESKey)] ); }, _native_get: function (success, error, key) { _executeNativeMethod( success, error, 'get', ['_SS_' + key] ); }, _native_set: function (success, error, key, value) { _executeNativeMethod( function () { success(key); }, error, 'set', ['_SS_' + key, value, this.service] ); }, _migrate_to_native_storage: function (success) { var key; var secureStorageData = []; var entriesCnt = 0; var entriesProcessed = 0; var entryMigrated; var migrated; var migrateEntry; migrated = function () { _executeNativeMethod( function () { success(); }, function () { }, 'store', ['_SS_MIGRATED_TO_NATIVE_STORAGE', '1'] ); }; entryMigrated = function () { entriesProcessed++; if (entriesProcessed === entriesCnt) { migrated(); } }; migrateEntry = function (key, value) { _executeNativeMethod( function () { localStorage.removeItem(key); entryMigrated(); }, function () { }, 'store', [key, value] ); }; for (key in localStorage) { if (localStorage.hasOwnProperty(key) && key.indexOf('_SS_') === 0) { entriesCnt++; secureStorageData[key] = localStorage.getItem(key); } } if (entriesCnt === 0) { migrated(); } else { for (key in secureStorageData) { if (secureStorageData.hasOwnProperty(key)) { migrateEntry(key, secureStorageData[key]); } } } }, _migrate_to_native_aes: function (success) { var self = this; var keysCnt, keysProcessed; var keyProcessed; var migrated; var migrateKey; var i; migrated = function () { _executeNativeMethod( function () { success(); }, function () { }, 'store', ['_SS_MIGRATED_TO_NATIVE', '1'] ); }; keyProcessed = function () { keysProcessed++; if (keysProcessed === keysCnt) { migrated(); } }; migrateKey = function (key) { var payload; _executeNativeMethod( function (value) { payload = JSON.parse(value); if (!payload.native) { self._sjcl_get( function (value) { self._native_set( function () { keyProcessed(); }, function () {}, key.replace('_SS_', ''), value ); }, function () {}, key.replace('_SS_', '') ); } else { keyProcessed(); } }, function () { }, 'fetch', [key] ); }; _executeNativeMethod( function (keys) { keysProcessed = 0; keysCnt = keys.length; if (keysCnt === 0) { migrated(); } else { for (i = 0; i < keysCnt; i++) { migrateKey(keys[i]); } } }, function () { }, 'keys', [] ); } }; SecureStorageBrowser = function (success, error, service) { this.service = service; setTimeout(success, 0); return this; }; SecureStorageBrowser.prototype = { get: function (success, error, key) { var value; try { _checkCallbacks(success, error); value = localStorage.getItem('_SS_' + key); if (!value) { error(new Error('Key "' + key + '" not found.')); } else { success(value); } } catch (e) { error(e); } }, set: function (success, error, key, value) { try { _checkIsString(value); _checkCallbacks(success, error); localStorage.setItem('_SS_' + key, value); success(key); } catch (e) { error(e); } }, remove: function (success, error, key) { localStorage.removeItem('_SS_' + key); success(key); }, keys: function (success, error) { var i, len, key, keys = []; try { _checkCallbacks(success, error); for (i = 0, len = localStorage.length; i < len; ++i) { key = localStorage.key(i); if ('_SS_' === key.slice(0, 4)) { keys.push(key.slice(4)); } } success(keys); } catch (e) { error(e); } }, clear: function (success, error) { var i, key; try { _checkCallbacks(success, error); i = localStorage.length; while (i-- > 0) { key = localStorage.key(i); if (key && '_SS_' === key.slice(0, 4)) { localStorage.removeItem(key); } } success(); } catch (e) { error(e); } } }; switch (cordova.platformId) { case 'ios': SecureStorage = SecureStorageiOS; break; case 'android': SecureStorage = SecureStorageAndroid; break; case 'windows': SecureStorage = SecureStorageWindows; break; case 'browser': SecureStorage = SecureStorageBrowser; break; default: SecureStorage = null; } if (!cordova.plugins) { cordova.plugins = {}; } if (!cordova.plugins.SecureStorage) { cordova.plugins.SecureStorage = SecureStorage; } if (typeof module != 'undefined' && module.exports) { module.exports = SecureStorage; }
www/securestorage.js
var SecureStorage, SecureStorageiOS, SecureStorageAndroid, SecureStorageWindows, SecureStorageBrowser; var sjcl_ss = cordova.require('cordova-plugin-secure-storage.sjcl_ss'); var _AES_PARAM = { ks: 256, ts: 128, mode: 'ccm', cipher: 'aes' }; var _checkCallbacks = function (success, error) { if (typeof success != 'function') { throw new Error('SecureStorage failure: success callback parameter must be a function'); } if (typeof error != 'function') { throw new Error('SecureStorage failure: error callback parameter must be a function'); } }; //Taken from undescore.js var _isString = function isString(x) { return Object.prototype.toString.call(x) === '[object String]'; }; var _checkIsString = function(value){ if (!_isString(value)) { throw new Error('Value is not a String'); } }; var _merge_options = function (defaults, options){ var res = {}; var attrname; for (attrname in defaults) { res[attrname] = defaults[attrname]; } for (attrname in options) { if (res.hasOwnProperty(attrname)) { res[attrname] = options[attrname]; } else { throw new Error('SecureStorage failure: invalid option ' + attrname); } } return res; }; /** * Helper method to execute Cordova native method * * @param {String} nativeMethodName Method to execute. * @param {Array} args Execution arguments. * @param {Function} success Called when returning successful result from an action. * @param {Function} error Called when returning error result from an action. * */ var _executeNativeMethod = function (success, error, nativeMethodName, args) { var fail; // args checking _checkCallbacks(success, error); // By convention a failure callback should always receive an instance // of a JavaScript Error object. fail = function(err) { // provide default message if no details passed to callback if (typeof err === 'undefined') { error(new Error('Error occured while executing native method.')); } else { // wrap string to Error instance if necessary error(_isString(err) ? new Error(err) : err); } }; cordova.exec(success, fail, 'SecureStorage', nativeMethodName, args); }; SecureStorageiOS = function (success, error, service) { this.service = service; setTimeout(success, 0); return this; }; SecureStorageiOS.prototype = { get: function (success, error, key) { try { _executeNativeMethod(success, error, 'get', [this.service, key]); } catch (e) { error(e); } }, set: function (success, error, key, value) { try { _checkIsString(value); _executeNativeMethod(success, error, 'set', [this.service, key, value]); } catch (e) { error(e); } }, remove: function (success, error, key) { try { _executeNativeMethod(success, error, 'remove', [this.service, key]); } catch (e) { error(e); } }, keys: function (success, error) { try { _executeNativeMethod(success, error, 'keys', [this.service]); } catch (e) { error(e); } }, clear: function (success, error) { try { _executeNativeMethod(success, error, 'clear', [this.service]); } catch (e) { error(e); } } }; // SecureStorage for Windows web interface and proxy parameters are the same as on iOS // so we don't create own definition for Windows and simply re-use iOS SecureStorageWindows = SecureStorageiOS; SecureStorageAndroid = function (success, error, service, options) { var self = this; if (options) { this.options = _merge_options(this.options, options); } this.service = service; try { _executeNativeMethod( function (native_aes_supported) { var checkMigrateToNativeAES; checkMigrateToNativeAES = function () { self.options.native = native_aes_supported && self.options.native; if (!self.options.native){ success(); } else { _executeNativeMethod( function () { success(); }, function() { self._migrate_to_native_aes(success); }, 'fetch', ['_SS_MIGRATED_TO_NATIVE'] ); } }; if (self.options.migrateLocalStorage){ self._migrate_to_native_storage(checkMigrateToNativeAES); } else { _executeNativeMethod( function () { checkMigrateToNativeAES(); }, function() { self._migrate_to_native_storage(checkMigrateToNativeAES); }, 'fetch', ['_SS_MIGRATED_TO_NATIVE_STORAGE'] ); } }, error, 'init', [this.service] ); } catch (e) { error(e); } return this; }; SecureStorageAndroid.prototype = { options: { native: true, migrateLocalStorage: false }, get: function (success, error, key) { try { if (this.options.native) { this._native_get(success, error, key); } else { this._sjcl_get(success, error, key); } } catch (e) { error(e); } }, set: function (success, error, key, value) { try { _checkIsString(value); if (this.options.native) { this._native_set(success, error, key, value); } else { this._sjcl_set(success, error, key, value); } } catch (e) { error(e); } }, keys: function (success, error) { try { _executeNativeMethod( function (ret) { var i, len = ret.length, keys = []; for (i = 0; i < len; ++i) { if (ret[i] && ret[i].slice(0, 4) === '_SS_') { keys.push(ret[i].slice(4)); } } success(keys); }, error, 'keys', [] ); } catch (e) { error(e); } }, remove: function (success, error, key) { try { _executeNativeMethod( function () { success(key); }, error, 'remove', ['_SS_' + key] ); } catch (e) { error(e); } }, secureDevice: function (success, error) { try { _executeNativeMethod( success, error, 'secureDevice', [] ); } catch (e) { error(e); } }, clear: function (success, error) { try { _executeNativeMethod( success, error, 'clear', [] ); } catch (e) { error(e); } }, _fetch: function (success, error, key) { _executeNativeMethod( function (value) { success(value); }, error, 'fetch', ['_SS_' + key] ); }, _sjcl_get: function (success, error, key) { var payload; _executeNativeMethod( function (value) { payload = JSON.parse(value); _executeNativeMethod( function (AESKey) { var value, AESKeyBits; try { AESKeyBits = sjcl_ss.codec.base64.toBits(AESKey); value = sjcl_ss.decrypt(AESKeyBits, payload.value); success(value); } catch (e) { error(e); } }, error, 'decrypt_rsa', [payload.key] ); }, error, 'fetch', ['_SS_' + key] ); }, _sjcl_set: function (success, error, key, value) { var AESKey, encValue; AESKey = sjcl_ss.random.randomWords(8); _AES_PARAM.adata = this.service; encValue = sjcl_ss.encrypt(AESKey, value, _AES_PARAM); // Encrypt the AES key _executeNativeMethod( function (encKey) { _executeNativeMethod( function () { success(key); }, error, 'store', ['_SS_' + key, JSON.stringify({key: encKey, value: encValue})] ); }, error, 'encrypt_rsa', [sjcl_ss.codec.base64.fromBits(AESKey)] ); }, _native_get: function (success, error, key) { _executeNativeMethod( success, error, 'get', ['_SS_' + key] ); }, _native_set: function (success, error, key, value) { _executeNativeMethod( function () { success(key); }, error, 'set', ['_SS_' + key, value, this.service] ); }, _migrate_to_native_storage: function (success) { var key; var secureStorageData = []; var entriesCnt; var entriesProcessed = 0; var entryMigrated; var migrated; var migrateEntry; migrated = function () { _executeNativeMethod( function () { success(); }, function () { }, 'store', ['_SS_MIGRATED_TO_NATIVE_STORAGE', '1'] ); }; entryMigrated = function () { entriesProcessed++; if (entriesProcessed === entriesCnt) { migrated(); } }; migrateEntry = function (key, value) { _executeNativeMethod( function () { localStorage.removeItem(key); entryMigrated(); }, function () { }, 'store', [key, value] ); }; for (key in localStorage) { if (localStorage.hasOwnProperty(key) && key.indexOf('_SS_') === 0) { secureStorageData[key] = localStorage.getItem(key); } } entriesCnt = secureStorageData.length; if (entriesCnt === 0) { migrated(); } for (key in secureStorageData) { if (secureStorageData.hasOwnProperty(key)) { migrateEntry(key, secureStorageData[key]); } } }, _migrate_to_native_aes: function (success) { var self = this; var keysCnt, keysProcessed; var keyProcessed; var migrated; var migrateKey; var i; migrated = function () { _executeNativeMethod( function () { success(); }, function () { }, 'store', ['_SS_MIGRATED_TO_NATIVE', '1'] ); }; keyProcessed = function () { keysProcessed++; if (keysProcessed === keysCnt) { migrated(); } }; migrateKey = function (key) { var payload; _executeNativeMethod( function (value) { payload = JSON.parse(value); if (!payload.native) { self._sjcl_get( function (value) { self._native_set( function () { keyProcessed(); }, function () {}, key.replace('_SS_', ''), value ); }, function () {}, key.replace('_SS_', '') ); } else { keyProcessed(); } }, function () { }, 'fetch', [key] ); }; _executeNativeMethod( function (keys) { keysProcessed = 0; keysCnt = keys.length; if (keysCnt === 0) { migrated(); } else { for (i = 0; i < keysCnt; i++) { migrateKey(keys[i]); } } }, function () { }, 'keys', [] ); } }; SecureStorageBrowser = function (success, error, service) { this.service = service; setTimeout(success, 0); return this; }; SecureStorageBrowser.prototype = { get: function (success, error, key) { var value; try { _checkCallbacks(success, error); value = localStorage.getItem('_SS_' + key); if (!value) { error(new Error('Key "' + key + '" not found.')); } else { success(value); } } catch (e) { error(e); } }, set: function (success, error, key, value) { try { _checkIsString(value); _checkCallbacks(success, error); localStorage.setItem('_SS_' + key, value); success(key); } catch (e) { error(e); } }, remove: function (success, error, key) { localStorage.removeItem('_SS_' + key); success(key); }, keys: function (success, error) { var i, len, key, keys = []; try { _checkCallbacks(success, error); for (i = 0, len = localStorage.length; i < len; ++i) { key = localStorage.key(i); if ('_SS_' === key.slice(0, 4)) { keys.push(key.slice(4)); } } success(keys); } catch (e) { error(e); } }, clear: function (success, error) { var i, key; try { _checkCallbacks(success, error); i = localStorage.length; while (i-- > 0) { key = localStorage.key(i); if (key && '_SS_' === key.slice(0, 4)) { localStorage.removeItem(key); } } success(); } catch (e) { error(e); } } }; switch (cordova.platformId) { case 'ios': SecureStorage = SecureStorageiOS; break; case 'android': SecureStorage = SecureStorageAndroid; break; case 'windows': SecureStorage = SecureStorageWindows; break; case 'browser': SecureStorage = SecureStorageBrowser; break; default: SecureStorage = null; } if (!cordova.plugins) { cordova.plugins = {}; } if (!cordova.plugins.SecureStorage) { cordova.plugins.SecureStorage = SecureStorage; } if (typeof module != 'undefined' && module.exports) { module.exports = SecureStorage; }
fix: migration to sharedPreferences for Android
www/securestorage.js
fix: migration to sharedPreferences for Android
<ide><path>ww/securestorage.js <ide> _migrate_to_native_storage: function (success) { <ide> var key; <ide> var secureStorageData = []; <del> var entriesCnt; <add> var entriesCnt = 0; <ide> var entriesProcessed = 0; <ide> var entryMigrated; <ide> var migrated; <ide> <ide> for (key in localStorage) { <ide> if (localStorage.hasOwnProperty(key) && key.indexOf('_SS_') === 0) { <add> entriesCnt++; <ide> secureStorageData[key] = localStorage.getItem(key); <ide> } <ide> } <del> entriesCnt = secureStorageData.length; <ide> if (entriesCnt === 0) { <ide> migrated(); <del> } <del> for (key in secureStorageData) { <del> if (secureStorageData.hasOwnProperty(key)) { <del> migrateEntry(key, secureStorageData[key]); <add> } else { <add> for (key in secureStorageData) { <add> if (secureStorageData.hasOwnProperty(key)) { <add> migrateEntry(key, secureStorageData[key]); <add> } <ide> } <ide> } <ide> },
JavaScript
mpl-2.0
67810673425e4e5762435487376fe70715533d6d
0
slidewiki/slidewiki-platform,slidewiki/slidewiki-platform,slidewiki/slidewiki-platform
import PropTypes from 'prop-types'; import React from 'react'; import {NavLink} from 'fluxible-router'; import {defineMessages} from 'react-intl'; import {Microservices} from '../../../../configs/microservices'; class UserMenu extends React.Component { constructor(props){ super(props); this.styles = {'backgroundColor': '#2185D0', 'color': 'white'}; this.messages = this.getIntlMessages(); } getIntlMessages(){ return defineMessages({ myDecks: { id: 'UserMenu.myDecks', defaultMessage: 'My Decks' }, ownedDecks: { id: 'UserMenu.ownedDecks', defaultMessage: 'Owned Decks' }, sharedDecks: { id: 'UserMenu.sharedDecks', defaultMessage: 'Shared Decks' }, collections: { id: 'UserMenu.collections', defaultMessage: 'Playlists' }, ownedCollections: { id: 'UserMenu.ownedCollections', defaultMessage: 'Owned Playlists' }, recommendedDecks: { id: 'UserMenu.recommendedDecks', defaultMessage: 'Recommended Decks' }, stats: { id: 'UserMenu.stats', defaultMessage: 'User Stats' }, }); } render() { let deckRecommendationsMsg = this.context.intl.formatMessage(this.messages.recommendedDecks); let deckRecommendationNavLink = ( <NavLink className="item" href={'/user/' + this.props.user.uname + '/recommendations'} activeStyle={this.styles}> <p><i className="icons"> <i className="yellow open folder icon"></i> <i className="corner thumbs up icon"></i> </i> {deckRecommendationsMsg}</p> </NavLink> ); let decksMsg = this.context.intl.formatMessage(this.messages.myDecks); let sharedDecksMsg = this.context.intl.formatMessage(this.messages.sharedDecks); let deckCollectionsMsg = this.context.intl.formatMessage(this.messages.collections); let userStatsMsg = this.context.intl.formatMessage(this.messages.stats); //Remove link if it's not user's own page //Until recommendation service is properly integrated into the system, show only on experimental if(this.props.user.uname !== this.props.loggedinuser || Microservices.recommendation === undefined || Microservices.recommendation.uri !== 'http://slidewiki.imp.bg.ac.rs') { decksMsg = this.context.intl.formatMessage(this.messages.ownedDecks); deckCollectionsMsg = this.context.intl.formatMessage(this.messages.ownedCollections); deckRecommendationNavLink = ''; } return ( <div role="navigation"> <div className="ui vertical fluid menu" role="menu"> <NavLink className="item" href={'/user/' + this.props.user.uname } activeStyle={this.styles} role="menuitem"> <p><i className="yellow icon open folder"/> {decksMsg}</p> </NavLink> { (this.props.user.uname === this.props.loggedinuser) && <NavLink className="item" href={'/user/' + this.props.user.uname + '/decks/shared'} activeStyle={this.styles} role="menuitem"> <p><i className="icons"> <i className="yellow open folder icon"></i> <i className="corner users icon"></i> </i> {sharedDecksMsg}</p> </NavLink> } {deckRecommendationNavLink} <NavLink className="item" href={'/user/' + this.props.user.uname + '/playlists'} activeStyle={this.styles} role="menuitem"> <p><i className="icon grid layout"/> {deckCollectionsMsg}</p> </NavLink> {(this.props.user.uname === this.props.loggedinuser) && <NavLink className="item" href={'/user/' + this.props.user.uname + '/stats'} activeStyle={this.styles} role="menuitem"> <p><i className="icon grid layout"/> {userStatsMsg}</p> </NavLink> } </div> </div> ); } } UserMenu.contextTypes = { executeAction: PropTypes.func.isRequired, intl: PropTypes.object.isRequired }; export default UserMenu;
components/User/UserProfile/PrivatePublicUserProfile/UserMenu.js
import PropTypes from 'prop-types'; import React from 'react'; import {NavLink, navigateAction} from 'fluxible-router'; import { FormattedMessage, defineMessages } from 'react-intl'; import {Microservices} from '../../../../configs/microservices'; class UserMenu extends React.Component { constructor(props){ super(props); this.styles = {'backgroundColor': '#2185D0', 'color': 'white'}; this.messages = this.getIntlMessages(); } getIntlMessages(){ return defineMessages({ myDecks: { id: 'UserMenu.myDecks', defaultMessage: 'My Decks' }, ownedDecks: { id: 'UserMenu.ownedDecks', defaultMessage: 'Owned Decks' }, sharedDecks: { id: 'UserMenu.sharedDecks', defaultMessage: 'Shared Decks' }, collections: { id: 'UserMenu.collections', defaultMessage: 'Playlists' }, ownedCollections: { id: 'UserMenu.ownedCollections', defaultMessage: 'Owned Playlists' }, recommendedDecks: { id: 'UserMenu.recommendedDecks', defaultMessage: 'Recommended Decks' }, stats: { id: 'UserMenu.stats', defaultMessage: 'User Stats' }, }); } render() { let deckRecommendationsMsg = this.context.intl.formatMessage(this.messages.recommendedDecks); let deckRecommendationNavLink = ( <NavLink className="item" href={'/user/' + this.props.user.uname + '/recommendations'} activeStyle={this.styles}> <p><i className="icons"> <i className="yellow open folder icon"></i> <i className="corner thumbs up icon"></i> </i> {deckRecommendationsMsg}</p> </NavLink> ); let decksMsg = this.context.intl.formatMessage(this.messages.myDecks); let sharedDecksMsg = this.context.intl.formatMessage(this.messages.sharedDecks); let deckCollectionsMsg = this.context.intl.formatMessage(this.messages.collections); let userStatsMsg = this.context.intl.formatMessage(this.messages.stats); //Remove link if it's not user's own page //Until recommendation service is properly integrated into the system, show only on experimental if(this.props.user.uname !== this.props.loggedinuser || Microservices.recommendation === undefined || Microservices.recommendation.uri !== 'http://slidewiki.imp.bg.ac.rs') { decksMsg = this.context.intl.formatMessage(this.messages.ownedDecks); deckCollectionsMsg = this.context.intl.formatMessage(this.messages.ownedCollections); deckRecommendationNavLink = ''; } return ( <div role="navigation"> <div className="ui vertical fluid menu" role="menu"> <NavLink className="item" href={'/user/' + this.props.user.uname } activeStyle={this.styles} role="menuitem"> <p><i className="yellow icon open folder"/> {decksMsg}</p> </NavLink> { (this.props.user.uname === this.props.loggedinuser) && <NavLink className="item" href={'/user/' + this.props.user.uname + '/decks/shared'} activeStyle={this.styles} role="menuitem"> <p><i className="icons"> <i className="yellow open folder icon"></i> <i className="corner users icon"></i> </i> {sharedDecksMsg}</p> </NavLink> } {deckRecommendationNavLink} <NavLink className="item" href={'/user/' + this.props.user.uname + '/playlists'} activeStyle={this.styles} role="menuitem"> <p><i className="icon grid layout"/> {deckCollectionsMsg}</p> </NavLink> <NavLink className="item" href={'/user/' + this.props.user.uname + '/stats'} activeStyle={this.styles} role="menuitem"> <p><i className="icon grid layout"/> {userStatsMsg}</p> </NavLink> </div> </div> ); } } UserMenu.contextTypes = { executeAction: PropTypes.func.isRequired, intl: PropTypes.object.isRequired }; export default UserMenu;
Show stats menu item only for user's own profile
components/User/UserProfile/PrivatePublicUserProfile/UserMenu.js
Show stats menu item only for user's own profile
<ide><path>omponents/User/UserProfile/PrivatePublicUserProfile/UserMenu.js <ide> import PropTypes from 'prop-types'; <ide> import React from 'react'; <del>import {NavLink, navigateAction} from 'fluxible-router'; <del>import { FormattedMessage, defineMessages } from 'react-intl'; <add>import {NavLink} from 'fluxible-router'; <add>import {defineMessages} from 'react-intl'; <ide> import {Microservices} from '../../../../configs/microservices'; <ide> <ide> class UserMenu extends React.Component { <ide> <NavLink className="item" href={'/user/' + this.props.user.uname + '/playlists'} activeStyle={this.styles} role="menuitem"> <ide> <p><i className="icon grid layout"/> {deckCollectionsMsg}</p> <ide> </NavLink> <del> <NavLink className="item" href={'/user/' + this.props.user.uname + '/stats'} activeStyle={this.styles} role="menuitem"> <del> <p><i className="icon grid layout"/> {userStatsMsg}</p> <del> </NavLink> <add> {(this.props.user.uname === this.props.loggedinuser) && <add> <NavLink className="item" href={'/user/' + this.props.user.uname + '/stats'} activeStyle={this.styles} <add> role="menuitem"> <add> <p><i className="icon grid layout"/> {userStatsMsg}</p> <add> </NavLink> <add> } <ide> </div> <ide> <ide> </div>
JavaScript
mit
e69cf6d83a749d0c10f7c0d03b46308fa20b4f65
0
rp4rk/ChimpTravisCI,rp4rk/ChimpTravisCI,rp4rk/ChimpTravisCI
const reporter = require('cucumber-html-reporter'); const options = require('./chimp.conf'); // Generate report reporter.generate(options);
generate-report.js
const reporter = require('cucumber-html-reporter'); const options = require('./chimp.conf'); reporter.generate(options);
Trigger build
generate-report.js
Trigger build
<ide><path>enerate-report.js <ide> const reporter = require('cucumber-html-reporter'); <ide> const options = require('./chimp.conf'); <ide> <add>// Generate report <ide> reporter.generate(options);
Java
apache-2.0
086c6c74305c242f3d9dd1995545b1d79c2bd89b
0
batfish/batfish,intentionet/batfish,dhalperi/batfish,dhalperi/batfish,batfish/batfish,batfish/batfish,arifogel/batfish,intentionet/batfish,intentionet/batfish,intentionet/batfish,intentionet/batfish,dhalperi/batfish,arifogel/batfish,arifogel/batfish
package org.batfish.dataplane.ibdp; import static com.google.common.base.MoreObjects.firstNonNull; import static java.util.Objects.requireNonNull; import static org.batfish.common.util.CommonUtil.toImmutableSortedMap; import static org.batfish.datamodel.MultipathEquivalentAsPathMatchMode.EXACT_PATH; import static org.batfish.dataplane.protocols.IsisProtocolHelper.convertRouteLevel1ToLevel2; import static org.batfish.dataplane.protocols.StaticRouteHelper.isInterfaceRoute; import static org.batfish.dataplane.protocols.StaticRouteHelper.shouldActivateNextHopIpRoute; import static org.batfish.dataplane.rib.AbstractRib.importRib; import static org.batfish.dataplane.rib.RibDelta.importRibDelta; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.ImmutableSortedSet; import com.google.common.graph.Network; import com.google.common.graph.ValueGraph; import java.util.AbstractMap.SimpleEntry; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.Collections; import java.util.IdentityHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Optional; import java.util.Queue; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.batfish.common.BatfishException; import org.batfish.common.util.ComparableStructure; import org.batfish.datamodel.AbstractRoute; import org.batfish.datamodel.AsPath; import org.batfish.datamodel.BgpActivePeerConfig; import org.batfish.datamodel.BgpAdvertisement; import org.batfish.datamodel.BgpAdvertisement.BgpAdvertisementType; import org.batfish.datamodel.BgpPeerConfig; import org.batfish.datamodel.BgpPeerConfigId; import org.batfish.datamodel.BgpProcess; import org.batfish.datamodel.BgpRoute; import org.batfish.datamodel.BgpSessionProperties; import org.batfish.datamodel.BgpTieBreaker; import org.batfish.datamodel.Configuration; import org.batfish.datamodel.ConnectedRoute; import org.batfish.datamodel.Edge; import org.batfish.datamodel.Fib; import org.batfish.datamodel.FibImpl; import org.batfish.datamodel.GeneratedRoute; import org.batfish.datamodel.Interface; import org.batfish.datamodel.InterfaceAddress; import org.batfish.datamodel.Ip; import org.batfish.datamodel.IsisInterfaceLevelSettings; import org.batfish.datamodel.IsisInterfaceMode; import org.batfish.datamodel.IsisInterfaceSettings; import org.batfish.datamodel.IsisLevel; import org.batfish.datamodel.IsisLevelSettings; import org.batfish.datamodel.IsisProcess; import org.batfish.datamodel.IsisRoute; import org.batfish.datamodel.LocalRoute; import org.batfish.datamodel.MultipathEquivalentAsPathMatchMode; import org.batfish.datamodel.NetworkConfigurations; import org.batfish.datamodel.OriginType; import org.batfish.datamodel.OspfExternalRoute; import org.batfish.datamodel.OspfExternalType1Route; import org.batfish.datamodel.OspfExternalType2Route; import org.batfish.datamodel.OspfInterAreaRoute; import org.batfish.datamodel.OspfInternalRoute; import org.batfish.datamodel.OspfIntraAreaRoute; import org.batfish.datamodel.OspfRoute; import org.batfish.datamodel.Prefix; import org.batfish.datamodel.RipInternalRoute; import org.batfish.datamodel.RipProcess; import org.batfish.datamodel.Route; import org.batfish.datamodel.RoutingProtocol; import org.batfish.datamodel.StaticRoute; import org.batfish.datamodel.Topology; import org.batfish.datamodel.Vrf; import org.batfish.datamodel.ospf.OspfArea; import org.batfish.datamodel.ospf.OspfAreaSummary; import org.batfish.datamodel.ospf.OspfMetricType; import org.batfish.datamodel.ospf.OspfProcess; import org.batfish.datamodel.ospf.StubType; import org.batfish.datamodel.routing_policy.Environment.Direction; import org.batfish.datamodel.routing_policy.RoutingPolicy; import org.batfish.dataplane.exceptions.BgpRoutePropagationException; import org.batfish.dataplane.protocols.BgpProtocolHelper; import org.batfish.dataplane.protocols.GeneratedRouteHelper; import org.batfish.dataplane.protocols.OspfProtocolHelper; import org.batfish.dataplane.rib.BgpBestPathRib; import org.batfish.dataplane.rib.BgpMultipathRib; import org.batfish.dataplane.rib.ConnectedRib; import org.batfish.dataplane.rib.IsisLevelRib; import org.batfish.dataplane.rib.IsisRib; import org.batfish.dataplane.rib.LocalRib; import org.batfish.dataplane.rib.OspfExternalType1Rib; import org.batfish.dataplane.rib.OspfExternalType2Rib; import org.batfish.dataplane.rib.OspfInterAreaRib; import org.batfish.dataplane.rib.OspfIntraAreaRib; import org.batfish.dataplane.rib.OspfRib; import org.batfish.dataplane.rib.Rib; import org.batfish.dataplane.rib.RibDelta; import org.batfish.dataplane.rib.RibDelta.Builder; import org.batfish.dataplane.rib.RipInternalRib; import org.batfish.dataplane.rib.RipRib; import org.batfish.dataplane.rib.RouteAdvertisement; import org.batfish.dataplane.rib.RouteAdvertisement.Reason; import org.batfish.dataplane.rib.StaticRib; import org.batfish.dataplane.topology.BgpEdgeId; import org.batfish.dataplane.topology.IsisEdge; import org.batfish.dataplane.topology.IsisNode; public class VirtualRouter extends ComparableStructure<String> { private static final long serialVersionUID = 1L; /** Parent configuration for this Virtual router */ private final Configuration _c; /** Route dependency tracker for BGP aggregate routes */ private transient RouteDependencyTracker<BgpRoute, AbstractRoute> _bgpAggDeps = new RouteDependencyTracker<>(); /** Best-path BGP RIB */ BgpBestPathRib _bgpBestPathRib; /** Builder for constructing {@link RibDelta} as pertains to the best-path BGP RIB */ private transient RibDelta.Builder<BgpRoute> _bgpBestPathDeltaBuilder; /** Incoming messages into this router from each BGP neighbor */ transient SortedMap<BgpEdgeId, Queue<RouteAdvertisement<BgpRoute>>> _bgpIncomingRoutes; /** BGP multipath RIB */ BgpMultipathRib _bgpMultipathRib; /** Builder for constructing {@link RibDelta} as pertains to the multipath BGP RIB */ private transient RibDelta.Builder<BgpRoute> _bgpMultiPathDeltaBuilder; /** The RIB containing connected routes */ private transient ConnectedRib _connectedRib; /** Helper RIB containing best paths obtained with external BGP */ transient BgpBestPathRib _ebgpBestPathRib; /** Helper RIB containing all paths obtained with external BGP */ transient BgpMultipathRib _ebgpMultipathRib; /** * Helper RIB containing paths obtained with external eBGP during current iteration. An Adj-RIB of * sorts. */ transient BgpMultipathRib _ebgpStagingRib; /** Helper RIB containing best paths obtained with iBGP */ transient BgpBestPathRib _ibgpBestPathRib; /** Helper RIB containing all paths obtained with iBGP */ transient BgpMultipathRib _ibgpMultipathRib; /** * Helper RIB containing paths obtained with iBGP during current iteration. An Adj-RIB of sorts. */ transient BgpMultipathRib _ibgpStagingRib; /** * The independent RIB contains connected and static routes, which are unaffected by BDP * iterations (hence, independent). */ transient Rib _independentRib; /** Incoming messages into this router from each IS-IS circuit */ transient SortedMap<IsisEdge, Queue<RouteAdvertisement<IsisRoute>>> _isisIncomingRoutes; transient IsisLevelRib _isisL1Rib; transient IsisLevelRib _isisL2Rib; transient IsisLevelRib _isisL1StagingRib; transient IsisLevelRib _isisL2StagingRib; transient IsisRib _isisRib; transient LocalRib _localRib; /** The finalized RIB, a combination different protocol RIBs */ Rib _mainRib; /** Keeps track of changes to the main RIB */ private transient RibDelta.Builder<AbstractRoute> _mainRibRouteDeltaBuiler; transient OspfExternalType1Rib _ospfExternalType1Rib; transient OspfExternalType1Rib _ospfExternalType1StagingRib; transient OspfExternalType2Rib _ospfExternalType2Rib; transient OspfExternalType2Rib _ospfExternalType2StagingRib; @VisibleForTesting transient SortedMap<Prefix, Queue<RouteAdvertisement<OspfExternalRoute>>> _ospfExternalIncomingRoutes; transient OspfInterAreaRib _ospfInterAreaRib; transient OspfInterAreaRib _ospfInterAreaStagingRib; transient OspfIntraAreaRib _ospfIntraAreaRib; transient OspfIntraAreaRib _ospfIntraAreaStagingRib; transient OspfRib _ospfRib; /** * Set of all valid BGP routes we have received during the DP computation. Used to fill gaps in * BGP RIBs when routes are withdrawn. */ private Map<Prefix, SortedSet<BgpRoute>> _receivedBgpRoutes; /** Set of all received BGP advertisements in {@link BgpAdvertisement} form */ private Set<BgpAdvertisement> _receivedBgpAdvertisements; /** Set of all valid IS-IS level-1 routes that we know about */ private Map<Prefix, SortedSet<IsisRoute>> _receivedIsisL1Routes; /** Set of all valid IS-IS level-2 routes that we know about */ private Map<Prefix, SortedSet<IsisRoute>> _receivedIsisL2Routes; /** Set of all valid OSPF external Type 1 routes that we know about */ private Map<Prefix, SortedSet<OspfExternalType1Route>> _receivedOspExternalType1Routes; /** Set of all valid OSPF external Type 2 routes that we know about */ private Map<Prefix, SortedSet<OspfExternalType2Route>> _receivedOspExternalType2Routes; transient RipInternalRib _ripInternalRib; transient RipInternalRib _ripInternalStagingRib; transient RipRib _ripRib; /** Set of all sent BGP advertisements in {@link BgpAdvertisement} form */ Set<BgpAdvertisement> _sentBgpAdvertisements; transient StaticRib _staticInterfaceRib; transient StaticRib _staticNextHopRib; /** FIB (forwarding information base) built from the main RIB */ private Fib _fib; /** RIB containing generated routes */ private transient Rib _generatedRib; private transient RibDelta.Builder<OspfExternalRoute> _ospfExternalDeltaBuiler; private transient Map<Prefix, OspfLink> _ospfNeighbors; // TODO: make non-transient. Currently transient because de-serialization crashes. /** Metadata about propagated prefixes to/from neighbors */ private transient PrefixTracer _prefixTracer; /** A {@link Vrf} that this virtual router represents */ final Vrf _vrf; VirtualRouter(final String name, final Configuration c) { super(name); _c = c; _vrf = c.getVrfs().get(name); initRibs(); // Keep track of sent and received advertisements _receivedBgpAdvertisements = new LinkedHashSet<>(); _sentBgpAdvertisements = new LinkedHashSet<>(); _receivedIsisL1Routes = new TreeMap<>(); _receivedIsisL2Routes = new TreeMap<>(); _receivedOspExternalType1Routes = new TreeMap<>(); _receivedOspExternalType2Routes = new TreeMap<>(); _receivedBgpRoutes = new TreeMap<>(); _bgpIncomingRoutes = new TreeMap<BgpEdgeId, Queue<RouteAdvertisement<BgpRoute>>>(); _prefixTracer = new PrefixTracer(); } /** * Convert a given RibDelta into {@link RouteAdvertisement} objects and enqueue them onto a given * queue. * * @param queue the message queue * @param delta {@link RibDelta} representing changes. */ @VisibleForTesting static <R extends AbstractRoute, D extends R> void queueDelta( Queue<RouteAdvertisement<R>> queue, @Nullable RibDelta<D> delta) { if (delta == null) { // Nothing to do return; } for (RouteAdvertisement<D> r : delta.getActions()) { // REPLACE does not make sense across routers, update with WITHDRAW Reason reason = r.getReason() == Reason.REPLACE ? Reason.WITHDRAW : r.getReason(); queue.add(new RouteAdvertisement<>(r.getRoute(), r.isWithdrawn(), reason)); } } static Entry<RibDelta<BgpRoute>, RibDelta<BgpRoute>> syncBgpDeltaPropagation( BgpBestPathRib bestPathRib, BgpMultipathRib multiPathRib, RibDelta<BgpRoute> delta) { // Build our first attempt at best path delta Builder<BgpRoute> bestDeltaBuilder = new Builder<>(bestPathRib); bestDeltaBuilder.from(importRibDelta(bestPathRib, delta)); RibDelta<BgpRoute> bestPathDelta = bestDeltaBuilder.build(); Builder<BgpRoute> mpBuilder = new Builder<>(multiPathRib); mpBuilder.from(importRibDelta(multiPathRib, bestPathDelta)); if (bestPathDelta != null) { /* * Handle mods to the best path RIB */ for (Prefix p : bestPathDelta.getPrefixes()) { List<RouteAdvertisement<BgpRoute>> actions = bestPathDelta.getActions(p); if (actions != null) { if (actions .stream() .map(RouteAdvertisement::getReason) .anyMatch(Predicate.isEqual(Reason.REPLACE))) { /* * Clear routes for prefixes where best path RIB was modified, because * a better route was chosen, and whatever we had in multipathRib is now invalid */ mpBuilder.from(multiPathRib.clearRoutes(p)); } else if (actions .stream() .map(RouteAdvertisement::getReason) .anyMatch(Predicate.isEqual(Reason.WITHDRAW))) { /* * Routes for that prefix were withdrawn. See if we have anything in the multipath RIB * to fix it. * Create a fake delta, let the routes fight it out for best path in the merge process */ RibDelta<BgpRoute> fakeDelta = new Builder<BgpRoute>(null).add(multiPathRib.getRoutes(p)).build(); bestDeltaBuilder.from(importRibDelta(bestPathRib, fakeDelta)); } } } } // Set the (possibly updated) best path delta bestPathDelta = bestDeltaBuilder.build(); // Update best paths multiPathRib.setBestAsPaths(bestPathRib.getBestAsPaths()); // Only iterate over valid prefixes (ones in best-path RIB) and see if anything should go into // multi-path RIB for (Prefix p : bestPathRib.getPrefixes()) { mpBuilder.from(importRibDelta(multiPathRib, delta, p)); } return new SimpleImmutableEntry<>(bestPathDelta, mpBuilder.build()); } /** Lookup the VirtualRouter owner of a remote BGP neighbor. */ @Nullable @VisibleForTesting static VirtualRouter getRemoteBgpNeighborVR( @Nonnull BgpPeerConfigId bgpId, @Nonnull final Map<String, Node> allNodes) { return allNodes.get(bgpId.getHostname()).getVirtualRouters().get(bgpId.getVrfName()); } /** * Initializes helper data structures and easy-to-compute RIBs that are not affected by BDP * iterations (e.g., static route RIB, connected route RIB, etc.) */ @VisibleForTesting void initForIgpComputation() { initConnectedRib(); initLocalRib(); initStaticRibs(); importRib(_independentRib, _connectedRib); importRib(_independentRib, _localRib); importRib(_independentRib, _staticInterfaceRib); importRib(_mainRib, _independentRib); initIntraAreaOspfRoutes(); initBaseRipRoutes(); } /** * Prep for the Egp part of the computation * * @param allNodes map of all network nodes, keyed by hostname * @param bgpTopology the bgp peering relationships */ void initForEgpComputation( final Map<String, Node> allNodes, Topology topology, ValueGraph<BgpPeerConfigId, BgpSessionProperties> bgpTopology, Network<IsisNode, IsisEdge> isisTopology) { initQueuesAndDeltaBuilders(allNodes, topology, bgpTopology, isisTopology); } /** * Initializes RIB delta builders and protocol message queues. * * @param allNodes map of all network nodes, keyed by hostname * @param topology Layer 3 network topology * @param bgpTopology the bgp peering relationships */ @VisibleForTesting void initQueuesAndDeltaBuilders( final Map<String, Node> allNodes, final Topology topology, ValueGraph<BgpPeerConfigId, BgpSessionProperties> bgpTopology, Network<IsisNode, IsisEdge> isisTopology) { // Initialize message queues for each BGP neighbor initBgpQueues(bgpTopology); initIsisQueues(isisTopology); // Initialize message queues for each Ospf neighbor if (_vrf.getOspfProcess() == null) { _ospfExternalIncomingRoutes = ImmutableSortedMap.of(); } else { _ospfNeighbors = getOspfNeighbors(allNodes, topology); if (_ospfNeighbors == null) { _ospfExternalIncomingRoutes = ImmutableSortedMap.of(); } else { _ospfExternalIncomingRoutes = _ospfNeighbors .keySet() .stream() .collect( ImmutableSortedMap.toImmutableSortedMap( Prefix::compareTo, Function.identity(), p -> new ConcurrentLinkedQueue<>())); } } } /** * Initialize incoming BGP message queues. * * @param bgpTopology source of truth for which sessions get established. */ void initBgpQueues(ValueGraph<BgpPeerConfigId, BgpSessionProperties> bgpTopology) { if (_vrf.getBgpProcess() == null) { _bgpIncomingRoutes = ImmutableSortedMap.of(); } else { _bgpIncomingRoutes = Stream.concat( _vrf.getBgpProcess() .getActiveNeighbors() .entrySet() .stream() .map( e -> new BgpPeerConfigId( getHostname(), _vrf.getName(), e.getKey(), false)), _vrf.getBgpProcess() .getPassiveNeighbors() .entrySet() .stream() .map( e -> new BgpPeerConfigId(getHostname(), _vrf.getName(), e.getKey(), true))) .filter(bgpTopology.nodes()::contains) .flatMap( dst -> bgpTopology.adjacentNodes(dst).stream().map(src -> new BgpEdgeId(src, dst))) .collect( toImmutableSortedMap(Function.identity(), e -> new ConcurrentLinkedQueue<>())); } } private void initIsisQueues(Network<IsisNode, IsisEdge> isisTopology) { // Initialize message queues for each IS-IS circuit if (_vrf.getIsisProcess() == null) { _isisIncomingRoutes = ImmutableSortedMap.of(); } else { _isisIncomingRoutes = _vrf.getInterfaceNames() .stream() .map(ifaceName -> new IsisNode(_c.getHostname(), ifaceName)) .filter(isisTopology.nodes()::contains) .flatMap(n -> isisTopology.inEdges(n).stream()) .collect( toImmutableSortedMap(Function.identity(), e -> new ConcurrentLinkedQueue<>())); } } /** * Activate generated routes. * * @return a new {@link RibDelta} if a new route has been activated, otherwise {@code null} */ @VisibleForTesting RibDelta<AbstractRoute> activateGeneratedRoutes() { RibDelta.Builder<AbstractRoute> builder = new Builder<>(_generatedRib); /* * Loop over all generated routes and check whether any of the contributing routes can trigger * activation. */ for (GeneratedRoute gr : _vrf.getGeneratedRoutes()) { String policyName = gr.getGenerationPolicy(); RoutingPolicy generationPolicy = policyName != null ? _c.getRoutingPolicies().get(gr.getGenerationPolicy()) : null; GeneratedRoute.Builder grb = GeneratedRouteHelper.activateGeneratedRoute( gr, generationPolicy, _mainRib.getRoutes(), _vrf.getName()); if (grb != null) { GeneratedRoute newGr = grb.build(); // Routes have been changed RibDelta<AbstractRoute> d = _generatedRib.mergeRouteGetDelta(newGr); builder.from(d); } } return builder.build(); } /** * Recompute generated routes. If new generated routes were activated, process them into the main * RIB. Check if any BGP aggregates were affected by the new generated routes. */ void recomputeGeneratedRoutes() { RibDelta<AbstractRoute> d; RibDelta.Builder<AbstractRoute> generatedRouteDeltaBuilder = new Builder<>(_mainRib); do { d = activateGeneratedRoutes(); generatedRouteDeltaBuilder.from(d); } while (d != null); d = generatedRouteDeltaBuilder.build(); // Update main rib as well _mainRibRouteDeltaBuiler.from(importRibDelta(_mainRib, d)); /* * Check dependencies for BGP aggregates. * * Updates from these BGP deltas into mainRib will be handled in finalizeBgp routes */ if (d != null) { d.getActions() .stream() .filter(RouteAdvertisement::isWithdrawn) .forEach( r -> { _bgpBestPathDeltaBuilder.from( _bgpAggDeps.deleteRoute(r.getRoute(), _bgpBestPathRib)); _bgpMultiPathDeltaBuilder.from( _bgpAggDeps.deleteRoute(r.getRoute(), _bgpMultipathRib)); }); } } /** * Activate static routes with next hop IP. Adds a static route {@code route} to the main RIB if * there exists an active route to the {@code routes}'s next-hop-ip. * * <p>Removes static route from the main RIB for which next-hop-ip has become unreachable. */ void activateStaticRoutes() { for (StaticRoute sr : _staticNextHopRib.getRoutes()) { if (shouldActivateNextHopIpRoute(sr, _mainRib)) { _mainRibRouteDeltaBuiler.from(_mainRib.mergeRouteGetDelta(sr)); } else { /* * If the route is not in the RIB, this has no effect. But might add some overhead (TODO) */ _mainRibRouteDeltaBuiler.from(_mainRib.removeRouteGetDelta(sr, Reason.WITHDRAW)); } } } /** Compute the FIB from the main RIB */ public void computeFib() { _fib = new FibImpl(_mainRib); } boolean computeInterAreaSummaries() { OspfProcess proc = _vrf.getOspfProcess(); boolean changed = false; // Ensure we have a running OSPF process on the VRF, otherwise bail. if (proc == null) { return false; } // Admin cost for the given protocol int admin = RoutingProtocol.OSPF_IA.getSummaryAdministrativeCost(_c.getConfigurationFormat()); // Determine whether to use min metric by default, based on RFC1583 compatibility setting. // Routers (at least Cisco and Juniper) default to min metric unless using RFC2328 with // RFC1583 compatibility explicitly disabled, in which case they default to max. boolean useMin = firstNonNull(proc.getRfc1583Compatible(), Boolean.TRUE); // Compute summaries for each area for (Entry<Long, OspfArea> e : proc.getAreas().entrySet()) { long areaNum = e.getKey(); OspfArea area = e.getValue(); for (Entry<Prefix, OspfAreaSummary> e2 : area.getSummaries().entrySet()) { Prefix prefix = e2.getKey(); OspfAreaSummary summary = e2.getValue(); // Only advertised summaries can contribute if (!summary.getAdvertised()) { continue; } Long metric = summary.getMetric(); if (summary.getMetric() == null) { // No metric was configured; compute it from any possible contributing routes. for (OspfIntraAreaRoute contributingRoute : _ospfIntraAreaRib.getRoutes()) { metric = OspfProtocolHelper.computeUpdatedOspfSummaryMetric( contributingRoute, prefix, metric, areaNum, useMin); } for (OspfInterAreaRoute contributingRoute : _ospfInterAreaRib.getRoutes()) { metric = OspfProtocolHelper.computeUpdatedOspfSummaryMetric( contributingRoute, prefix, metric, areaNum, useMin); } } // No routes contributed to the summary, nothing to construct if (metric == null) { continue; } // Non-null metric means we generate a new summary and put it in the RIB OspfInterAreaRoute summaryRoute = new OspfInterAreaRoute(prefix, Ip.ZERO, admin, metric, areaNum); if (_ospfInterAreaStagingRib.mergeRouteGetDelta(summaryRoute) != null) { changed = true; } } } return changed; } /** * Initializes BGP RIBs prior to any dataplane iterations based on the external BGP advertisements * coming into the network * * @param externalAdverts a set of external BGP advertisements * @param ipOwners mapping of IPs to their owners in our network * @param bgpTopology the bgp peering relationships */ void initBaseBgpRibs( Set<BgpAdvertisement> externalAdverts, Map<Ip, Set<String>> ipOwners, final Map<String, Node> allNodes, ValueGraph<BgpPeerConfigId, BgpSessionProperties> bgpTopology, NetworkConfigurations networkConfigurations) { BgpProcess proc = _vrf.getBgpProcess(); if (proc == null) { // Nothing to do return; } // Keep track of changes to the RIBs using delta builders, keyed by RIB type Map<BgpMultipathRib, RibDelta.Builder<BgpRoute>> ribDeltas = new IdentityHashMap<>(); ribDeltas.put(_ebgpStagingRib, new Builder<>(_ebgpStagingRib)); ribDeltas.put(_ibgpStagingRib, new Builder<>(_ibgpStagingRib)); // initialize admin costs for routes int ebgpAdmin = RoutingProtocol.BGP.getDefaultAdministrativeCost(_c.getConfigurationFormat()); int ibgpAdmin = RoutingProtocol.IBGP.getDefaultAdministrativeCost(_c.getConfigurationFormat()); BgpRoute.Builder outgoingRouteBuilder = new BgpRoute.Builder(); // Process each BGP advertisement for (BgpAdvertisement advert : externalAdverts) { // If it is not for us, ignore it if (!advert.getDstNode().equals(_c.getHostname())) { continue; } // If we don't own the IP for this advertisement, ignore it Ip dstIp = advert.getDstIp(); Set<String> dstIpOwners = ipOwners.get(dstIp); String hostname = _c.getHostname(); if (dstIpOwners == null || !dstIpOwners.contains(hostname)) { continue; } Ip srcIp = advert.getSrcIp(); // TODO: support passive bgp connections Prefix srcPrefix = new Prefix(srcIp, Prefix.MAX_PREFIX_LENGTH); BgpPeerConfig neighbor = _vrf.getBgpProcess().getActiveNeighbors().get(srcPrefix); if (neighbor == null) { continue; } // Build a route based on the type of this advertisement BgpAdvertisementType type = advert.getType(); boolean ebgp; boolean received; switch (type) { case EBGP_RECEIVED: ebgp = true; received = true; break; case EBGP_SENT: ebgp = true; received = false; break; case IBGP_RECEIVED: ebgp = false; received = true; break; case IBGP_SENT: ebgp = false; received = false; break; case EBGP_ORIGINATED: case IBGP_ORIGINATED: default: throw new BatfishException("Missing or invalid bgp advertisement type"); } BgpMultipathRib targetRib = ebgp ? _ebgpStagingRib : _ibgpStagingRib; RoutingProtocol targetProtocol = ebgp ? RoutingProtocol.BGP : RoutingProtocol.IBGP; if (received) { int admin = ebgp ? ebgpAdmin : ibgpAdmin; AsPath asPath = advert.getAsPath(); SortedSet<Long> clusterList = advert.getClusterList(); SortedSet<Long> communities = ImmutableSortedSet.copyOf(advert.getCommunities()); int localPreference = advert.getLocalPreference(); long metric = advert.getMed(); Prefix network = advert.getNetwork(); Ip nextHopIp = advert.getNextHopIp(); Ip originatorIp = advert.getOriginatorIp(); OriginType originType = advert.getOriginType(); RoutingProtocol srcProtocol = advert.getSrcProtocol(); int weight = advert.getWeight(); BgpRoute.Builder builder = new BgpRoute.Builder(); builder.setAdmin(admin); builder.setAsPath(asPath.getAsSets()); builder.setClusterList(clusterList); builder.setCommunities(communities); builder.setLocalPreference(localPreference); builder.setMetric(metric); builder.setNetwork(network); builder.setNextHopIp(nextHopIp); builder.setOriginatorIp(originatorIp); builder.setOriginType(originType); builder.setProtocol(targetProtocol); // TODO: support external route reflector clients builder.setReceivedFromIp(advert.getSrcIp()); builder.setReceivedFromRouteReflectorClient(false); builder.setSrcProtocol(srcProtocol); // TODO: possibly support setting tag builder.setWeight(weight); BgpRoute route = builder.build(); ribDeltas.get(targetRib).from(targetRib.mergeRouteGetDelta(route)); } else { int localPreference; if (ebgp) { localPreference = BgpRoute.DEFAULT_LOCAL_PREFERENCE; } else { localPreference = advert.getLocalPreference(); } outgoingRouteBuilder.setAsPath(advert.getAsPath().getAsSets()); outgoingRouteBuilder.setCommunities(ImmutableSortedSet.copyOf(advert.getCommunities())); outgoingRouteBuilder.setLocalPreference(localPreference); outgoingRouteBuilder.setMetric(advert.getMed()); outgoingRouteBuilder.setNetwork(advert.getNetwork()); outgoingRouteBuilder.setNextHopIp(advert.getNextHopIp()); outgoingRouteBuilder.setOriginatorIp(advert.getOriginatorIp()); outgoingRouteBuilder.setOriginType(advert.getOriginType()); outgoingRouteBuilder.setProtocol(targetProtocol); outgoingRouteBuilder.setReceivedFromIp(advert.getSrcIp()); // TODO: // outgoingRouteBuilder.setReceivedFromRouteReflectorClient(...); outgoingRouteBuilder.setSrcProtocol(advert.getSrcProtocol()); BgpRoute transformedOutgoingRoute = outgoingRouteBuilder.build(); BgpRoute.Builder transformedIncomingRouteBuilder = new BgpRoute.Builder(); // Incoming originatorIp transformedIncomingRouteBuilder.setOriginatorIp(transformedOutgoingRoute.getOriginatorIp()); // Incoming receivedFromIp transformedIncomingRouteBuilder.setReceivedFromIp( transformedOutgoingRoute.getReceivedFromIp()); // Incoming clusterList transformedIncomingRouteBuilder .getClusterList() .addAll(transformedOutgoingRoute.getClusterList()); // Incoming receivedFromRouteReflectorClient transformedIncomingRouteBuilder.setReceivedFromRouteReflectorClient( transformedOutgoingRoute.getReceivedFromRouteReflectorClient()); // Incoming asPath transformedIncomingRouteBuilder.setAsPath(transformedOutgoingRoute.getAsPath().getAsSets()); // Incoming communities transformedIncomingRouteBuilder .getCommunities() .addAll(transformedOutgoingRoute.getCommunities()); // Incoming protocol transformedIncomingRouteBuilder.setProtocol(targetProtocol); // Incoming network transformedIncomingRouteBuilder.setNetwork(transformedOutgoingRoute.getNetwork()); // Incoming nextHopIp transformedIncomingRouteBuilder.setNextHopIp(transformedOutgoingRoute.getNextHopIp()); // Incoming originType transformedIncomingRouteBuilder.setOriginType(transformedOutgoingRoute.getOriginType()); // Incoming localPreference transformedIncomingRouteBuilder.setLocalPreference( transformedOutgoingRoute.getLocalPreference()); // Incoming admin int admin = ebgp ? ebgpAdmin : ibgpAdmin; transformedIncomingRouteBuilder.setAdmin(admin); // Incoming metric transformedIncomingRouteBuilder.setMetric(transformedOutgoingRoute.getMetric()); // Incoming srcProtocol transformedIncomingRouteBuilder.setSrcProtocol(targetProtocol); String importPolicyName = neighbor.getImportPolicy(); // TODO: ensure there is always an import policy if (ebgp && transformedOutgoingRoute.getAsPath().containsAs(neighbor.getLocalAs()) && !neighbor.getAllowLocalAsIn()) { // skip routes containing peer's AS unless // disable-peer-as-check (getAllowRemoteAsOut) is set continue; } /* * CREATE INCOMING ROUTE */ boolean acceptIncoming = true; if (importPolicyName != null) { RoutingPolicy importPolicy = _c.getRoutingPolicies().get(importPolicyName); if (importPolicy != null) { acceptIncoming = importPolicy.process( transformedOutgoingRoute, transformedIncomingRouteBuilder, advert.getSrcIp(), _key, Direction.IN); } } if (acceptIncoming) { BgpRoute transformedIncomingRoute = transformedIncomingRouteBuilder.build(); ribDeltas.get(targetRib).from(targetRib.mergeRouteGetDelta(transformedIncomingRoute)); } } } // Propagate received routes through all the RIBs and send out appropriate messages // to neighbors Map<BgpMultipathRib, RibDelta<BgpRoute>> deltas = ribDeltas .entrySet() .stream() .filter(e -> e.getValue().build() != null) .collect(Collectors.toMap(Entry::getKey, e -> e.getValue().build())); finalizeBgpRoutesAndQueueOutgoingMessages( proc.getMultipathEbgp(), proc.getMultipathIbgp(), deltas, allNodes, bgpTopology, networkConfigurations); } /** Initialize Intra-area OSPF routes from the interface prefixes */ private void initIntraAreaOspfRoutes() { OspfProcess proc = _vrf.getOspfProcess(); if (proc == null) { return; // nothing to do } /* * init intra-area routes from connected routes * For each interface within an OSPF area and each interface prefix, * construct a new OSPF-IA route. Put it in the IA RIB. */ proc.getAreas() .forEach( (areaNum, area) -> { for (String ifaceName : area.getInterfaces()) { Interface iface = _c.getInterfaces().get(ifaceName); if (iface.getActive()) { Set<Prefix> allNetworkPrefixes = iface .getAllAddresses() .stream() .map(InterfaceAddress::getPrefix) .collect(Collectors.toSet()); int interfaceOspfCost = iface.getOspfCost(); for (Prefix prefix : allNetworkPrefixes) { long cost = interfaceOspfCost; boolean stubNetwork = iface.getOspfPassive() || iface.getOspfPointToPoint(); if (stubNetwork) { if (proc.getMaxMetricStubNetworks() != null) { cost = proc.getMaxMetricStubNetworks(); } } else if (proc.getMaxMetricTransitLinks() != null) { cost = proc.getMaxMetricTransitLinks(); } OspfIntraAreaRoute route = new OspfIntraAreaRoute( prefix, null, RoutingProtocol.OSPF.getDefaultAdministrativeCost( _c.getConfigurationFormat()), cost, areaNum); _ospfIntraAreaRib.mergeRouteGetDelta(route); } } } }); } /** Initialize RIP routes from the interface prefixes */ @VisibleForTesting void initBaseRipRoutes() { if (_vrf.getRipProcess() == null) { return; // nothing to do } // init internal routes from connected routes for (String ifaceName : _vrf.getRipProcess().getInterfaces()) { Interface iface = _vrf.getInterfaces().get(ifaceName); if (iface.getActive()) { Set<Prefix> allNetworkPrefixes = iface .getAllAddresses() .stream() .map(InterfaceAddress::getPrefix) .collect(Collectors.toSet()); long cost = RipProcess.DEFAULT_RIP_COST; for (Prefix prefix : allNetworkPrefixes) { RipInternalRoute route = new RipInternalRoute( prefix, null, RoutingProtocol.RIP.getDefaultAdministrativeCost(_c.getConfigurationFormat()), cost); _ripInternalRib.mergeRouteGetDelta(route); } } } } /** * This function creates BGP routes from generated routes that go into the BGP RIB, but cannot be * imported into the main RIB. The purpose of these routes is to prevent the local router from * accepting advertisements less desirable than the local generated ones for a given network. */ void initBgpAggregateRoutes() { // first import aggregates switch (_c.getConfigurationFormat()) { case JUNIPER: case JUNIPER_SWITCH: return; // $CASES-OMITTED$ default: break; } for (AbstractRoute grAbstract : _generatedRib.getRoutes()) { GeneratedRoute gr = (GeneratedRoute) grAbstract; BgpRoute br = BgpProtocolHelper.convertGeneratedRouteToBgp(gr, _vrf.getBgpProcess().getRouterId()); // Prevent route from being merged into the main RIB. br.setNonRouting(true); /* TODO: tests for this */ RibDelta<BgpRoute> d1 = _bgpMultipathRib.mergeRouteGetDelta(br); _bgpBestPathDeltaBuilder.from(d1); RibDelta<BgpRoute> d2 = _bgpBestPathRib.mergeRouteGetDelta(br); _bgpMultiPathDeltaBuilder.from(d2); if (d1 != null || d2 != null) { _bgpAggDeps.addRouteDependency(br, gr); } } } /** * Initialize the connected RIB -- a RIB containing connected routes (i.e., direct connections to * neighbors). */ @VisibleForTesting void initConnectedRib() { // Look at all connected interfaces for (Interface i : _vrf.getInterfaces().values()) { if (i.getActive()) { // Make sure the interface is active // Create a route for each interface prefix for (InterfaceAddress ifaceAddress : i.getAllAddresses()) { Prefix prefix = ifaceAddress.getPrefix(); ConnectedRoute cr = new ConnectedRoute(prefix, i.getName()); _connectedRib.mergeRoute(cr); } } } } /** * Initialize the local RIB -- a RIB containing non-forwarding /32 routes for exact addresses of * interfaces */ @VisibleForTesting void initLocalRib() { // Look at all connected interfaces for (Interface i : _vrf.getInterfaces().values()) { if (i.getActive()) { // Make sure the interface is active // Create a route for each interface prefix for (InterfaceAddress ifaceAddress : i.getAllAddresses()) { if (ifaceAddress.getNetworkBits() < Prefix.MAX_PREFIX_LENGTH) { LocalRoute lr = new LocalRoute(ifaceAddress, i.getName()); _localRib.mergeRoute(lr); } } } } } @Nullable @VisibleForTesting OspfExternalRoute computeOspfExportRoute( AbstractRoute potentialExportRoute, RoutingPolicy exportPolicy, OspfProcess proc) { OspfExternalRoute.Builder outputRouteBuilder = new OspfExternalRoute.Builder(); // Export based on the policy result of processing the potentialExportRoute boolean accept = exportPolicy.process(potentialExportRoute, outputRouteBuilder, null, _key, Direction.OUT); if (!accept) { return null; } OspfMetricType metricType = outputRouteBuilder.getOspfMetricType(); outputRouteBuilder.setAdmin( outputRouteBuilder .getOspfMetricType() .toRoutingProtocol() .getDefaultAdministrativeCost(_c.getConfigurationFormat())); outputRouteBuilder.setNetwork(potentialExportRoute.getNetwork()); Long maxMetricExternalNetworks = proc.getMaxMetricExternalNetworks(); long costToAdvertiser; if (maxMetricExternalNetworks != null) { if (metricType == OspfMetricType.E1) { outputRouteBuilder.setMetric(maxMetricExternalNetworks); } costToAdvertiser = maxMetricExternalNetworks; } else { costToAdvertiser = 0L; } outputRouteBuilder.setCostToAdvertiser(costToAdvertiser); outputRouteBuilder.setAdvertiser(_c.getHostname()); outputRouteBuilder.setArea(OspfRoute.NO_AREA); outputRouteBuilder.setLsaMetric(outputRouteBuilder.getMetric()); OspfExternalRoute outputRoute = outputRouteBuilder.build(); outputRoute.setNonRouting(true); return outputRoute; } void initIsisExports(Map<String, Node> allNodes) { /* TODO: https://github.com/batfish/batfish/issues/1703 */ IsisProcess proc = _vrf.getIsisProcess(); if (proc == null) { return; // nothing to do } RibDelta.Builder<IsisRoute> d1 = new Builder<>(_isisL1Rib); RibDelta.Builder<IsisRoute> d2 = new Builder<>(_isisL2Rib); /* * init L1 and L2 routes from connected routes */ int l1Admin = RoutingProtocol.ISIS_L1.getDefaultAdministrativeCost(_c.getConfigurationFormat()); int l2Admin = RoutingProtocol.ISIS_L2.getDefaultAdministrativeCost(_c.getConfigurationFormat()); IsisLevelSettings l1Settings = proc.getLevel1(); IsisLevelSettings l2Settings = proc.getLevel2(); IsisRoute.Builder builder = new IsisRoute.Builder() .setArea(proc.getNetAddress().getAreaIdString()) .setSystemId(proc.getNetAddress().getSystemIdString()); _vrf.getInterfaces() .values() .forEach( iface -> generateAllIsisInterfaceRoutes( d1, d2, l1Admin, l2Admin, l1Settings, l2Settings, builder, iface)); // export default route for L1 neighbors on L1L2 routers if (l1Settings != null && l2Settings != null) { IsisRoute defaultRoute = builder .setAdmin(l1Admin) .setAttach(true) .setLevel(IsisLevel.LEVEL_1) .setMetric(0L) .setNetwork(Prefix.ZERO) .setProtocol(RoutingProtocol.ISIS_L1) .build(); d1.from(_isisL1Rib.mergeRouteGetDelta(defaultRoute)); } queueOutgoingIsisRoutes(allNodes, d1.build(), d2.build()); } /** * Generate IS-IS L1/L2 routes from a given interface and merge them into appropriate L1/L2 RIBs. */ private void generateAllIsisInterfaceRoutes( Builder<IsisRoute> d1, Builder<IsisRoute> d2, int l1Admin, int l2Admin, @Nullable IsisLevelSettings l1Settings, @Nullable IsisLevelSettings l2Settings, IsisRoute.Builder routeBuilder, Interface iface) { IsisInterfaceSettings ifaceSettings = iface.getIsis(); if (ifaceSettings == null) { return; } IsisInterfaceLevelSettings ifaceL1Settings = ifaceSettings.getLevel1(); IsisInterfaceLevelSettings ifaceL2Settings = ifaceSettings.getLevel2(); if (ifaceL1Settings != null && l1Settings != null) { long metric = ifaceL1Settings.getMode() == IsisInterfaceMode.PASSIVE ? 0L : firstNonNull(ifaceL1Settings.getCost(), IsisRoute.DEFAULT_METRIC); generateIsisInterfaceRoutesPerLevel( l1Admin, routeBuilder, iface, metric, IsisLevel.LEVEL_1, RoutingProtocol.ISIS_L1) .forEach(r -> d1.from(_isisL1Rib.mergeRouteGetDelta(r))); } if (ifaceL2Settings != null && l2Settings != null) { long metric = ifaceL2Settings.getMode() == IsisInterfaceMode.PASSIVE ? 0L : firstNonNull(ifaceL2Settings.getCost(), IsisRoute.DEFAULT_METRIC); generateIsisInterfaceRoutesPerLevel( l2Admin, routeBuilder, iface, metric, IsisLevel.LEVEL_2, RoutingProtocol.ISIS_L2) .forEach(r -> d2.from(_isisL2Rib.mergeRouteGetDelta(r))); } } /** * Generate IS-IS from a given interface for a given level (with a given metric/admin cost) and * merge them into the appropriate RIB. */ private static Set<IsisRoute> generateIsisInterfaceRoutesPerLevel( int adminCost, IsisRoute.Builder routeBuilder, Interface iface, long metric, IsisLevel level, RoutingProtocol isisProtocol) { routeBuilder.setAdmin(adminCost).setLevel(level).setMetric(metric).setProtocol(isisProtocol); return iface .getAllAddresses() .stream() .map( address -> routeBuilder.setNetwork(address.getPrefix()).setNextHopIp(address.getIp()).build()) .collect(ImmutableSet.toImmutableSet()); } void initOspfExports() { OspfProcess proc = _vrf.getOspfProcess(); // Nothing to do if (proc == null) { return; } // get OSPF export policy name String exportPolicyName = _vrf.getOspfProcess().getExportPolicy(); if (exportPolicyName == null) { return; // nothing to export } RoutingPolicy exportPolicy = _c.getRoutingPolicies().get(exportPolicyName); if (exportPolicy == null) { return; // nothing to export } // For each route in the previous RIB, compute an export route and add it to the appropriate // RIB. RibDelta.Builder<OspfExternalType1Route> d1 = new Builder<>(_ospfExternalType1Rib); RibDelta.Builder<OspfExternalType2Route> d2 = new Builder<>(_ospfExternalType2Rib); for (AbstractRoute potentialExport : _mainRib.getRoutes()) { OspfExternalRoute outputRoute = computeOspfExportRoute(potentialExport, exportPolicy, proc); if (outputRoute == null) { continue; // no need to export } if (outputRoute.getOspfMetricType() == OspfMetricType.E1) { d1.from(_ospfExternalType1Rib.mergeRouteGetDelta((OspfExternalType1Route) outputRoute)); } else { // assuming here that MetricType exists. Or E2 is the default d2.from(_ospfExternalType2Rib.mergeRouteGetDelta((OspfExternalType2Route) outputRoute)); } } queueOutgoingOspfExternalRoutes(d1.build(), d2.build()); } /** Initialize all ribs on this router. All RIBs will be empty */ @VisibleForTesting final void initRibs() { _connectedRib = new ConnectedRib(); _localRib = new LocalRib(); // If bgp process is null, doesn't matter MultipathEquivalentAsPathMatchMode mpTieBreaker = _vrf.getBgpProcess() == null ? EXACT_PATH : _vrf.getBgpProcess().getMultipathEquivalentAsPathMatchMode(); _ebgpMultipathRib = new BgpMultipathRib(mpTieBreaker); _ebgpStagingRib = new BgpMultipathRib(mpTieBreaker); _generatedRib = new Rib(); _ibgpMultipathRib = new BgpMultipathRib(mpTieBreaker); _ibgpStagingRib = new BgpMultipathRib(mpTieBreaker); _independentRib = new Rib(); _isisRib = new IsisRib(isL1Only()); _isisL1Rib = new IsisLevelRib(_receivedIsisL1Routes); _isisL2Rib = new IsisLevelRib(_receivedIsisL2Routes); _isisL1StagingRib = new IsisLevelRib(null); _isisL2StagingRib = new IsisLevelRib(null); _mainRib = new Rib(); _ospfExternalType1Rib = new OspfExternalType1Rib(getHostname(), _receivedOspExternalType1Routes); _ospfExternalType2Rib = new OspfExternalType2Rib(getHostname(), _receivedOspExternalType2Routes); _ospfExternalType1StagingRib = new OspfExternalType1Rib(getHostname(), null); _ospfExternalType2StagingRib = new OspfExternalType2Rib(getHostname(), null); _ospfInterAreaRib = new OspfInterAreaRib(); _ospfInterAreaStagingRib = new OspfInterAreaRib(); _ospfIntraAreaRib = new OspfIntraAreaRib(this); _ospfIntraAreaStagingRib = new OspfIntraAreaRib(this); _ospfRib = new OspfRib(); _ripInternalRib = new RipInternalRib(); _ripInternalStagingRib = new RipInternalRib(); _ripRib = new RipRib(); _staticNextHopRib = new StaticRib(); _staticInterfaceRib = new StaticRib(); _bgpMultipathRib = new BgpMultipathRib(mpTieBreaker); _ebgpMultipathRib = new BgpMultipathRib(mpTieBreaker); _ibgpMultipathRib = new BgpMultipathRib(mpTieBreaker); BgpTieBreaker tieBreaker = _vrf.getBgpProcess() == null ? BgpTieBreaker.ARRIVAL_ORDER : _vrf.getBgpProcess().getTieBreaker(); _ebgpBestPathRib = new BgpBestPathRib(tieBreaker, null, _mainRib); _ibgpBestPathRib = new BgpBestPathRib(tieBreaker, null, _mainRib); _bgpBestPathRib = new BgpBestPathRib(tieBreaker, _receivedBgpRoutes, _mainRib); _mainRibRouteDeltaBuiler = new RibDelta.Builder<>(_mainRib); _bgpBestPathDeltaBuilder = new RibDelta.Builder<>(_bgpBestPathRib); _bgpMultiPathDeltaBuilder = new RibDelta.Builder<>(_bgpMultipathRib); } private boolean isL1Only() { IsisProcess proc = _vrf.getIsisProcess(); if (proc == null) { return false; } return proc.getLevel1() != null && proc.getLevel2() == null; } /** * Initialize the static route RIBs from the VRF config. Interface routes go into {@link * #_staticInterfaceRib}; routes that only have next-hop-ip go into {@link #_staticNextHopRib} */ @VisibleForTesting void initStaticRibs() { for (StaticRoute sr : _vrf.getStaticRoutes()) { if (isInterfaceRoute(sr)) { // We have an interface route, check if interface is active Interface nextHopInterface = _c.getInterfaces().get(sr.getNextHopInterface()); if (Interface.NULL_INTERFACE_NAME.equals(sr.getNextHopInterface()) || (nextHopInterface != null && (nextHopInterface.getActive()))) { // Interface is active (or special null interface), install route _staticInterfaceRib.mergeRouteGetDelta(sr); } } else { if (Route.UNSET_ROUTE_NEXT_HOP_IP.equals(sr.getNextHopIp())) { continue; } // We have a next-hop-ip route, keep in it that RIB _staticNextHopRib.mergeRouteGetDelta(sr); } } } /** * Compute a set of BGP advertisements to the outside of the network. Done after the dataplane * computation has converged. * * @param ipOwners mapping of IPs to their owners (nodes) * @return a number of sent out advertisements */ int computeBgpAdvertisementsToOutside(Map<Ip, Set<String>> ipOwners) { int numAdvertisements = 0; // If we have no BGP process, nothing to do if (_vrf.getBgpProcess() == null) { return numAdvertisements; } /* * This operation only really makes sense for active neighbors, otherwise we're missing required * information for which advertisements would be sent out. */ for (BgpActivePeerConfig neighbor : _vrf.getBgpProcess().getActiveNeighbors().values()) { String hostname = _c.getHostname(); Ip remoteIp = neighbor.getPeerAddress(); if (neighbor.getLocalIp() == null || remoteIp == null || neighbor.getLocalAs() == null || neighbor.getRemoteAs() == null || ipOwners.get(remoteIp) != null) { // Skip if neighbor is mis-configured or remote peer is inside the network continue; } long localAs = neighbor.getLocalAs(); long remoteAs = neighbor.getRemoteAs(); String remoteHostname = remoteIp.toString(); String remoteVrfName = _vrf.getName(); RoutingPolicy exportPolicy = _c.getRoutingPolicies().get(neighbor.getExportPolicy()); boolean ebgpSession = localAs != remoteAs; RoutingProtocol targetProtocol = ebgpSession ? RoutingProtocol.BGP : RoutingProtocol.IBGP; Set<AbstractRoute> candidateRoutes = Collections.newSetFromMap(new IdentityHashMap<>()); // Add IGP routes Set<AbstractRoute> activeRoutes = Collections.newSetFromMap(new IdentityHashMap<>()); activeRoutes.addAll(_mainRib.getRoutes()); for (AbstractRoute candidateRoute : activeRoutes) { if (candidateRoute.getProtocol() != RoutingProtocol.BGP && candidateRoute.getProtocol() != RoutingProtocol.IBGP) { candidateRoutes.add(candidateRoute); } } /* * bgp advertise-external * * When this is set, add best eBGP path independently of whether * it is preempted by an iBGP or IGP route. Only applicable to * iBGP sessions. */ boolean advertiseExternal = !ebgpSession && neighbor.getAdvertiseExternal(); if (advertiseExternal) { candidateRoutes.addAll(_ebgpBestPathRib.getRoutes()); } /* * bgp advertise-inactive * * When this is set, add best BGP path independently of whether * it is preempted by an IGP route. Only applicable to eBGP * sessions. */ boolean advertiseInactive = ebgpSession && neighbor.getAdvertiseInactive(); /* Add best bgp paths if they are active, or if advertise-inactive */ for (AbstractRoute candidateRoute : _bgpBestPathRib.getRoutes()) { if (advertiseInactive || activeRoutes.contains(candidateRoute)) { candidateRoutes.add(candidateRoute); } } /* Add all bgp paths if additional-paths active for this session */ boolean additionalPaths = !ebgpSession && neighbor.getAdditionalPathsSend() && neighbor.getAdditionalPathsSelectAll(); if (additionalPaths) { candidateRoutes.addAll(_bgpMultipathRib.getRoutes()); } for (AbstractRoute route : candidateRoutes) { // TODO: update this using BgpProtocolHelper BgpRoute.Builder transformedOutgoingRouteBuilder = new BgpRoute.Builder(); RoutingProtocol routeProtocol = route.getProtocol(); boolean routeIsBgp = routeProtocol == RoutingProtocol.IBGP || routeProtocol == RoutingProtocol.BGP; // originatorIP Ip originatorIp; if (!ebgpSession && routeProtocol == RoutingProtocol.IBGP) { BgpRoute bgpRoute = (BgpRoute) route; originatorIp = bgpRoute.getOriginatorIp(); } else { originatorIp = _vrf.getBgpProcess().getRouterId(); } transformedOutgoingRouteBuilder.setOriginatorIp(originatorIp); transformedOutgoingRouteBuilder.setReceivedFromIp(neighbor.getLocalIp()); /* * clusterList, receivedFromRouteReflectorClient, (originType for bgp remote route) */ if (routeIsBgp) { BgpRoute bgpRoute = (BgpRoute) route; transformedOutgoingRouteBuilder.setOriginType(bgpRoute.getOriginType()); if (ebgpSession && bgpRoute.getAsPath().containsAs(neighbor.getRemoteAs()) && !neighbor.getAllowRemoteAsOut()) { // skip routes containing peer's AS unless // disable-peer-as-check (getAllowRemoteAsOut) is set continue; } /* * route reflection: reflect everything received from * clients to clients and non-clients. reflect everything * received from non-clients to clients. Do not reflect to * originator */ Ip routeOriginatorIp = bgpRoute.getOriginatorIp(); /* * iBGP speaker should not send out routes to iBGP neighbor whose router-id is * same as originator id of advertisement */ if (!ebgpSession && remoteIp.equals(routeOriginatorIp)) { continue; } if (routeProtocol == RoutingProtocol.IBGP && !ebgpSession) { boolean routeReceivedFromRouteReflectorClient = bgpRoute.getReceivedFromRouteReflectorClient(); boolean sendingToRouteReflectorClient = neighbor.getRouteReflectorClient(); transformedOutgoingRouteBuilder.getClusterList().addAll(bgpRoute.getClusterList()); if (!routeReceivedFromRouteReflectorClient && !sendingToRouteReflectorClient) { continue; } if (sendingToRouteReflectorClient) { // sender adds its local cluster id to clusterlist of // new route transformedOutgoingRouteBuilder.getClusterList().add(neighbor.getClusterId()); } } } // Outgoing asPath // Outgoing communities if (routeIsBgp) { BgpRoute bgpRoute = (BgpRoute) route; transformedOutgoingRouteBuilder.setAsPath(bgpRoute.getAsPath().getAsSets()); if (neighbor.getSendCommunity()) { transformedOutgoingRouteBuilder.getCommunities().addAll(bgpRoute.getCommunities()); } } if (ebgpSession) { SortedSet<Long> newAsPathElement = new TreeSet<>(); newAsPathElement.add(localAs); transformedOutgoingRouteBuilder.getAsPath().add(0, newAsPathElement); } // Outgoing protocol transformedOutgoingRouteBuilder.setProtocol(targetProtocol); transformedOutgoingRouteBuilder.setNetwork(route.getNetwork()); // Outgoing metric if (routeIsBgp) { transformedOutgoingRouteBuilder.setMetric(route.getMetric()); } // Outgoing nextHopIp // Outgoing localPreference Ip nextHopIp; int localPreference; if (ebgpSession || !routeIsBgp) { nextHopIp = neighbor.getLocalIp(); localPreference = BgpRoute.DEFAULT_LOCAL_PREFERENCE; } else { nextHopIp = route.getNextHopIp(); BgpRoute ibgpRoute = (BgpRoute) route; localPreference = ibgpRoute.getLocalPreference(); } if (Route.UNSET_ROUTE_NEXT_HOP_IP.equals(nextHopIp)) { // should only happen for ibgp String nextHopInterface = route.getNextHopInterface(); InterfaceAddress nextHopAddress = _c.getInterfaces().get(nextHopInterface).getAddress(); if (nextHopAddress == null) { throw new BatfishException("route's nextHopInterface has no address"); } nextHopIp = nextHopAddress.getIp(); } transformedOutgoingRouteBuilder.setNextHopIp(nextHopIp); transformedOutgoingRouteBuilder.setLocalPreference(localPreference); // Outgoing srcProtocol transformedOutgoingRouteBuilder.setSrcProtocol(route.getProtocol()); /* * CREATE OUTGOING ROUTE */ boolean acceptOutgoing = exportPolicy.process( route, transformedOutgoingRouteBuilder, remoteIp, new Prefix(neighbor.getPeerAddress(), Prefix.MAX_PREFIX_LENGTH), remoteVrfName, Direction.OUT); if (!acceptOutgoing) { _prefixTracer.filtered( route.getNetwork(), remoteHostname, remoteIp, remoteVrfName, neighbor.getExportPolicy(), Direction.OUT); continue; } _prefixTracer.sentTo( route.getNetwork(), remoteHostname, remoteIp, remoteVrfName, neighbor.getExportPolicy()); BgpRoute transformedOutgoingRoute = transformedOutgoingRouteBuilder.build(); // Record sent advertisement BgpAdvertisementType sentType = ebgpSession ? BgpAdvertisementType.EBGP_SENT : BgpAdvertisementType.IBGP_SENT; Ip sentOriginatorIp = transformedOutgoingRoute.getOriginatorIp(); SortedSet<Long> sentClusterList = ImmutableSortedSet.copyOf(transformedOutgoingRoute.getClusterList()); AsPath sentAsPath = transformedOutgoingRoute.getAsPath(); SortedSet<Long> sentCommunities = ImmutableSortedSet.copyOf(transformedOutgoingRoute.getCommunities()); Prefix sentNetwork = route.getNetwork(); Ip sentNextHopIp; String sentSrcNode = hostname; String sentSrcVrf = _vrf.getName(); Ip sentSrcIp = neighbor.getLocalIp(); String sentDstNode = remoteHostname; String sentDstVrf = remoteVrfName; Ip sentDstIp = remoteIp; int sentWeight = -1; if (ebgpSession) { sentNextHopIp = nextHopIp; } else { sentNextHopIp = transformedOutgoingRoute.getNextHopIp(); } int sentLocalPreference = transformedOutgoingRoute.getLocalPreference(); long sentMed = transformedOutgoingRoute.getMetric(); OriginType sentOriginType = transformedOutgoingRoute.getOriginType(); RoutingProtocol sentSrcProtocol = targetProtocol; BgpAdvertisement sentAdvert = new BgpAdvertisement( sentType, sentNetwork, sentNextHopIp, sentSrcNode, sentSrcVrf, sentSrcIp, sentDstNode, sentDstVrf, sentDstIp, sentSrcProtocol, sentOriginType, sentLocalPreference, sentMed, sentOriginatorIp, sentAsPath, ImmutableSortedSet.copyOf(sentCommunities), ImmutableSortedSet.copyOf(sentClusterList), sentWeight); _sentBgpAdvertisements.add(sentAdvert); numAdvertisements++; } } return numAdvertisements; } /** * Process BGP messages from neighbors, return a list of delta changes to the RIBs * * @param bgpTopology the bgp peering relationships * @return List of {@link RibDelta objects} */ @Nullable Map<BgpMultipathRib, RibDelta<BgpRoute>> processBgpMessages( ValueGraph<BgpPeerConfigId, BgpSessionProperties> bgpTopology, NetworkConfigurations nc) { // If we have no BGP process, nothing to do if (_vrf.getBgpProcess() == null) { return null; } // Keep track of changes to the RIBs using delta builders, keyed by RIB type Map<BgpMultipathRib, RibDelta.Builder<BgpRoute>> ribDeltas = new IdentityHashMap<>(); ribDeltas.put(_ebgpStagingRib, new Builder<>(_ebgpStagingRib)); ribDeltas.put(_ibgpStagingRib, new Builder<>(_ibgpStagingRib)); // Process updates from each neighbor for (Entry<BgpEdgeId, Queue<RouteAdvertisement<BgpRoute>>> e : _bgpIncomingRoutes.entrySet()) { // Grab the queue containing all messages from remoteBgpPeerConfig Queue<RouteAdvertisement<BgpRoute>> queue = e.getValue(); // Setup helper vars BgpPeerConfigId remoteConfigId = e.getKey().src(); BgpPeerConfigId ourConfigId = e.getKey().dst(); BgpSessionProperties sessionProperties = getBgpSessionProperties(bgpTopology, new BgpEdgeId(remoteConfigId, ourConfigId)); BgpPeerConfig ourBgpConfig = requireNonNull(nc.getBgpPeerConfig(e.getKey().dst())); BgpPeerConfig remoteBgpConfig = requireNonNull(nc.getBgpPeerConfig(e.getKey().src())); BgpMultipathRib targetRib = sessionProperties.isEbgp() ? _ebgpStagingRib : _ibgpStagingRib; // Process all routes from neighbor while (queue.peek() != null) { RouteAdvertisement<BgpRoute> remoteRouteAdvert = queue.remove(); BgpRoute remoteRoute = remoteRouteAdvert.getRoute(); BgpRoute.Builder transformedIncomingRouteBuilder = BgpProtocolHelper.transformBgpRouteOnImport( ourBgpConfig, sessionProperties, remoteRoute, _c.getConfigurationFormat()); if (transformedIncomingRouteBuilder == null) { // Route could not be imported for core protocol reasons continue; } // Process route through import policy, if one exists String importPolicyName = ourBgpConfig.getImportPolicy(); boolean acceptIncoming = true; // TODO: ensure there is always an import policy if (importPolicyName != null) { RoutingPolicy importPolicy = _c.getRoutingPolicies().get(importPolicyName); if (importPolicy != null) { acceptIncoming = importPolicy.process( remoteRoute, transformedIncomingRouteBuilder, remoteBgpConfig.getLocalIp(), ourConfigId.getRemotePeerPrefix(), _key, Direction.IN); } } if (!acceptIncoming) { // Route could not be imported due to routing policy _prefixTracer.filtered( remoteRoute.getNetwork(), ourConfigId.getHostname(), remoteBgpConfig.getLocalIp(), remoteConfigId.getVrfName(), importPolicyName, Direction.IN); continue; } BgpRoute transformedIncomingRoute = transformedIncomingRouteBuilder.build(); if (remoteRouteAdvert.isWithdrawn()) { // Note this route was removed ribDeltas.get(targetRib).remove(transformedIncomingRoute, Reason.WITHDRAW); SortedSet<BgpRoute> b = _receivedBgpRoutes.get(transformedIncomingRoute.getNetwork()); if (b != null) { b.remove(transformedIncomingRoute); } } else { // Merge into staging rib, note delta ribDeltas.get(targetRib).from(targetRib.mergeRouteGetDelta(transformedIncomingRoute)); if (!remoteRouteAdvert.isWithdrawn()) { markReceivedBgpAdvertisement( ourConfigId, remoteConfigId, ourBgpConfig, remoteBgpConfig, sessionProperties, transformedIncomingRoute); _receivedBgpRoutes .computeIfAbsent(transformedIncomingRoute.getNetwork(), k -> new TreeSet<>()) .add(transformedIncomingRoute); _prefixTracer.installed( transformedIncomingRoute.getNetwork(), remoteConfigId.getHostname(), remoteBgpConfig.getLocalIp(), remoteConfigId.getVrfName(), importPolicyName); } } } } // Return built deltas from RibDelta builders Map<BgpMultipathRib, RibDelta<BgpRoute>> builtDeltas = new IdentityHashMap<>(); ribDeltas.forEach( (rib, deltaBuilder) -> { RibDelta<BgpRoute> delta = deltaBuilder.build(); if (delta != null) { builtDeltas.put(rib, delta); } }); return builtDeltas; } public @Nullable Entry<RibDelta<IsisRoute>, RibDelta<IsisRoute>> propagateIsisRoutes( final Map<String, Node> nodes) { if (_vrf.getIsisProcess() == null) { return null; } RibDelta.Builder<IsisRoute> l1DeltaBuilder = new RibDelta.Builder<>(_isisL1StagingRib); RibDelta.Builder<IsisRoute> l2DeltaBuilder = new RibDelta.Builder<>(_isisL2StagingRib); IsisRoute.Builder routeBuilder = new IsisRoute.Builder(); int l1Admin = RoutingProtocol.ISIS_L1.getDefaultAdministrativeCost(_c.getConfigurationFormat()); int l2Admin = RoutingProtocol.ISIS_L2.getDefaultAdministrativeCost(_c.getConfigurationFormat()); _isisIncomingRoutes.forEach( (edge, queue) -> { Ip nextHopIp = edge.getNode1().getInterface(nodes).getAddress().getIp(); Interface iface = edge.getNode2().getInterface(nodes); routeBuilder.setNextHopIp(nextHopIp); while (queue.peek() != null) { RouteAdvertisement<IsisRoute> routeAdvert = queue.remove(); IsisRoute neighborRoute = routeAdvert.getRoute(); routeBuilder .setNetwork(neighborRoute.getNetwork()) .setArea(neighborRoute.getArea()) .setAttach(neighborRoute.getAttach()) .setSystemId(neighborRoute.getSystemId()); boolean withdraw = routeAdvert.isWithdrawn(); // TODO: simplify if (neighborRoute.getLevel() == IsisLevel.LEVEL_1) { long incrementalMetric = firstNonNull(iface.getIsis().getLevel1().getCost(), IsisRoute.DEFAULT_METRIC); IsisRoute newL1Route = routeBuilder .setAdmin(l1Admin) .setLevel(IsisLevel.LEVEL_1) .setMetric(incrementalMetric + neighborRoute.getMetric()) .setProtocol(RoutingProtocol.ISIS_L1) .build(); if (withdraw) { l1DeltaBuilder.remove(newL1Route, Reason.WITHDRAW); SortedSet<IsisRoute> backups = _receivedIsisL1Routes.get(newL1Route.getNetwork()); if (backups != null) { backups.remove(newL1Route); } } else { l1DeltaBuilder.from(_isisL1StagingRib.mergeRouteGetDelta(newL1Route)); _receivedIsisL1Routes .computeIfAbsent(newL1Route.getNetwork(), k -> new TreeSet<>()) .add(newL1Route); } } else { // neighborRoute is level2 long incrementalMetric = firstNonNull(iface.getIsis().getLevel2().getCost(), IsisRoute.DEFAULT_METRIC); IsisRoute newL2Route = routeBuilder .setAdmin(l2Admin) .setLevel(IsisLevel.LEVEL_2) .setMetric(incrementalMetric + neighborRoute.getMetric()) .setProtocol(RoutingProtocol.ISIS_L2) .build(); if (withdraw) { l2DeltaBuilder.remove(newL2Route, Reason.WITHDRAW); SortedSet<IsisRoute> backups = _receivedIsisL2Routes.get(newL2Route.getNetwork()); if (backups != null) { backups.remove(newL2Route); } } else { l2DeltaBuilder.from(_isisL2StagingRib.mergeRouteGetDelta(newL2Route)); _receivedIsisL2Routes .computeIfAbsent(newL2Route.getNetwork(), k -> new TreeSet<>()) .add(newL2Route); } } } }); return new SimpleEntry<>(l1DeltaBuilder.build(), l2DeltaBuilder.build()); } /** * Propagate OSPF external routes from our neighbors by reading OSPF route "advertisements" from * our queues. * * @param allNodes map of all nodes, keyed by hostname * @param topology the Layer-3 network topology * @return a pair of {@link RibDelta}s, for Type1 and Type2 routes */ @Nullable public Entry<RibDelta<OspfExternalType1Route>, RibDelta<OspfExternalType2Route>> propagateOspfExternalRoutes(final Map<String, Node> allNodes, Topology topology) { String node = _c.getHostname(); OspfProcess proc = _vrf.getOspfProcess(); if (proc == null) { return null; } int admin = RoutingProtocol.OSPF.getDefaultAdministrativeCost(_c.getConfigurationFormat()); SortedSet<Edge> edges = topology.getNodeEdges().get(node); if (edges == null) { // there are no edges, so OSPF won't produce anything return null; } RibDelta.Builder<OspfExternalType1Route> builderType1 = new RibDelta.Builder<>(_ospfExternalType1StagingRib); RibDelta.Builder<OspfExternalType2Route> builderType2 = new RibDelta.Builder<>(_ospfExternalType2StagingRib); for (Edge edge : edges) { if (!edge.getNode1().equals(node)) { continue; } String connectingInterfaceName = edge.getInt1(); Interface connectingInterface = _vrf.getInterfaces().get(connectingInterfaceName); if (connectingInterface == null) { // wrong vrf, so skip continue; } String neighborName = edge.getNode2(); Node neighbor = allNodes.get(neighborName); String neighborInterfaceName = edge.getInt2(); OspfArea area = connectingInterface.getOspfArea(); Configuration nc = neighbor.getConfiguration(); Interface neighborInterface = nc.getInterfaces().get(neighborInterfaceName); String neighborVrfName = neighborInterface.getVrfName(); VirtualRouter neighborVirtualRouter = allNodes.get(neighborName).getVirtualRouters().get(neighborVrfName); OspfArea neighborArea = neighborInterface.getOspfArea(); if (connectingInterface.getOspfEnabled() && !connectingInterface.getOspfPassive() && neighborInterface.getOspfEnabled() && !neighborInterface.getOspfPassive() && area != null && neighborArea != null && area.getName().equals(neighborArea.getName())) { /* * We have an ospf neighbor relationship on this edge. So we * should add all ospf external type 1(2) routes from this * neighbor into our ospf external type 1(2) staging rib. For * type 1, the cost of the route increases each time. For type 2, * the cost remains constant, but we must keep track of cost to * advertiser as a tie-breaker. */ long connectingInterfaceCost = connectingInterface.getOspfCost(); long incrementalCost = proc.getMaxMetricTransitLinks() != null ? proc.getMaxMetricTransitLinks() : connectingInterfaceCost; Queue<RouteAdvertisement<OspfExternalRoute>> q = _ospfExternalIncomingRoutes.get(connectingInterface.getAddress().getPrefix()); while (q.peek() != null) { RouteAdvertisement<OspfExternalRoute> routeAdvert = q.remove(); OspfExternalRoute neighborRoute = routeAdvert.getRoute(); boolean withdraw = routeAdvert.isWithdrawn(); if (neighborRoute instanceof OspfExternalType1Route) { long oldArea = neighborRoute.getArea(); long connectionArea = area.getName(); long newArea; long baseMetric = neighborRoute.getMetric(); long baseCostToAdvertiser = neighborRoute.getCostToAdvertiser(); newArea = connectionArea; if (oldArea != OspfRoute.NO_AREA) { Long maxMetricSummaryNetworks = neighborVirtualRouter._vrf.getOspfProcess().getMaxMetricSummaryNetworks(); if (connectionArea != oldArea) { if (connectionArea != 0L && oldArea != 0L) { continue; } if (maxMetricSummaryNetworks != null) { baseMetric = maxMetricSummaryNetworks + neighborRoute.getLsaMetric(); baseCostToAdvertiser = maxMetricSummaryNetworks; } } } long newMetric = baseMetric + incrementalCost; long newCostToAdvertiser = baseCostToAdvertiser + incrementalCost; OspfExternalType1Route newRoute = new OspfExternalType1Route( neighborRoute.getNetwork(), neighborInterface.getAddress().getIp(), admin, newMetric, neighborRoute.getLsaMetric(), newArea, newCostToAdvertiser, neighborRoute.getAdvertiser()); if (withdraw) { builderType1.remove(newRoute, Reason.WITHDRAW); SortedSet<OspfExternalType1Route> backups = _receivedOspExternalType1Routes.get(newRoute.getNetwork()); if (backups != null) { backups.remove(newRoute); } } else { builderType1.from(_ospfExternalType1StagingRib.mergeRouteGetDelta(newRoute)); _receivedOspExternalType1Routes .computeIfAbsent(newRoute.getNetwork(), k -> new TreeSet<>()) .add(newRoute); } } else if (neighborRoute instanceof OspfExternalType2Route) { long oldArea = neighborRoute.getArea(); long connectionArea = area.getName(); long newArea; long baseCostToAdvertiser = neighborRoute.getCostToAdvertiser(); if (oldArea == OspfRoute.NO_AREA) { newArea = connectionArea; } else { newArea = oldArea; Long maxMetricSummaryNetworks = neighborVirtualRouter._vrf.getOspfProcess().getMaxMetricSummaryNetworks(); if (connectionArea != oldArea && maxMetricSummaryNetworks != null) { baseCostToAdvertiser = maxMetricSummaryNetworks; } } long newCostToAdvertiser = baseCostToAdvertiser + incrementalCost; OspfExternalType2Route newRoute = new OspfExternalType2Route( neighborRoute.getNetwork(), neighborInterface.getAddress().getIp(), admin, neighborRoute.getMetric(), neighborRoute.getLsaMetric(), newArea, newCostToAdvertiser, neighborRoute.getAdvertiser()); if (withdraw) { builderType2.remove(newRoute, Reason.WITHDRAW); SortedSet<OspfExternalType2Route> backups = _receivedOspExternalType2Routes.get(newRoute.getNetwork()); if (backups != null) { backups.remove(newRoute); } } else { builderType2.from(_ospfExternalType2StagingRib.mergeRouteGetDelta(newRoute)); _receivedOspExternalType2Routes .computeIfAbsent(newRoute.getNetwork(), k -> new TreeSet<>()) .add(newRoute); } } } } } return new SimpleEntry<>(builderType1.build(), builderType2.build()); } /** * Construct an OSPF Inter-Area route and put into our staging rib. Note, no route validity checks * are performed, (i.e., whether the route should even go into the staging rib). {@link * #propagateOspfInternalRoutesFromNeighbor} takes care of such logic. * * @param neighborRoute the route to propagate * @param nextHopIp nextHopIp for this route (the neighbor's IP) * @param incrementalCost OSPF cost of the interface from which this route came (added to route * cost) * @param adminCost OSPF administrative distance * @param areaNum area number of the route * @return True if the route was added to the inter-area staging RIB */ @VisibleForTesting boolean stageOspfInterAreaRoute( OspfInternalRoute neighborRoute, Long maxMetricSummaryNetworks, Ip nextHopIp, long incrementalCost, int adminCost, long areaNum) { long newCost; if (maxMetricSummaryNetworks != null) { newCost = maxMetricSummaryNetworks + incrementalCost; } else { newCost = neighborRoute.getMetric() + incrementalCost; } OspfInterAreaRoute newRoute = new OspfInterAreaRoute(neighborRoute.getNetwork(), nextHopIp, adminCost, newCost, areaNum); return _ospfInterAreaStagingRib.mergeRoute(newRoute); } boolean propagateOspfInterAreaRouteFromIntraAreaRoute( Configuration neighbor, OspfProcess neighborProc, OspfIntraAreaRoute neighborRoute, long incrementalCost, Interface neighborInterface, int adminCost, long linkAreaNum) { return OspfProtocolHelper.isOspfInterAreaFromIntraAreaPropagationAllowed( linkAreaNum, neighbor, neighborProc, neighborRoute, neighborInterface.getOspfArea()) && stageOspfInterAreaRoute( neighborRoute, neighborInterface.getVrf().getOspfProcess().getMaxMetricSummaryNetworks(), neighborInterface.getAddress().getIp(), incrementalCost, adminCost, linkAreaNum); } /** * Propagate OSPF Internal routes from a single neighbor. * * @param proc The receiving OSPF process * @param neighbor the neighbor * @param connectingInterface interface on which we are connected to the neighbor * @param neighborInterface interface that the neighbor uses to connect to us * @param adminCost route administrative distance * @return true if new routes have been added to our staging RIB */ boolean propagateOspfInternalRoutesFromNeighbor( OspfProcess proc, Node neighbor, Interface connectingInterface, Interface neighborInterface, int adminCost) { OspfArea area = connectingInterface.getOspfArea(); OspfArea neighborArea = neighborInterface.getOspfArea(); // Ensure that the link (i.e., both interfaces) has OSPF enabled and OSPF areas are set if (!connectingInterface.getOspfEnabled() || connectingInterface.getOspfPassive() || !neighborInterface.getOspfEnabled() || neighborInterface.getOspfPassive() || area == null || neighborArea == null || !area.getName().equals(neighborArea.getName())) { return false; } /* * An OSPF neighbor relationship exists on this edge. So we examine all intra- and inter-area * routes belonging to the neighbor to see what should be propagated to this router. We add the * incremental cost associated with our settings and the connecting interface, and use the * neighborInterface's address as the next hop ip. */ int connectingInterfaceCost = connectingInterface.getOspfCost(); long incrementalCost = proc.getMaxMetricTransitLinks() != null ? proc.getMaxMetricTransitLinks() : connectingInterfaceCost; Long linkAreaNum = area.getName(); Configuration neighborConfiguration = neighbor.getConfiguration(); String neighborVrfName = neighborInterface.getVrfName(); OspfProcess neighborProc = neighborConfiguration.getVrfs().get(neighborVrfName).getOspfProcess(); VirtualRouter neighborVirtualRouter = neighbor.getVirtualRouters().get(neighborVrfName); boolean changed = false; for (OspfIntraAreaRoute neighborRoute : neighborVirtualRouter._ospfIntraAreaRib.getRoutes()) { changed |= propagateOspfIntraAreaRoute( neighborRoute, incrementalCost, neighborInterface, adminCost, linkAreaNum); changed |= propagateOspfInterAreaRouteFromIntraAreaRoute( neighborConfiguration, neighborProc, neighborRoute, incrementalCost, neighborInterface, adminCost, linkAreaNum); } for (OspfInterAreaRoute neighborRoute : neighborVirtualRouter._ospfInterAreaRib.getRoutes()) { changed |= propagateOspfInterAreaRouteFromInterAreaRoute( proc, neighborConfiguration, neighborProc, neighborRoute, incrementalCost, neighborInterface, adminCost, linkAreaNum); } changed |= originateOspfStubAreaDefaultRoute( neighborProc, incrementalCost, neighborInterface, adminCost, linkAreaNum); return changed; } /** * If neighbor is an ABR and this is a stub area link, propagate * * @param neighborProc The adjacent {@link OspfProcess} * @param incrementalCost The cost to reach the propagator * @param neighborInterface The propagator's interface on the link * @param adminCost The administrative cost of the route to be installed * @param linkAreaNum The area ID of the link * @return whether this route changed the RIB into which we merged it */ private boolean originateOspfStubAreaDefaultRoute( OspfProcess neighborProc, long incrementalCost, Interface neighborInterface, int adminCost, long linkAreaNum) { return OspfProtocolHelper.isOspfInterAreaDefaultOriginationAllowed( _vrf.getOspfProcess(), neighborProc, neighborInterface.getOspfArea()) && _ospfInterAreaStagingRib.mergeRoute( new OspfInterAreaRoute( Prefix.ZERO, neighborInterface.getAddress().getIp(), adminCost, incrementalCost, linkAreaNum)); } boolean propagateOspfInterAreaRouteFromInterAreaRoute( OspfProcess proc, Configuration neighbor, OspfProcess neighborProc, OspfInterAreaRoute neighborRoute, long incrementalCost, Interface neighborInterface, int adminCost, long linkAreaNum) { return OspfProtocolHelper.isOspfInterAreaFromInterAreaPropagationAllowed( proc, linkAreaNum, neighbor, neighborProc, neighborRoute, neighborInterface.getOspfArea()) && stageOspfInterAreaRoute( neighborRoute, neighborInterface.getVrf().getOspfProcess().getMaxMetricSummaryNetworks(), neighborInterface.getAddress().getIp(), incrementalCost, adminCost, linkAreaNum); } boolean propagateOspfIntraAreaRoute( OspfIntraAreaRoute neighborRoute, long incrementalCost, Interface neighborInterface, int adminCost, long linkAreaNum) { long newCost = neighborRoute.getMetric() + incrementalCost; Ip nextHopIp = neighborInterface.getAddress().getIp(); OspfIntraAreaRoute newRoute = new OspfIntraAreaRoute( neighborRoute.getNetwork(), nextHopIp, adminCost, newCost, linkAreaNum); return neighborRoute.getArea() == linkAreaNum && (_ospfIntraAreaStagingRib.mergeRoute(newRoute)); } /** * Propagate OSPF internal routes from every valid OSPF neighbor * * @param nodes mapping of node names to instances. * @param topology network topology * @return true if new routes have been added to the staging RIB */ boolean propagateOspfInternalRoutes(Map<String, Node> nodes, Topology topology) { OspfProcess proc = _vrf.getOspfProcess(); if (proc == null) { return false; // nothing to do } boolean changed = false; String node = _c.getHostname(); // Default OSPF admin cost for constructing new routes int adminCost = RoutingProtocol.OSPF.getDefaultAdministrativeCost(_c.getConfigurationFormat()); SortedSet<Edge> edges = topology.getNodeEdges().get(node); if (edges == null) { // there are no edges, so OSPF won't produce anything return false; } for (Edge edge : edges) { if (!edge.getNode1().equals(node)) { continue; } String connectingInterfaceName = edge.getInt1(); Interface connectingInterface = _vrf.getInterfaces().get(connectingInterfaceName); if (connectingInterface == null) { // wrong vrf, so skip continue; } String neighborName = edge.getNode2(); Node neighbor = nodes.get(neighborName); Interface neighborInterface = neighbor.getConfiguration().getInterfaces().get(edge.getInt2()); changed |= propagateOspfInternalRoutesFromNeighbor( proc, neighbor, connectingInterface, neighborInterface, adminCost); } return changed; } /** * Process RIP routes from our neighbors. * * @param nodes Mapping of node names to Node instances * @param topology The network topology * @return True if the rib has changed as a result of route propagation */ boolean propagateRipInternalRoutes(Map<String, Node> nodes, Topology topology) { boolean changed = false; // No rip process, nothing to do if (_vrf.getRipProcess() == null) { return false; } String node = _c.getHostname(); int admin = RoutingProtocol.RIP.getDefaultAdministrativeCost(_c.getConfigurationFormat()); SortedSet<Edge> edges = topology.getNodeEdges().get(node); if (edges == null) { // there are no edges, so RIP won't produce anything return false; } for (Edge edge : edges) { // Do not accept routes from ourselves if (!edge.getNode1().equals(node)) { continue; } // Get interface String connectingInterfaceName = edge.getInt1(); Interface connectingInterface = _vrf.getInterfaces().get(connectingInterfaceName); if (connectingInterface == null) { // wrong vrf, so skip continue; } // Get the neighbor and its interface + VRF String neighborName = edge.getNode2(); Node neighbor = nodes.get(neighborName); String neighborInterfaceName = edge.getInt2(); Interface neighborInterface = neighbor.getConfiguration().getInterfaces().get(neighborInterfaceName); String neighborVrfName = neighborInterface.getVrfName(); VirtualRouter neighborVirtualRouter = nodes.get(neighborName).getVirtualRouters().get(neighborVrfName); if (connectingInterface.getRipEnabled() && !connectingInterface.getRipPassive() && neighborInterface.getRipEnabled() && !neighborInterface.getRipPassive()) { /* * We have a RIP neighbor relationship on this edge. So we should add all RIP routes * from this neighbor into our RIP internal staging rib, adding the incremental cost * (?), and using the neighborInterface's address as the next hop ip */ for (RipInternalRoute neighborRoute : neighborVirtualRouter._ripInternalRib.getRoutes()) { long newCost = neighborRoute.getMetric() + RipProcess.DEFAULT_RIP_COST; Ip nextHopIp = neighborInterface.getAddress().getIp(); RipInternalRoute newRoute = new RipInternalRoute(neighborRoute.getNetwork(), nextHopIp, admin, newCost); if (_ripInternalStagingRib.mergeRouteGetDelta(newRoute) != null) { changed = true; } } } } return changed; } /** * Queue advertised BGP routes to all BGP neighbors. * * @param ebgpBestPathDelta {@link RibDelta} indicating what changed in the {@link * #_bgpBestPathRib} * @param bgpMultiPathDelta a {@link RibDelta} indicating what changed in the {@link * #_bgpMultipathRib} * @param mainDelta a {@link RibDelta} indicating what changed in the {@link #_mainRib} * @param allNodes map of all nodes in the network, keyed by hostname * @param bgpTopology the bgp peering relationships */ private void queueOutgoingBgpRoutes( RibDelta<BgpRoute> ebgpBestPathDelta, @Nullable RibDelta<BgpRoute> bgpMultiPathDelta, @Nullable RibDelta<AbstractRoute> mainDelta, final Map<String, Node> allNodes, ValueGraph<BgpPeerConfigId, BgpSessionProperties> bgpTopology, NetworkConfigurations networkConfigurations) { for (BgpEdgeId edge : _bgpIncomingRoutes.keySet()) { final BgpSessionProperties session = getBgpSessionProperties(bgpTopology, edge); BgpPeerConfigId remoteConfigId = edge.src(); BgpPeerConfigId ourConfigId = edge.dst(); BgpPeerConfig ourConfig = networkConfigurations.getBgpPeerConfig(edge.dst()); BgpPeerConfig remoteConfig = networkConfigurations.getBgpPeerConfig(edge.src()); VirtualRouter remoteVirtualRouter = getRemoteBgpNeighborVR(remoteConfigId, allNodes); if (remoteVirtualRouter == null) { continue; } Builder<AbstractRoute> finalBuilder = new Builder<>(null); // Definitely queue mainRib updates finalBuilder.from(mainDelta); // These knobs control which additional BGP routes get advertised if (session.getAdvertiseExternal()) { /* * Advertise external ensures that even if we withdrew an external route from the RIB */ finalBuilder.from(ebgpBestPathDelta); } if (session.getAdvertiseInactive()) { /* * In case BGP routes were deleted from the main RIB * (e.g., preempted by a better IGP route) * and advertiseInactive is true, re-add inactive BGP routes from the BGP best-path RIB. * If the BGP routes are already active, this will have no effect. */ if (mainDelta != null) { for (Prefix p : mainDelta.getPrefixes()) { if (_bgpBestPathRib.getRoutes(p) == null) { continue; } finalBuilder.add(_bgpBestPathRib.getRoutes(p)); } } } if (session.getAdditionalPaths()) { finalBuilder.from(bgpMultiPathDelta); } RibDelta<AbstractRoute> routesToExport = finalBuilder.build(); if (routesToExport == null) { continue; } // Compute a set of advertisements that can be queued on remote VR Set<RouteAdvertisement<BgpRoute>> exportedAdvertisements = routesToExport .getActions() .stream() .map( adv -> { BgpRoute transformedRoute = exportBgpRoute( adv.getRoute(), ourConfigId, remoteConfigId, ourConfig, remoteConfig, allNodes, session); return transformedRoute == null ? null : new RouteAdvertisement<>( // REPLACE does not make sense across routers, update with WITHDRAW transformedRoute, adv.isWithdrawn(), adv.getReason() == Reason.REPLACE ? Reason.WITHDRAW : adv.getReason()); }) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); // Call this on the REMOTE VR and REVERSE the edge! remoteVirtualRouter.enqueueBgpMessages(edge.reverse(), exportedAdvertisements); // Note what we sent markSentBgpAdvertisements( ourConfigId, remoteConfigId, ourConfig, remoteConfig, session, exportedAdvertisements); } } private static BgpSessionProperties getBgpSessionProperties( ValueGraph<BgpPeerConfigId, BgpSessionProperties> bgpTopology, BgpEdgeId edge) { /* BGP topology edges not guaranteed to be symmetrical (in case of dynamic neighbors). So to get session properties, we might need to flip the src/dst edge */ BgpSessionProperties tmpSession; try { tmpSession = bgpTopology.edgeValue(edge.src(), edge.dst()); } catch (IllegalArgumentException e) { tmpSession = bgpTopology.edgeValue(edge.dst(), edge.src()); } return tmpSession; } private void queueOutgoingIsisRoutes( @Nonnull Map<String, Node> allNodes, @Nullable RibDelta<IsisRoute> l1delta, @Nullable RibDelta<IsisRoute> l2delta) { if (_vrf.getIsisProcess() == null || _isisIncomingRoutes == null) { return; } // Loop over neighbors, enqueue messages _isisIncomingRoutes .keySet() .forEach( edge -> { VirtualRouter remoteVr = allNodes .get(edge.getNode1().getHostname()) .getVirtualRouters() .get(edge.getNode1().getInterface(allNodes).getVrfName()); Queue<RouteAdvertisement<IsisRoute>> queue = remoteVr._isisIncomingRoutes.get(edge.reverse()); IsisLevel circuitType = edge.getCircuitType(); if (circuitType == IsisLevel.LEVEL_1_2 || circuitType == IsisLevel.LEVEL_1) { queueDelta(queue, l1delta); } if (circuitType == IsisLevel.LEVEL_1_2 || circuitType == IsisLevel.LEVEL_2) { queueDelta(queue, l2delta); if (_vrf.getIsisProcess().getLevel1() != null && _vrf.getIsisProcess().getLevel2() != null && l1delta != null) { // We are a L1_L2 router, we must "upgrade" L1 routes to L2 routes // TODO: a little cumbersome, simplify later RibDelta.Builder<IsisRoute> upgradedRoutes = new RibDelta.Builder<>(null); l1delta .getActions() .forEach( ra -> { Optional<IsisRoute> newRoute = convertRouteLevel1ToLevel2( ra.getRoute(), RoutingProtocol.ISIS_L2.getDefaultAdministrativeCost( _c.getConfigurationFormat())); if (newRoute.isPresent()) { if (ra.isWithdrawn()) { upgradedRoutes.remove(newRoute.get(), ra.getReason()); } else { upgradedRoutes.add(newRoute.get()); } } }); queueDelta(queue, upgradedRoutes.build()); } } }); } /** * Send out OSPF External route updates to our neighbors * * @param type1delta A {@link RibDelta} containing diffs with respect to OSPF Type1 external * routes * @param type2delta A {@link RibDelta} containing diffs with respect to OSPF Type2 external * routes */ private void queueOutgoingOspfExternalRoutes( @Nullable RibDelta<OspfExternalType1Route> type1delta, @Nullable RibDelta<OspfExternalType2Route> type2delta) { if (_vrf.getOspfProcess() == null) { return; } if (_ospfNeighbors != null) { _ospfNeighbors.forEach( (key, ospfLink) -> { if (ospfLink._localOspfArea.getStubType() == StubType.STUB) { return; } // Get remote neighbor's queue by prefix Queue<RouteAdvertisement<OspfExternalRoute>> q = ospfLink._remoteVirtualRouter._ospfExternalIncomingRoutes.get(key); queueDelta(q, type1delta); queueDelta(q, type2delta); }); } } /** * Propagate BGP routes received from neighbours into the appropriate RIBs. As the propagation is * happening, queue appropriate outgoing messages to neighbors as well. * * @param multipathEbgp whether or not EBGP is multipath * @param multipathIbgp whether or not IBGP is multipath * @param stagingDeltas a map of RIB to corresponding delta. Keys are expected to contain {@link * #_ebgpStagingRib} and {@link #_ibgpStagingRib} * @param bgpTopology the bgp peering relationships */ void finalizeBgpRoutesAndQueueOutgoingMessages( boolean multipathEbgp, boolean multipathIbgp, Map<BgpMultipathRib, RibDelta<BgpRoute>> stagingDeltas, final Map<String, Node> allNodes, ValueGraph<BgpPeerConfigId, BgpSessionProperties> bgpTopology, NetworkConfigurations networkConfigurations) { RibDelta<BgpRoute> ebgpStagingDelta = stagingDeltas.get(_ebgpStagingRib); RibDelta<BgpRoute> ibgpStagingDelta = stagingDeltas.get(_ibgpStagingRib); Entry<RibDelta<BgpRoute>, RibDelta<BgpRoute>> e; RibDelta<BgpRoute> ebgpBestPathDelta; if (multipathEbgp) { e = syncBgpDeltaPropagation(_bgpBestPathRib, _bgpMultipathRib, ebgpStagingDelta); ebgpBestPathDelta = e.getKey(); _bgpBestPathDeltaBuilder.from(e.getKey()); _bgpMultiPathDeltaBuilder.from(e.getValue()); } else { ebgpBestPathDelta = importRibDelta(_bgpBestPathRib, ebgpStagingDelta); _bgpBestPathDeltaBuilder.from(ebgpBestPathDelta); _bgpMultiPathDeltaBuilder.from(ebgpBestPathDelta); } if (multipathIbgp) { e = syncBgpDeltaPropagation(_bgpBestPathRib, _bgpMultipathRib, ibgpStagingDelta); _bgpBestPathDeltaBuilder.from(e.getKey()); _bgpMultiPathDeltaBuilder.from(e.getValue()); } else { RibDelta<BgpRoute> ibgpBestPathDelta = importRibDelta(_bgpBestPathRib, ibgpStagingDelta); _bgpBestPathDeltaBuilder.from(ibgpBestPathDelta); _bgpMultiPathDeltaBuilder.from(ibgpBestPathDelta); } _mainRibRouteDeltaBuiler.from(importRibDelta(_mainRib, _bgpMultiPathDeltaBuilder.build())); queueOutgoingBgpRoutes( ebgpBestPathDelta, _bgpMultiPathDeltaBuilder.build(), _mainRibRouteDeltaBuiler.build(), allNodes, bgpTopology, networkConfigurations); } /** * Move IS-IS routes from L1/L2 staging RIBs into their respective "proper" RIBs. Following that, * move any resulting deltas into the combined IS-IS RIB, and finally, main RIB. * * @param allNodes all network nodes, keyed by hostname * @param l1Delta staging Level 1 delta * @param l2Delta staging Level 2 delta * @return true if any routes from given deltas were merged into the combined IS-IS RIB. */ boolean unstageIsisRoutes( Map<String, Node> allNodes, RibDelta<IsisRoute> l1Delta, RibDelta<IsisRoute> l2Delta) { RibDelta<IsisRoute> d1 = importRibDelta(_isisL1Rib, l1Delta); RibDelta<IsisRoute> d2 = importRibDelta(_isisL2Rib, l2Delta); queueOutgoingIsisRoutes(allNodes, d1, d2); Builder<IsisRoute> isisDeltaBuilder = new Builder<>(_isisRib); isisDeltaBuilder.from(importRibDelta(_isisRib, d1)); isisDeltaBuilder.from(importRibDelta(_isisRib, d2)); _mainRibRouteDeltaBuiler.from(importRibDelta(_mainRib, isisDeltaBuilder.build())); return d1 != null || d2 != null; } /** * Merges staged OSPF external routes into the "real" OSPF-external RIBs * * @param type1Delta a {@link RibDelta} indicating changes to be made to {@link * #_ospfExternalType1Rib} * @param type2Delta a {@link RibDelta} indicating changes to be made to {@link * #_ospfExternalType2Rib} */ boolean unstageOspfExternalRoutes( RibDelta<OspfExternalType1Route> type1Delta, RibDelta<OspfExternalType2Route> type2Delta) { RibDelta<OspfExternalType1Route> d1 = importRibDelta(_ospfExternalType1Rib, type1Delta); RibDelta<OspfExternalType2Route> d2 = importRibDelta(_ospfExternalType2Rib, type2Delta); queueOutgoingOspfExternalRoutes(d1, d2); Builder<OspfRoute> ospfDeltaBuilder = new Builder<>(_ospfRib); ospfDeltaBuilder.from(importRibDelta(_ospfRib, d1)); ospfDeltaBuilder.from(importRibDelta(_ospfRib, d2)); _mainRibRouteDeltaBuiler.from(importRibDelta(_mainRib, ospfDeltaBuilder.build())); return d1 != null || d2 != null; } /** Merges staged OSPF internal routes into the "real" OSPF-internal RIBs */ void unstageOspfInternalRoutes() { importRib(_ospfIntraAreaRib, _ospfIntraAreaStagingRib); importRib(_ospfInterAreaRib, _ospfInterAreaStagingRib); } /** Merges staged RIP routes into the "real" RIP RIB */ void unstageRipInternalRoutes() { importRib(_ripInternalRib, _ripInternalStagingRib); } /** Re-initialize RIBs (at the start of each iteration). */ void reinitForNewIteration() { _mainRibRouteDeltaBuiler = new Builder<>(_mainRib); _bgpBestPathDeltaBuilder = new RibDelta.Builder<>(_bgpBestPathRib); _bgpMultiPathDeltaBuilder = new RibDelta.Builder<>(_bgpMultipathRib); _ospfExternalDeltaBuiler = new RibDelta.Builder<>(null); /* * RIBs not read from can just be re-initialized */ _ospfRib = new OspfRib(); _ripRib = new RipRib(); /* * Staging RIBs can also be re-initialized */ MultipathEquivalentAsPathMatchMode mpTieBreaker = _vrf.getBgpProcess() == null ? EXACT_PATH : _vrf.getBgpProcess().getMultipathEquivalentAsPathMatchMode(); _ebgpStagingRib = new BgpMultipathRib(mpTieBreaker); _ibgpStagingRib = new BgpMultipathRib(mpTieBreaker); _ospfExternalType1StagingRib = new OspfExternalType1Rib(getHostname(), null); _ospfExternalType2StagingRib = new OspfExternalType2Rib(getHostname(), null); /* * Add routes that cannot change (does not affect below computation) */ _mainRibRouteDeltaBuiler.from(importRib(_mainRib, _independentRib)); /* * Re-add independent OSPF routes to ospfRib for tie-breaking */ importRib(_ospfRib, _ospfIntraAreaRib); importRib(_ospfRib, _ospfInterAreaRib); /* * Re-add independent RIP routes to ripRib for tie-breaking */ importRib(_ripRib, _ripInternalRib); } /** * Merge intra/inter OSPF RIBs into a general OSPF RIB, then merge that into the independent RIB */ void importOspfInternalRoutes() { importRib(_ospfRib, _ospfIntraAreaRib); importRib(_ospfRib, _ospfInterAreaRib); importRib(_independentRib, _ospfRib); } /** * Check if RIBs that contribute to the dataplane "dependent routes" computation have any routes * that still need to be merged. I.e., if this method returns true, we cannot converge yet. * * @return true if there are any routes remaining, in need of merging in to the RIBs */ boolean hasOutstandingRoutes() { return _ospfExternalDeltaBuiler.build() != null || _mainRibRouteDeltaBuiler.build() != null || _bgpBestPathDeltaBuilder.build() != null || _bgpMultiPathDeltaBuilder.build() != null; } /** * Check if this router has processed all its incoming BGP messages (i.e., all router queues are * empty) * * @return true if all queues are empty. */ boolean hasProcessedAllMessages() { boolean processedAll = true; // Check the BGP message queues if (_vrf.getBgpProcess() != null) { processedAll = _bgpIncomingRoutes .values() .stream() .map(Queue::isEmpty) .noneMatch(Predicate.isEqual(false)); } // Check the OSPF external message queues if (_vrf.getOspfProcess() != null) { for (Queue<RouteAdvertisement<OspfExternalRoute>> queue : _ospfExternalIncomingRoutes.values()) { if (!queue.isEmpty()) { return false; } } } if (_vrf.getIsisProcess() != null) { for (Queue<RouteAdvertisement<IsisRoute>> queue : _isisIncomingRoutes.values()) { if (!queue.isEmpty()) { return false; } } } return processedAll; } /** * Queues initial round of outgoing BGP messages based on the state of the RIBs prior to any data * plane iterations. */ void queueInitialBgpMessages( final ValueGraph<BgpPeerConfigId, BgpSessionProperties> bgpTopology, final Map<String, Node> allNodes, NetworkConfigurations nc) { if (_vrf.getBgpProcess() == null) { // nothing to do return; } for (BgpEdgeId edge : _bgpIncomingRoutes.keySet()) { newBgpSessionEstablishedHook(edge, getBgpSessionProperties(bgpTopology, edge), allNodes, nc); } } /** * Utility "message passing" method between virtual routers. Take a set of BGP {@link * RouteAdvertisement}s and puts them onto a local queue corresponding to the session between * given neighbors. * * @param routes a set of BGP routes that are being exchanged */ private void enqueueBgpMessages( @Nonnull BgpEdgeId edgeId, @Nonnull Set<RouteAdvertisement<BgpRoute>> routes) { _bgpIncomingRoutes.get(edgeId).addAll(routes); } /** Note which advertisement we sent, in full {@link BgpAdvertisement} form. */ private void markSentBgpAdvertisements( BgpPeerConfigId localNeighborId, BgpPeerConfigId remoteNeighborId, BgpPeerConfig localNeighbor, BgpPeerConfig remoteNeighbor, BgpSessionProperties sessionProperties, Set<RouteAdvertisement<BgpRoute>> routeAdvertisements) { for (RouteAdvertisement<BgpRoute> routeAdvertisement : routeAdvertisements) { if (!routeAdvertisement.isWithdrawn()) { BgpRoute route = routeAdvertisement.getRoute(); _sentBgpAdvertisements.add( BgpAdvertisement.builder() .setType( sessionProperties.isEbgp() ? BgpAdvertisementType.EBGP_SENT : BgpAdvertisementType.IBGP_SENT) .setNetwork(route.getNetwork()) .setNextHopIp(route.getNextHopIp()) .setSrcNode(getHostname()) .setSrcVrf(localNeighborId.getVrfName()) .setSrcIp(localNeighbor.getLocalIp()) .setDstNode(remoteNeighborId.getHostname()) .setDstVrf(remoteNeighborId.getVrfName()) .setDstIp(remoteNeighbor.getLocalIp()) .setSrcProtocol( sessionProperties.isEbgp() ? RoutingProtocol.BGP : RoutingProtocol.IBGP) .setOriginType(route.getOriginType()) .setLocalPreference(route.getLocalPreference()) .setMed(route.getMetric()) .setOriginatorIp(route.getOriginatorIp()) .setAsPath(route.getAsPath()) .setCommunities(route.getCommunities()) .setClusterList(route.getClusterList()) .setWeight(-1) .build()); } } } /** Note which advertisement we received, in full {@link BgpAdvertisement} form. */ private void markReceivedBgpAdvertisement( BgpPeerConfigId localNeighborId, BgpPeerConfigId remoteNeighborId, BgpPeerConfig localNeighbor, BgpPeerConfig remoteNeighbor, BgpSessionProperties sessionProperties, BgpRoute route) { _receivedBgpAdvertisements.add( BgpAdvertisement.builder() .setType( sessionProperties.isEbgp() ? BgpAdvertisementType.EBGP_RECEIVED : BgpAdvertisementType.IBGP_RECEIVED) .setNetwork(route.getNetwork()) .setNextHopIp(route.getNextHopIp()) .setSrcNode(remoteNeighborId.getHostname()) .setSrcVrf(remoteNeighborId.getVrfName()) .setSrcIp(remoteNeighbor.getLocalIp()) .setDstNode(getHostname()) .setDstVrf(localNeighborId.getVrfName()) .setDstIp(localNeighbor.getLocalIp()) .setSrcProtocol(route.getProtocol()) .setOriginType(route.getOriginType()) .setLocalPreference(route.getLocalPreference()) .setMed(route.getMetric()) .setOriginatorIp(route.getOriginatorIp()) .setAsPath(route.getAsPath()) .setCommunities(route.getCommunities()) .setClusterList(route.getClusterList()) .setWeight(route.getWeight()) .build()); } /** Deal with a newly established BGP session. */ private void newBgpSessionEstablishedHook( @Nonnull BgpEdgeId edge, @Nonnull BgpSessionProperties sessionProperties, @Nonnull Map<String, Node> allNodes, NetworkConfigurations nc) { BgpPeerConfigId localConfigId = edge.dst(); BgpPeerConfigId remoteConfigId = edge.src(); BgpPeerConfig localConfig = nc.getBgpPeerConfig(localConfigId); BgpPeerConfig remoteConfig = nc.getBgpPeerConfig(remoteConfigId); VirtualRouter remoteVr = getRemoteBgpNeighborVR(remoteConfigId, allNodes); if (remoteVr == null) { return; } // Note prefixes we tried to originate _mainRib.getRoutes().forEach(r -> _prefixTracer.originated(r.getNetwork())); /* * Export route advertisements by looking at main RIB */ Set<RouteAdvertisement<BgpRoute>> exportedRoutes = _mainRib .getRoutes() .stream() // This performs transformations and filtering using the export policy .map( r -> exportBgpRoute( r, localConfigId, remoteConfigId, localConfig, remoteConfig, allNodes, sessionProperties)) .filter(Objects::nonNull) .map(RouteAdvertisement::new) .collect(ImmutableSet.toImmutableSet()); // Call this on the neighbor's VR! remoteVr.enqueueBgpMessages(edge.reverse(), exportedRoutes); /* * Export neighbor-specific generated routes, these routes skip global export policy */ Set<RouteAdvertisement<BgpRoute>> exportedNeighborSpecificRoutes = localConfig .getGeneratedRoutes() .stream() .map(this::processNeighborSpecificGeneratedRoute) .filter(Objects::nonNull) .map(RouteAdvertisement::new) .collect(ImmutableSet.toImmutableSet()); // Call this on the neighbor's VR, and reverse the egde! remoteVr.enqueueBgpMessages(edge.reverse(), exportedNeighborSpecificRoutes); // Note which BGP advertisements were sent markSentBgpAdvertisements( localConfigId, remoteConfigId, localConfig, remoteConfig, sessionProperties, exportedRoutes); markSentBgpAdvertisements( localConfigId, remoteConfigId, localConfig, remoteConfig, sessionProperties, exportedNeighborSpecificRoutes); } /** * Check whether given {@link GeneratedRoute} should be sent to a BGP neighbor. This checks * activation conditions for the generated route, and converts it to a {@link BgpRoute}. No export * policy computation is performed. * * @param generatedRoute route to process * @return a new {@link BgpRoute} if the {@code generatedRoute} was activated. */ @Nullable private BgpRoute processNeighborSpecificGeneratedRoute(@Nonnull GeneratedRoute generatedRoute) { String policyName = generatedRoute.getGenerationPolicy(); RoutingPolicy policy = policyName != null ? _c.getRoutingPolicies().get(policyName) : null; GeneratedRoute.Builder builder = GeneratedRouteHelper.activateGeneratedRoute( generatedRoute, policy, _mainRib.getRoutes(), _vrf.getName()); return builder != null ? BgpProtocolHelper.convertGeneratedRouteToBgp( builder.build(), _vrf.getBgpProcess().getRouterId()) : null; } /** * Compute our OSPF neighbors. * * @param allNodes map of all network nodes, keyed by hostname * @param topology the Layer-3 network topology * @return A sorted map of neighbor prefixes to links to which they correspond */ @Nullable SortedMap<Prefix, OspfLink> getOspfNeighbors( final Map<String, Node> allNodes, Topology topology) { // Check we have ospf process OspfProcess proc = _vrf.getOspfProcess(); if (proc == null) { return null; } String node = _c.getHostname(); SortedSet<Edge> edges = topology.getNodeEdges().get(node); if (edges == null) { // there are no edges, so OSPF won't produce anything return null; } SortedMap<Prefix, OspfLink> neighbors = new TreeMap<>(); for (Edge edge : edges) { if (!edge.getNode1().equals(node)) { continue; } String connectingInterfaceName = edge.getInt1(); Interface connectingInterface = _vrf.getInterfaces().get(connectingInterfaceName); if (connectingInterface == null) { // wrong vrf, so skip continue; } String neighborName = edge.getNode2(); Node neighbor = allNodes.get(neighborName); String neighborInterfaceName = edge.getInt2(); OspfArea area = connectingInterface.getOspfArea(); Configuration nc = neighbor.getConfiguration(); Interface neighborInterface = nc.getInterfaces().get(neighborInterfaceName); String neighborVrfName = neighborInterface.getVrfName(); VirtualRouter neighborVirtualRouter = allNodes.get(neighborName).getVirtualRouters().get(neighborVrfName); OspfArea neighborArea = neighborInterface.getOspfArea(); if (connectingInterface.getOspfEnabled() && !connectingInterface.getOspfPassive() && neighborInterface.getOspfEnabled() && !neighborInterface.getOspfPassive() && area != null && neighborArea != null && area.getName().equals(neighborArea.getName())) { neighbors.put( connectingInterface.getAddress().getPrefix(), new OspfLink(area, neighborArea, neighborVirtualRouter)); } } return ImmutableSortedMap.copyOf(neighbors); } public Configuration getConfiguration() { return _c; } ConnectedRib getConnectedRib() { return _connectedRib; } public Fib getFib() { return _fib; } Rib getMainRib() { return _mainRib; } BgpBestPathRib getBgpBestPathRib() { return _bgpBestPathRib; } /** Convenience method to get the VirtualRouter's hostname */ String getHostname() { return _c.getHostname(); } /** * Compute the "hashcode" of this router for the iBDP purposes. The hashcode is computed from the * following data structures: * * <ul> * <li>"external" RIBs ({@link #_mainRib}, {@link #_ospfExternalType1Rib}, {@link * #_ospfExternalType2Rib} * <li>message queues ({@link #_bgpIncomingRoutes} and {@link #_ospfExternalIncomingRoutes}) * </ul> * * @return integer hashcode */ int computeIterationHashCode() { return _mainRib.getRoutes().hashCode() + _ospfExternalType1Rib.getRoutes().hashCode() + _ospfExternalType2Rib.getRoutes().hashCode() + _bgpIncomingRoutes .values() .stream() .flatMap(Queue::stream) .mapToInt(RouteAdvertisement::hashCode) .sum() + _ospfExternalIncomingRoutes .values() .stream() .flatMap(Queue::stream) .mapToInt(RouteAdvertisement::hashCode) .sum() + _isisIncomingRoutes .values() .stream() .flatMap(Queue::stream) .mapToInt(RouteAdvertisement::hashCode) .sum(); } PrefixTracer getPrefixTracer() { return _prefixTracer; } /** * Given an {@link AbstractRoute}, run it through the BGP outbound transformations and export * routing policy. * * @param exportCandidate a route to try and export * @param ourConfig {@link BgpPeerConfig} that sends the route * @param remoteConfig {@link BgpPeerConfig} that will be receiving the route * @param allNodes all nodes in the network * @return The transformed route as a {@link BgpRoute}, or {@code null} if the route should not be * exported. */ @Nullable private BgpRoute exportBgpRoute( @Nonnull AbstractRoute exportCandidate, @Nonnull BgpPeerConfigId ourConfigId, @Nonnull BgpPeerConfigId remoteConfigId, @Nonnull BgpPeerConfig ourConfig, @Nonnull BgpPeerConfig remoteConfig, @Nonnull Map<String, Node> allNodes, @Nonnull BgpSessionProperties sessionProperties) { RoutingPolicy exportPolicy = _c.getRoutingPolicies().get(ourConfig.getExportPolicy()); BgpRoute.Builder transformedOutgoingRouteBuilder; try { transformedOutgoingRouteBuilder = BgpProtocolHelper.transformBgpRouteOnExport( ourConfig, remoteConfig, sessionProperties, _vrf, requireNonNull(getRemoteBgpNeighborVR(remoteConfigId, allNodes))._vrf, exportCandidate); } catch (BgpRoutePropagationException e) { // TODO: Log a warning return null; } if (transformedOutgoingRouteBuilder == null) { // This route could not be exported for core bgp protocol reasons return null; } // Process transformed outgoing route by the export policy boolean shouldExport = exportPolicy.process( exportCandidate, transformedOutgoingRouteBuilder, remoteConfig.getLocalIp(), ourConfigId.getRemotePeerPrefix(), ourConfigId.getVrfName(), Direction.OUT); VirtualRouter remoteVr = getRemoteBgpNeighborVR(remoteConfigId, allNodes); if (!shouldExport) { // This route could not be exported due to export policy _prefixTracer.filtered( exportCandidate.getNetwork(), requireNonNull(remoteVr).getHostname(), remoteConfig.getLocalIp(), remoteConfigId.getVrfName(), ourConfig.getExportPolicy(), Direction.OUT); return null; } // Successfully exported route BgpRoute transformedOutgoingRoute = transformedOutgoingRouteBuilder.build(); _prefixTracer.sentTo( transformedOutgoingRoute.getNetwork(), requireNonNull(remoteVr).getHostname(), remoteConfig.getLocalIp(), remoteConfigId.getVrfName(), ourConfig.getExportPolicy()); return transformedOutgoingRoute; } Set<BgpAdvertisement> getReceivedBgpAdvertisements() { return _receivedBgpAdvertisements; } Set<BgpAdvertisement> getSentBgpAdvertisements() { return _sentBgpAdvertisements; } public BgpMultipathRib getBgpMultipathRib() { return _bgpMultipathRib; } }
projects/batfish/src/main/java/org/batfish/dataplane/ibdp/VirtualRouter.java
package org.batfish.dataplane.ibdp; import static com.google.common.base.MoreObjects.firstNonNull; import static java.util.Objects.requireNonNull; import static org.batfish.common.util.CommonUtil.toImmutableSortedMap; import static org.batfish.datamodel.MultipathEquivalentAsPathMatchMode.EXACT_PATH; import static org.batfish.dataplane.protocols.IsisProtocolHelper.convertRouteLevel1ToLevel2; import static org.batfish.dataplane.protocols.StaticRouteHelper.isInterfaceRoute; import static org.batfish.dataplane.protocols.StaticRouteHelper.shouldActivateNextHopIpRoute; import static org.batfish.dataplane.rib.AbstractRib.importRib; import static org.batfish.dataplane.rib.RibDelta.importRibDelta; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.ImmutableSortedSet; import com.google.common.graph.Network; import com.google.common.graph.ValueGraph; import java.util.AbstractMap.SimpleEntry; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.Collections; import java.util.IdentityHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Optional; import java.util.Queue; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.batfish.common.BatfishException; import org.batfish.common.util.ComparableStructure; import org.batfish.datamodel.AbstractRoute; import org.batfish.datamodel.AsPath; import org.batfish.datamodel.BgpActivePeerConfig; import org.batfish.datamodel.BgpAdvertisement; import org.batfish.datamodel.BgpAdvertisement.BgpAdvertisementType; import org.batfish.datamodel.BgpPeerConfig; import org.batfish.datamodel.BgpPeerConfigId; import org.batfish.datamodel.BgpProcess; import org.batfish.datamodel.BgpRoute; import org.batfish.datamodel.BgpSessionProperties; import org.batfish.datamodel.BgpTieBreaker; import org.batfish.datamodel.Configuration; import org.batfish.datamodel.ConnectedRoute; import org.batfish.datamodel.Edge; import org.batfish.datamodel.Fib; import org.batfish.datamodel.FibImpl; import org.batfish.datamodel.GeneratedRoute; import org.batfish.datamodel.Interface; import org.batfish.datamodel.InterfaceAddress; import org.batfish.datamodel.Ip; import org.batfish.datamodel.IsisInterfaceLevelSettings; import org.batfish.datamodel.IsisInterfaceMode; import org.batfish.datamodel.IsisInterfaceSettings; import org.batfish.datamodel.IsisLevel; import org.batfish.datamodel.IsisLevelSettings; import org.batfish.datamodel.IsisProcess; import org.batfish.datamodel.IsisRoute; import org.batfish.datamodel.LocalRoute; import org.batfish.datamodel.MultipathEquivalentAsPathMatchMode; import org.batfish.datamodel.NetworkConfigurations; import org.batfish.datamodel.OriginType; import org.batfish.datamodel.OspfExternalRoute; import org.batfish.datamodel.OspfExternalType1Route; import org.batfish.datamodel.OspfExternalType2Route; import org.batfish.datamodel.OspfInterAreaRoute; import org.batfish.datamodel.OspfInternalRoute; import org.batfish.datamodel.OspfIntraAreaRoute; import org.batfish.datamodel.OspfRoute; import org.batfish.datamodel.Prefix; import org.batfish.datamodel.RipInternalRoute; import org.batfish.datamodel.RipProcess; import org.batfish.datamodel.Route; import org.batfish.datamodel.RoutingProtocol; import org.batfish.datamodel.StaticRoute; import org.batfish.datamodel.Topology; import org.batfish.datamodel.Vrf; import org.batfish.datamodel.ospf.OspfArea; import org.batfish.datamodel.ospf.OspfAreaSummary; import org.batfish.datamodel.ospf.OspfMetricType; import org.batfish.datamodel.ospf.OspfProcess; import org.batfish.datamodel.ospf.StubType; import org.batfish.datamodel.routing_policy.Environment.Direction; import org.batfish.datamodel.routing_policy.RoutingPolicy; import org.batfish.dataplane.exceptions.BgpRoutePropagationException; import org.batfish.dataplane.protocols.BgpProtocolHelper; import org.batfish.dataplane.protocols.GeneratedRouteHelper; import org.batfish.dataplane.protocols.OspfProtocolHelper; import org.batfish.dataplane.rib.BgpBestPathRib; import org.batfish.dataplane.rib.BgpMultipathRib; import org.batfish.dataplane.rib.ConnectedRib; import org.batfish.dataplane.rib.IsisLevelRib; import org.batfish.dataplane.rib.IsisRib; import org.batfish.dataplane.rib.LocalRib; import org.batfish.dataplane.rib.OspfExternalType1Rib; import org.batfish.dataplane.rib.OspfExternalType2Rib; import org.batfish.dataplane.rib.OspfInterAreaRib; import org.batfish.dataplane.rib.OspfIntraAreaRib; import org.batfish.dataplane.rib.OspfRib; import org.batfish.dataplane.rib.Rib; import org.batfish.dataplane.rib.RibDelta; import org.batfish.dataplane.rib.RibDelta.Builder; import org.batfish.dataplane.rib.RipInternalRib; import org.batfish.dataplane.rib.RipRib; import org.batfish.dataplane.rib.RouteAdvertisement; import org.batfish.dataplane.rib.RouteAdvertisement.Reason; import org.batfish.dataplane.rib.StaticRib; import org.batfish.dataplane.topology.BgpEdgeId; import org.batfish.dataplane.topology.IsisEdge; import org.batfish.dataplane.topology.IsisNode; public class VirtualRouter extends ComparableStructure<String> { private static final long serialVersionUID = 1L; /** Parent configuration for this Virtual router */ private final Configuration _c; /** Route dependency tracker for BGP aggregate routes */ private transient RouteDependencyTracker<BgpRoute, AbstractRoute> _bgpAggDeps = new RouteDependencyTracker<>(); /** Best-path BGP RIB */ BgpBestPathRib _bgpBestPathRib; /** Builder for constructing {@link RibDelta} as pertains to the best-path BGP RIB */ private transient RibDelta.Builder<BgpRoute> _bgpBestPathDeltaBuilder; /** Incoming messages into this router from each BGP neighbor */ transient SortedMap<BgpEdgeId, Queue<RouteAdvertisement<BgpRoute>>> _bgpIncomingRoutes; /** BGP multipath RIB */ BgpMultipathRib _bgpMultipathRib; /** Builder for constructing {@link RibDelta} as pertains to the multipath BGP RIB */ private transient RibDelta.Builder<BgpRoute> _bgpMultiPathDeltaBuilder; /** The RIB containing connected routes */ private transient ConnectedRib _connectedRib; /** Helper RIB containing best paths obtained with external BGP */ transient BgpBestPathRib _ebgpBestPathRib; /** Helper RIB containing all paths obtained with external BGP */ transient BgpMultipathRib _ebgpMultipathRib; /** * Helper RIB containing paths obtained with external eBGP during current iteration. An Adj-RIB of * sorts. */ transient BgpMultipathRib _ebgpStagingRib; /** Helper RIB containing best paths obtained with iBGP */ transient BgpBestPathRib _ibgpBestPathRib; /** Helper RIB containing all paths obtained with iBGP */ transient BgpMultipathRib _ibgpMultipathRib; /** * Helper RIB containing paths obtained with iBGP during current iteration. An Adj-RIB of sorts. */ transient BgpMultipathRib _ibgpStagingRib; /** * The independent RIB contains connected and static routes, which are unaffected by BDP * iterations (hence, independent). */ transient Rib _independentRib; /** Incoming messages into this router from each IS-IS circuit */ transient SortedMap<IsisEdge, Queue<RouteAdvertisement<IsisRoute>>> _isisIncomingRoutes; transient IsisLevelRib _isisL1Rib; transient IsisLevelRib _isisL2Rib; transient IsisLevelRib _isisL1StagingRib; transient IsisLevelRib _isisL2StagingRib; transient IsisRib _isisRib; transient LocalRib _localRib; /** The finalized RIB, a combination different protocol RIBs */ Rib _mainRib; /** Keeps track of changes to the main RIB */ private transient RibDelta.Builder<AbstractRoute> _mainRibRouteDeltaBuiler; transient OspfExternalType1Rib _ospfExternalType1Rib; transient OspfExternalType1Rib _ospfExternalType1StagingRib; transient OspfExternalType2Rib _ospfExternalType2Rib; transient OspfExternalType2Rib _ospfExternalType2StagingRib; @VisibleForTesting transient SortedMap<Prefix, Queue<RouteAdvertisement<OspfExternalRoute>>> _ospfExternalIncomingRoutes; transient OspfInterAreaRib _ospfInterAreaRib; transient OspfInterAreaRib _ospfInterAreaStagingRib; transient OspfIntraAreaRib _ospfIntraAreaRib; transient OspfIntraAreaRib _ospfIntraAreaStagingRib; transient OspfRib _ospfRib; /** * Set of all valid BGP routes we have received during the DP computation. Used to fill gaps in * BGP RIBs when routes are withdrawn. */ private Map<Prefix, SortedSet<BgpRoute>> _receivedBgpRoutes; /** Set of all received BGP advertisements in {@link BgpAdvertisement} form */ private Set<BgpAdvertisement> _receivedBgpAdvertisements; /** Set of all valid IS-IS level-1 routes that we know about */ private Map<Prefix, SortedSet<IsisRoute>> _receivedIsisL1Routes; /** Set of all valid IS-IS level-2 routes that we know about */ private Map<Prefix, SortedSet<IsisRoute>> _receivedIsisL2Routes; /** Set of all valid OSPF external Type 1 routes that we know about */ private Map<Prefix, SortedSet<OspfExternalType1Route>> _receivedOspExternalType1Routes; /** Set of all valid OSPF external Type 2 routes that we know about */ private Map<Prefix, SortedSet<OspfExternalType2Route>> _receivedOspExternalType2Routes; transient RipInternalRib _ripInternalRib; transient RipInternalRib _ripInternalStagingRib; transient RipRib _ripRib; /** Set of all sent BGP advertisements in {@link BgpAdvertisement} form */ Set<BgpAdvertisement> _sentBgpAdvertisements; transient StaticRib _staticInterfaceRib; transient StaticRib _staticNextHopRib; /** FIB (forwarding information base) built from the main RIB */ private Fib _fib; /** RIB containing generated routes */ private transient Rib _generatedRib; private transient RibDelta.Builder<OspfExternalRoute> _ospfExternalDeltaBuiler; private transient Map<Prefix, OspfLink> _ospfNeighbors; // TODO: make non-transient. Currently transient because de-serialization crashes. /** Metadata about propagated prefixes to/from neighbors */ private transient PrefixTracer _prefixTracer; /** A {@link Vrf} that this virtual router represents */ final Vrf _vrf; VirtualRouter(final String name, final Configuration c) { super(name); _c = c; _vrf = c.getVrfs().get(name); initRibs(); // Keep track of sent and received advertisements _receivedBgpAdvertisements = new LinkedHashSet<>(); _sentBgpAdvertisements = new LinkedHashSet<>(); _receivedIsisL1Routes = new TreeMap<>(); _receivedIsisL2Routes = new TreeMap<>(); _receivedOspExternalType1Routes = new TreeMap<>(); _receivedOspExternalType2Routes = new TreeMap<>(); _receivedBgpRoutes = new TreeMap<>(); _bgpIncomingRoutes = new TreeMap<BgpEdgeId, Queue<RouteAdvertisement<BgpRoute>>>(); _prefixTracer = new PrefixTracer(); } /** * Convert a given RibDelta into {@link RouteAdvertisement} objects and enqueue them onto a given * queue. * * @param queue the message queue * @param delta {@link RibDelta} representing changes. */ @VisibleForTesting static <R extends AbstractRoute, D extends R> void queueDelta( Queue<RouteAdvertisement<R>> queue, @Nullable RibDelta<D> delta) { if (delta == null) { // Nothing to do return; } for (RouteAdvertisement<D> r : delta.getActions()) { // REPLACE does not make sense across routers, update with WITHDRAW Reason reason = r.getReason() == Reason.REPLACE ? Reason.WITHDRAW : r.getReason(); queue.add(new RouteAdvertisement<>(r.getRoute(), r.isWithdrawn(), reason)); } } static Entry<RibDelta<BgpRoute>, RibDelta<BgpRoute>> syncBgpDeltaPropagation( BgpBestPathRib bestPathRib, BgpMultipathRib multiPathRib, RibDelta<BgpRoute> delta) { // Build our first attempt at best path delta Builder<BgpRoute> bestDeltaBuilder = new Builder<>(bestPathRib); bestDeltaBuilder.from(importRibDelta(bestPathRib, delta)); RibDelta<BgpRoute> bestPathDelta = bestDeltaBuilder.build(); Builder<BgpRoute> mpBuilder = new Builder<>(multiPathRib); mpBuilder.from(importRibDelta(multiPathRib, bestPathDelta)); if (bestPathDelta != null) { /* * Handle mods to the best path RIB */ for (Prefix p : bestPathDelta.getPrefixes()) { List<RouteAdvertisement<BgpRoute>> actions = bestPathDelta.getActions(p); if (actions != null) { if (actions .stream() .map(RouteAdvertisement::getReason) .anyMatch(Predicate.isEqual(Reason.REPLACE))) { /* * Clear routes for prefixes where best path RIB was modified, because * a better route was chosen, and whatever we had in multipathRib is now invalid */ mpBuilder.from(multiPathRib.clearRoutes(p)); } else if (actions .stream() .map(RouteAdvertisement::getReason) .anyMatch(Predicate.isEqual(Reason.WITHDRAW))) { /* * Routes for that prefix were withdrawn. See if we have anything in the multipath RIB * to fix it. * Create a fake delta, let the routes fight it out for best path in the merge process */ RibDelta<BgpRoute> fakeDelta = new Builder<BgpRoute>(null).add(multiPathRib.getRoutes(p)).build(); bestDeltaBuilder.from(importRibDelta(bestPathRib, fakeDelta)); } } } } // Set the (possibly updated) best path delta bestPathDelta = bestDeltaBuilder.build(); // Update best paths multiPathRib.setBestAsPaths(bestPathRib.getBestAsPaths()); // Only iterate over valid prefixes (ones in best-path RIB) and see if anything should go into // multi-path RIB for (Prefix p : bestPathRib.getPrefixes()) { mpBuilder.from(importRibDelta(multiPathRib, delta, p)); } return new SimpleImmutableEntry<>(bestPathDelta, mpBuilder.build()); } /** Lookup the VirtualRouter owner of a remote BGP neighbor. */ @Nullable @VisibleForTesting static VirtualRouter getRemoteBgpNeighborVR( @Nonnull BgpPeerConfigId bgpId, @Nonnull final Map<String, Node> allNodes) { return allNodes.get(bgpId.getHostname()).getVirtualRouters().get(bgpId.getVrfName()); } /** * Initializes helper data structures and easy-to-compute RIBs that are not affected by BDP * iterations (e.g., static route RIB, connected route RIB, etc.) */ @VisibleForTesting void initForIgpComputation() { initConnectedRib(); initLocalRib(); initStaticRibs(); importRib(_independentRib, _connectedRib); importRib(_independentRib, _localRib); importRib(_independentRib, _staticInterfaceRib); importRib(_mainRib, _independentRib); initIntraAreaOspfRoutes(); initBaseRipRoutes(); } /** * Prep for the Egp part of the computation * * @param allNodes map of all network nodes, keyed by hostname * @param bgpTopology the bgp peering relationships */ void initForEgpComputation( final Map<String, Node> allNodes, Topology topology, ValueGraph<BgpPeerConfigId, BgpSessionProperties> bgpTopology, Network<IsisNode, IsisEdge> isisTopology) { initQueuesAndDeltaBuilders(allNodes, topology, bgpTopology, isisTopology); } /** * Initializes RIB delta builders and protocol message queues. * * @param allNodes map of all network nodes, keyed by hostname * @param topology Layer 3 network topology * @param bgpTopology the bgp peering relationships */ @VisibleForTesting void initQueuesAndDeltaBuilders( final Map<String, Node> allNodes, final Topology topology, ValueGraph<BgpPeerConfigId, BgpSessionProperties> bgpTopology, Network<IsisNode, IsisEdge> isisTopology) { // Initialize message queues for each BGP neighbor initBgpQueues(bgpTopology); initIsisQueues(isisTopology); // Initialize message queues for each Ospf neighbor if (_vrf.getOspfProcess() == null) { _ospfExternalIncomingRoutes = ImmutableSortedMap.of(); } else { _ospfNeighbors = getOspfNeighbors(allNodes, topology); if (_ospfNeighbors == null) { _ospfExternalIncomingRoutes = ImmutableSortedMap.of(); } else { _ospfExternalIncomingRoutes = _ospfNeighbors .keySet() .stream() .collect( ImmutableSortedMap.toImmutableSortedMap( Prefix::compareTo, Function.identity(), p -> new ConcurrentLinkedQueue<>())); } } } /** * Initialize incoming BGP message queues. * * @param bgpTopology source of truth for which sessions get established. */ void initBgpQueues(ValueGraph<BgpPeerConfigId, BgpSessionProperties> bgpTopology) { if (_vrf.getBgpProcess() == null) { _bgpIncomingRoutes = ImmutableSortedMap.of(); } else { _bgpIncomingRoutes = Stream.concat( _vrf.getBgpProcess() .getActiveNeighbors() .entrySet() .stream() .map( e -> new BgpPeerConfigId( getHostname(), _vrf.getName(), e.getKey(), false)), _vrf.getBgpProcess() .getPassiveNeighbors() .entrySet() .stream() .map( e -> new BgpPeerConfigId(getHostname(), _vrf.getName(), e.getKey(), true))) .filter(bgpTopology.nodes()::contains) .flatMap( dst -> bgpTopology.adjacentNodes(dst).stream().map(src -> new BgpEdgeId(src, dst))) .collect( toImmutableSortedMap(Function.identity(), e -> new ConcurrentLinkedQueue<>())); } } private void initIsisQueues(Network<IsisNode, IsisEdge> isisTopology) { // Initialize message queues for each IS-IS circuit if (_vrf.getIsisProcess() == null) { _isisIncomingRoutes = ImmutableSortedMap.of(); } else { _isisIncomingRoutes = _vrf.getInterfaceNames() .stream() .map(ifaceName -> new IsisNode(_c.getHostname(), ifaceName)) .filter(isisTopology.nodes()::contains) .flatMap(n -> isisTopology.inEdges(n).stream()) .collect( toImmutableSortedMap(Function.identity(), e -> new ConcurrentLinkedQueue<>())); } } /** * Activate generated routes. * * @return a new {@link RibDelta} if a new route has been activated, otherwise {@code null} */ @VisibleForTesting RibDelta<AbstractRoute> activateGeneratedRoutes() { RibDelta.Builder<AbstractRoute> builder = new Builder<>(_generatedRib); /* * Loop over all generated routes and check whether any of the contributing routes can trigger * activation. */ for (GeneratedRoute gr : _vrf.getGeneratedRoutes()) { String policyName = gr.getGenerationPolicy(); RoutingPolicy generationPolicy = policyName != null ? _c.getRoutingPolicies().get(gr.getGenerationPolicy()) : null; GeneratedRoute.Builder grb = GeneratedRouteHelper.activateGeneratedRoute( gr, generationPolicy, _mainRib.getRoutes(), _vrf.getName()); if (grb != null) { GeneratedRoute newGr = grb.build(); // Routes have been changed RibDelta<AbstractRoute> d = _generatedRib.mergeRouteGetDelta(newGr); builder.from(d); } } return builder.build(); } /** * Recompute generated routes. If new generated routes were activated, process them into the main * RIB. Check if any BGP aggregates were affected by the new generated routes. */ void recomputeGeneratedRoutes() { RibDelta<AbstractRoute> d; RibDelta.Builder<AbstractRoute> generatedRouteDeltaBuilder = new Builder<>(_mainRib); do { d = activateGeneratedRoutes(); generatedRouteDeltaBuilder.from(d); } while (d != null); d = generatedRouteDeltaBuilder.build(); // Update main rib as well _mainRibRouteDeltaBuiler.from(importRibDelta(_mainRib, d)); /* * Check dependencies for BGP aggregates. * * Updates from these BGP deltas into mainRib will be handled in finalizeBgp routes */ if (d != null) { d.getActions() .stream() .filter(RouteAdvertisement::isWithdrawn) .forEach( r -> { _bgpBestPathDeltaBuilder.from( _bgpAggDeps.deleteRoute(r.getRoute(), _bgpBestPathRib)); _bgpMultiPathDeltaBuilder.from( _bgpAggDeps.deleteRoute(r.getRoute(), _bgpMultipathRib)); }); } } /** * Activate static routes with next hop IP. Adds a static route {@code route} to the main RIB if * there exists an active route to the {@code routes}'s next-hop-ip. * * <p>Removes static route from the main RIB for which next-hop-ip has become unreachable. */ void activateStaticRoutes() { for (StaticRoute sr : _staticNextHopRib.getRoutes()) { if (shouldActivateNextHopIpRoute(sr, _mainRib)) { _mainRibRouteDeltaBuiler.from(_mainRib.mergeRouteGetDelta(sr)); } else { /* * If the route is not in the RIB, this has no effect. But might add some overhead (TODO) */ _mainRibRouteDeltaBuiler.from(_mainRib.removeRouteGetDelta(sr, Reason.WITHDRAW)); } } } /** Compute the FIB from the main RIB */ public void computeFib() { _fib = new FibImpl(_mainRib); } boolean computeInterAreaSummaries() { OspfProcess proc = _vrf.getOspfProcess(); boolean changed = false; // Ensure we have a running OSPF process on the VRF, otherwise bail. if (proc == null) { return false; } // Admin cost for the given protocol int admin = RoutingProtocol.OSPF_IA.getSummaryAdministrativeCost(_c.getConfigurationFormat()); // Determine whether to use min metric by default, based on RFC1583 compatibility setting. // Routers (at least Cisco and Juniper) default to min metric unless using RFC2328 with // RFC1583 compatibility explicitly disabled, in which case they default to max. boolean useMin = firstNonNull(proc.getRfc1583Compatible(), Boolean.TRUE); // Compute summaries for each area for (Entry<Long, OspfArea> e : proc.getAreas().entrySet()) { long areaNum = e.getKey(); OspfArea area = e.getValue(); for (Entry<Prefix, OspfAreaSummary> e2 : area.getSummaries().entrySet()) { Prefix prefix = e2.getKey(); OspfAreaSummary summary = e2.getValue(); // Only advertised summaries can contribute if (!summary.getAdvertised()) { continue; } Long metric = summary.getMetric(); if (summary.getMetric() == null) { // No metric was configured; compute it from any possible contributing routes. for (OspfIntraAreaRoute contributingRoute : _ospfIntraAreaRib.getRoutes()) { metric = OspfProtocolHelper.computeUpdatedOspfSummaryMetric( contributingRoute, prefix, metric, areaNum, useMin); } for (OspfInterAreaRoute contributingRoute : _ospfInterAreaRib.getRoutes()) { metric = OspfProtocolHelper.computeUpdatedOspfSummaryMetric( contributingRoute, prefix, metric, areaNum, useMin); } } // No routes contributed to the summary, nothing to construct if (metric == null) { continue; } // Non-null metric means we generate a new summary and put it in the RIB OspfInterAreaRoute summaryRoute = new OspfInterAreaRoute(prefix, Ip.ZERO, admin, metric, areaNum); if (_ospfInterAreaStagingRib.mergeRouteGetDelta(summaryRoute) != null) { changed = true; } } } return changed; } /** * Initializes BGP RIBs prior to any dataplane iterations based on the external BGP advertisements * coming into the network * * @param externalAdverts a set of external BGP advertisements * @param ipOwners mapping of IPs to their owners in our network * @param bgpTopology the bgp peering relationships */ void initBaseBgpRibs( Set<BgpAdvertisement> externalAdverts, Map<Ip, Set<String>> ipOwners, final Map<String, Node> allNodes, ValueGraph<BgpPeerConfigId, BgpSessionProperties> bgpTopology, NetworkConfigurations networkConfigurations) { BgpProcess proc = _vrf.getBgpProcess(); if (proc == null) { // Nothing to do return; } // Keep track of changes to the RIBs using delta builders, keyed by RIB type Map<BgpMultipathRib, RibDelta.Builder<BgpRoute>> ribDeltas = new IdentityHashMap<>(); ribDeltas.put(_ebgpStagingRib, new Builder<>(_ebgpStagingRib)); ribDeltas.put(_ibgpStagingRib, new Builder<>(_ibgpStagingRib)); // initialize admin costs for routes int ebgpAdmin = RoutingProtocol.BGP.getDefaultAdministrativeCost(_c.getConfigurationFormat()); int ibgpAdmin = RoutingProtocol.IBGP.getDefaultAdministrativeCost(_c.getConfigurationFormat()); BgpRoute.Builder outgoingRouteBuilder = new BgpRoute.Builder(); // Process each BGP advertisement for (BgpAdvertisement advert : externalAdverts) { // If it is not for us, ignore it if (!advert.getDstNode().equals(_c.getHostname())) { continue; } // If we don't own the IP for this advertisement, ignore it Ip dstIp = advert.getDstIp(); Set<String> dstIpOwners = ipOwners.get(dstIp); String hostname = _c.getHostname(); if (dstIpOwners == null || !dstIpOwners.contains(hostname)) { continue; } Ip srcIp = advert.getSrcIp(); // TODO: support passive bgp connections Prefix srcPrefix = new Prefix(srcIp, Prefix.MAX_PREFIX_LENGTH); BgpPeerConfig neighbor = _vrf.getBgpProcess().getActiveNeighbors().get(srcPrefix); if (neighbor == null) { continue; } // Build a route based on the type of this advertisement BgpAdvertisementType type = advert.getType(); boolean ebgp; boolean received; switch (type) { case EBGP_RECEIVED: ebgp = true; received = true; break; case EBGP_SENT: ebgp = true; received = false; break; case IBGP_RECEIVED: ebgp = false; received = true; break; case IBGP_SENT: ebgp = false; received = false; break; case EBGP_ORIGINATED: case IBGP_ORIGINATED: default: throw new BatfishException("Missing or invalid bgp advertisement type"); } BgpMultipathRib targetRib = ebgp ? _ebgpStagingRib : _ibgpStagingRib; RoutingProtocol targetProtocol = ebgp ? RoutingProtocol.BGP : RoutingProtocol.IBGP; if (received) { int admin = ebgp ? ebgpAdmin : ibgpAdmin; AsPath asPath = advert.getAsPath(); SortedSet<Long> clusterList = advert.getClusterList(); SortedSet<Long> communities = ImmutableSortedSet.copyOf(advert.getCommunities()); int localPreference = advert.getLocalPreference(); long metric = advert.getMed(); Prefix network = advert.getNetwork(); Ip nextHopIp = advert.getNextHopIp(); Ip originatorIp = advert.getOriginatorIp(); OriginType originType = advert.getOriginType(); RoutingProtocol srcProtocol = advert.getSrcProtocol(); int weight = advert.getWeight(); BgpRoute.Builder builder = new BgpRoute.Builder(); builder.setAdmin(admin); builder.setAsPath(asPath.getAsSets()); builder.setClusterList(clusterList); builder.setCommunities(communities); builder.setLocalPreference(localPreference); builder.setMetric(metric); builder.setNetwork(network); builder.setNextHopIp(nextHopIp); builder.setOriginatorIp(originatorIp); builder.setOriginType(originType); builder.setProtocol(targetProtocol); // TODO: support external route reflector clients builder.setReceivedFromIp(advert.getSrcIp()); builder.setReceivedFromRouteReflectorClient(false); builder.setSrcProtocol(srcProtocol); // TODO: possibly support setting tag builder.setWeight(weight); BgpRoute route = builder.build(); ribDeltas.get(targetRib).from(targetRib.mergeRouteGetDelta(route)); } else { int localPreference; if (ebgp) { localPreference = BgpRoute.DEFAULT_LOCAL_PREFERENCE; } else { localPreference = advert.getLocalPreference(); } outgoingRouteBuilder.setAsPath(advert.getAsPath().getAsSets()); outgoingRouteBuilder.setCommunities(ImmutableSortedSet.copyOf(advert.getCommunities())); outgoingRouteBuilder.setLocalPreference(localPreference); outgoingRouteBuilder.setMetric(advert.getMed()); outgoingRouteBuilder.setNetwork(advert.getNetwork()); outgoingRouteBuilder.setNextHopIp(advert.getNextHopIp()); outgoingRouteBuilder.setOriginatorIp(advert.getOriginatorIp()); outgoingRouteBuilder.setOriginType(advert.getOriginType()); outgoingRouteBuilder.setProtocol(targetProtocol); outgoingRouteBuilder.setReceivedFromIp(advert.getSrcIp()); // TODO: // outgoingRouteBuilder.setReceivedFromRouteReflectorClient(...); outgoingRouteBuilder.setSrcProtocol(advert.getSrcProtocol()); BgpRoute transformedOutgoingRoute = outgoingRouteBuilder.build(); BgpRoute.Builder transformedIncomingRouteBuilder = new BgpRoute.Builder(); // Incoming originatorIp transformedIncomingRouteBuilder.setOriginatorIp(transformedOutgoingRoute.getOriginatorIp()); // Incoming receivedFromIp transformedIncomingRouteBuilder.setReceivedFromIp( transformedOutgoingRoute.getReceivedFromIp()); // Incoming clusterList transformedIncomingRouteBuilder .getClusterList() .addAll(transformedOutgoingRoute.getClusterList()); // Incoming receivedFromRouteReflectorClient transformedIncomingRouteBuilder.setReceivedFromRouteReflectorClient( transformedOutgoingRoute.getReceivedFromRouteReflectorClient()); // Incoming asPath transformedIncomingRouteBuilder.setAsPath(transformedOutgoingRoute.getAsPath().getAsSets()); // Incoming communities transformedIncomingRouteBuilder .getCommunities() .addAll(transformedOutgoingRoute.getCommunities()); // Incoming protocol transformedIncomingRouteBuilder.setProtocol(targetProtocol); // Incoming network transformedIncomingRouteBuilder.setNetwork(transformedOutgoingRoute.getNetwork()); // Incoming nextHopIp transformedIncomingRouteBuilder.setNextHopIp(transformedOutgoingRoute.getNextHopIp()); // Incoming originType transformedIncomingRouteBuilder.setOriginType(transformedOutgoingRoute.getOriginType()); // Incoming localPreference transformedIncomingRouteBuilder.setLocalPreference( transformedOutgoingRoute.getLocalPreference()); // Incoming admin int admin = ebgp ? ebgpAdmin : ibgpAdmin; transformedIncomingRouteBuilder.setAdmin(admin); // Incoming metric transformedIncomingRouteBuilder.setMetric(transformedOutgoingRoute.getMetric()); // Incoming srcProtocol transformedIncomingRouteBuilder.setSrcProtocol(targetProtocol); String importPolicyName = neighbor.getImportPolicy(); // TODO: ensure there is always an import policy if (ebgp && transformedOutgoingRoute.getAsPath().containsAs(neighbor.getLocalAs()) && !neighbor.getAllowLocalAsIn()) { // skip routes containing peer's AS unless // disable-peer-as-check (getAllowRemoteAsOut) is set continue; } /* * CREATE INCOMING ROUTE */ boolean acceptIncoming = true; if (importPolicyName != null) { RoutingPolicy importPolicy = _c.getRoutingPolicies().get(importPolicyName); if (importPolicy != null) { acceptIncoming = importPolicy.process( transformedOutgoingRoute, transformedIncomingRouteBuilder, advert.getSrcIp(), _key, Direction.IN); } } if (acceptIncoming) { BgpRoute transformedIncomingRoute = transformedIncomingRouteBuilder.build(); ribDeltas.get(targetRib).from(targetRib.mergeRouteGetDelta(transformedIncomingRoute)); } } } // Propagate received routes through all the RIBs and send out appropriate messages // to neighbors Map<BgpMultipathRib, RibDelta<BgpRoute>> deltas = ribDeltas .entrySet() .stream() .filter(e -> e.getValue().build() != null) .collect(Collectors.toMap(Entry::getKey, e -> e.getValue().build())); finalizeBgpRoutesAndQueueOutgoingMessages( proc.getMultipathEbgp(), proc.getMultipathIbgp(), deltas, allNodes, bgpTopology, networkConfigurations); } /** Initialize Intra-area OSPF routes from the interface prefixes */ private void initIntraAreaOspfRoutes() { OspfProcess proc = _vrf.getOspfProcess(); if (proc == null) { return; // nothing to do } /* * init intra-area routes from connected routes * For each interface within an OSPF area and each interface prefix, * construct a new OSPF-IA route. Put it in the IA RIB. */ proc.getAreas() .forEach( (areaNum, area) -> { for (String ifaceName : area.getInterfaces()) { Interface iface = _c.getInterfaces().get(ifaceName); if (iface.getActive()) { Set<Prefix> allNetworkPrefixes = iface .getAllAddresses() .stream() .map(InterfaceAddress::getPrefix) .collect(Collectors.toSet()); int interfaceOspfCost = iface.getOspfCost(); for (Prefix prefix : allNetworkPrefixes) { long cost = interfaceOspfCost; boolean stubNetwork = iface.getOspfPassive() || iface.getOspfPointToPoint(); if (stubNetwork) { if (proc.getMaxMetricStubNetworks() != null) { cost = proc.getMaxMetricStubNetworks(); } } else if (proc.getMaxMetricTransitLinks() != null) { cost = proc.getMaxMetricTransitLinks(); } OspfIntraAreaRoute route = new OspfIntraAreaRoute( prefix, null, RoutingProtocol.OSPF.getDefaultAdministrativeCost( _c.getConfigurationFormat()), cost, areaNum); _ospfIntraAreaRib.mergeRouteGetDelta(route); } } } }); } /** Initialize RIP routes from the interface prefixes */ @VisibleForTesting void initBaseRipRoutes() { if (_vrf.getRipProcess() == null) { return; // nothing to do } // init internal routes from connected routes for (String ifaceName : _vrf.getRipProcess().getInterfaces()) { Interface iface = _vrf.getInterfaces().get(ifaceName); if (iface.getActive()) { Set<Prefix> allNetworkPrefixes = iface .getAllAddresses() .stream() .map(InterfaceAddress::getPrefix) .collect(Collectors.toSet()); long cost = RipProcess.DEFAULT_RIP_COST; for (Prefix prefix : allNetworkPrefixes) { RipInternalRoute route = new RipInternalRoute( prefix, null, RoutingProtocol.RIP.getDefaultAdministrativeCost(_c.getConfigurationFormat()), cost); _ripInternalRib.mergeRouteGetDelta(route); } } } } /** * This function creates BGP routes from generated routes that go into the BGP RIB, but cannot be * imported into the main RIB. The purpose of these routes is to prevent the local router from * accepting advertisements less desirable than the local generated ones for a given network. */ void initBgpAggregateRoutes() { // first import aggregates switch (_c.getConfigurationFormat()) { case JUNIPER: case JUNIPER_SWITCH: return; // $CASES-OMITTED$ default: break; } for (AbstractRoute grAbstract : _generatedRib.getRoutes()) { GeneratedRoute gr = (GeneratedRoute) grAbstract; BgpRoute br = BgpProtocolHelper.convertGeneratedRouteToBgp(gr, _vrf.getBgpProcess().getRouterId()); // Prevent route from being merged into the main RIB. br.setNonRouting(true); /* TODO: tests for this */ RibDelta<BgpRoute> d1 = _bgpMultipathRib.mergeRouteGetDelta(br); _bgpBestPathDeltaBuilder.from(d1); RibDelta<BgpRoute> d2 = _bgpBestPathRib.mergeRouteGetDelta(br); _bgpMultiPathDeltaBuilder.from(d2); if (d1 != null || d2 != null) { _bgpAggDeps.addRouteDependency(br, gr); } } } /** * Initialize the connected RIB -- a RIB containing connected routes (i.e., direct connections to * neighbors). */ @VisibleForTesting void initConnectedRib() { // Look at all connected interfaces for (Interface i : _vrf.getInterfaces().values()) { if (i.getActive()) { // Make sure the interface is active // Create a route for each interface prefix for (InterfaceAddress ifaceAddress : i.getAllAddresses()) { Prefix prefix = ifaceAddress.getPrefix(); ConnectedRoute cr = new ConnectedRoute(prefix, i.getName()); _connectedRib.mergeRoute(cr); } } } } /** * Initialize the local RIB -- a RIB containing non-forwarding /32 routes for exact addresses of * interfaces */ @VisibleForTesting void initLocalRib() { // Look at all connected interfaces for (Interface i : _vrf.getInterfaces().values()) { if (i.getActive()) { // Make sure the interface is active // Create a route for each interface prefix for (InterfaceAddress ifaceAddress : i.getAllAddresses()) { if (ifaceAddress.getNetworkBits() < Prefix.MAX_PREFIX_LENGTH) { LocalRoute lr = new LocalRoute(ifaceAddress, i.getName()); _localRib.mergeRoute(lr); } } } } } @Nullable @VisibleForTesting OspfExternalRoute computeOspfExportRoute( AbstractRoute potentialExportRoute, RoutingPolicy exportPolicy, OspfProcess proc) { OspfExternalRoute.Builder outputRouteBuilder = new OspfExternalRoute.Builder(); // Export based on the policy result of processing the potentialExportRoute boolean accept = exportPolicy.process(potentialExportRoute, outputRouteBuilder, null, _key, Direction.OUT); if (!accept) { return null; } OspfMetricType metricType = outputRouteBuilder.getOspfMetricType(); outputRouteBuilder.setAdmin( outputRouteBuilder .getOspfMetricType() .toRoutingProtocol() .getDefaultAdministrativeCost(_c.getConfigurationFormat())); outputRouteBuilder.setNetwork(potentialExportRoute.getNetwork()); Long maxMetricExternalNetworks = proc.getMaxMetricExternalNetworks(); long costToAdvertiser; if (maxMetricExternalNetworks != null) { if (metricType == OspfMetricType.E1) { outputRouteBuilder.setMetric(maxMetricExternalNetworks); } costToAdvertiser = maxMetricExternalNetworks; } else { costToAdvertiser = 0L; } outputRouteBuilder.setCostToAdvertiser(costToAdvertiser); outputRouteBuilder.setAdvertiser(_c.getHostname()); outputRouteBuilder.setArea(OspfRoute.NO_AREA); outputRouteBuilder.setLsaMetric(outputRouteBuilder.getMetric()); OspfExternalRoute outputRoute = outputRouteBuilder.build(); outputRoute.setNonRouting(true); return outputRoute; } void initIsisExports(Map<String, Node> allNodes) { /* TODO: https://github.com/batfish/batfish/issues/1703 */ IsisProcess proc = _vrf.getIsisProcess(); if (proc == null) { return; // nothing to do } RibDelta.Builder<IsisRoute> d1 = new Builder<>(_isisL1Rib); RibDelta.Builder<IsisRoute> d2 = new Builder<>(_isisL2Rib); /* * init L1 and L2 routes from connected routes */ int l1Admin = RoutingProtocol.ISIS_L1.getDefaultAdministrativeCost(_c.getConfigurationFormat()); int l2Admin = RoutingProtocol.ISIS_L2.getDefaultAdministrativeCost(_c.getConfigurationFormat()); IsisLevelSettings l1Settings = proc.getLevel1(); IsisLevelSettings l2Settings = proc.getLevel2(); IsisRoute.Builder builder = new IsisRoute.Builder() .setArea(proc.getNetAddress().getAreaIdString()) .setSystemId(proc.getNetAddress().getSystemIdString()); _vrf.getInterfaces() .values() .forEach( iface -> generateAllIsisInterfaceRoutes( d1, d2, l1Admin, l2Admin, l1Settings, l2Settings, builder, iface)); // export default route for L1 neighbors on L1L2 routers if (l1Settings != null && l2Settings != null) { IsisRoute defaultRoute = builder .setAdmin(l1Admin) .setAttach(true) .setLevel(IsisLevel.LEVEL_1) .setMetric(0L) .setNetwork(Prefix.ZERO) .setProtocol(RoutingProtocol.ISIS_L1) .build(); d1.from(_isisL1Rib.mergeRouteGetDelta(defaultRoute)); } queueOutgoingIsisRoutes(allNodes, d1.build(), d2.build()); } /** * Generate IS-IS L1/L2 routes from a given interface and merge them into appropriate L1/L2 RIBs. */ private void generateAllIsisInterfaceRoutes( Builder<IsisRoute> d1, Builder<IsisRoute> d2, int l1Admin, int l2Admin, @Nullable IsisLevelSettings l1Settings, @Nullable IsisLevelSettings l2Settings, IsisRoute.Builder routeBuilder, Interface iface) { IsisInterfaceSettings ifaceSettings = iface.getIsis(); if (ifaceSettings == null) { return; } IsisInterfaceLevelSettings ifaceL1Settings = ifaceSettings.getLevel1(); IsisInterfaceLevelSettings ifaceL2Settings = ifaceSettings.getLevel2(); if (ifaceL1Settings != null && l1Settings != null) { long metric = ifaceL1Settings.getMode() == IsisInterfaceMode.PASSIVE ? 0L : firstNonNull(ifaceL1Settings.getCost(), IsisRoute.DEFAULT_METRIC); generateIsisInterfaceRoutesPerLevel( l1Admin, routeBuilder, iface, metric, IsisLevel.LEVEL_1, RoutingProtocol.ISIS_L1) .forEach(r -> d1.from(_isisL1Rib.mergeRouteGetDelta(r))); } if (ifaceL2Settings != null && l2Settings != null) { long metric = ifaceL2Settings.getMode() == IsisInterfaceMode.PASSIVE ? 0L : firstNonNull(ifaceL2Settings.getCost(), IsisRoute.DEFAULT_METRIC); generateIsisInterfaceRoutesPerLevel( l2Admin, routeBuilder, iface, metric, IsisLevel.LEVEL_2, RoutingProtocol.ISIS_L2) .forEach(r -> d2.from(_isisL2Rib.mergeRouteGetDelta(r))); } } /** * Generate IS-IS from a given interface for a given level (with a given metric/admin cost) and * merge them into the appropriate RIB. */ private static Set<IsisRoute> generateIsisInterfaceRoutesPerLevel( int adminCost, IsisRoute.Builder routeBuilder, Interface iface, long metric, IsisLevel level, RoutingProtocol isisProtocol) { routeBuilder.setAdmin(adminCost).setLevel(level).setMetric(metric).setProtocol(isisProtocol); return iface .getAllAddresses() .stream() .map( address -> routeBuilder.setNetwork(address.getPrefix()).setNextHopIp(address.getIp()).build()) .collect(ImmutableSet.toImmutableSet()); } void initOspfExports() { OspfProcess proc = _vrf.getOspfProcess(); // Nothing to do if (proc == null) { return; } // get OSPF export policy name String exportPolicyName = _vrf.getOspfProcess().getExportPolicy(); if (exportPolicyName == null) { return; // nothing to export } RoutingPolicy exportPolicy = _c.getRoutingPolicies().get(exportPolicyName); if (exportPolicy == null) { return; // nothing to export } // For each route in the previous RIB, compute an export route and add it to the appropriate // RIB. RibDelta.Builder<OspfExternalType1Route> d1 = new Builder<>(_ospfExternalType1Rib); RibDelta.Builder<OspfExternalType2Route> d2 = new Builder<>(_ospfExternalType2Rib); for (AbstractRoute potentialExport : _mainRib.getRoutes()) { OspfExternalRoute outputRoute = computeOspfExportRoute(potentialExport, exportPolicy, proc); if (outputRoute == null) { continue; // no need to export } if (outputRoute.getOspfMetricType() == OspfMetricType.E1) { d1.from(_ospfExternalType1Rib.mergeRouteGetDelta((OspfExternalType1Route) outputRoute)); } else { // assuming here that MetricType exists. Or E2 is the default d2.from(_ospfExternalType2Rib.mergeRouteGetDelta((OspfExternalType2Route) outputRoute)); } } queueOutgoingOspfExternalRoutes(d1.build(), d2.build()); } /** Initialize all ribs on this router. All RIBs will be empty */ @VisibleForTesting final void initRibs() { _connectedRib = new ConnectedRib(); _localRib = new LocalRib(); // If bgp process is null, doesn't matter MultipathEquivalentAsPathMatchMode mpTieBreaker = _vrf.getBgpProcess() == null ? EXACT_PATH : _vrf.getBgpProcess().getMultipathEquivalentAsPathMatchMode(); _ebgpMultipathRib = new BgpMultipathRib(mpTieBreaker); _ebgpStagingRib = new BgpMultipathRib(mpTieBreaker); _generatedRib = new Rib(); _ibgpMultipathRib = new BgpMultipathRib(mpTieBreaker); _ibgpStagingRib = new BgpMultipathRib(mpTieBreaker); _independentRib = new Rib(); _isisRib = new IsisRib(isL1Only()); _isisL1Rib = new IsisLevelRib(_receivedIsisL1Routes); _isisL2Rib = new IsisLevelRib(_receivedIsisL2Routes); _isisL1StagingRib = new IsisLevelRib(null); _isisL2StagingRib = new IsisLevelRib(null); _mainRib = new Rib(); _ospfExternalType1Rib = new OspfExternalType1Rib(getHostname(), _receivedOspExternalType1Routes); _ospfExternalType2Rib = new OspfExternalType2Rib(getHostname(), _receivedOspExternalType2Routes); _ospfExternalType1StagingRib = new OspfExternalType1Rib(getHostname(), null); _ospfExternalType2StagingRib = new OspfExternalType2Rib(getHostname(), null); _ospfInterAreaRib = new OspfInterAreaRib(); _ospfInterAreaStagingRib = new OspfInterAreaRib(); _ospfIntraAreaRib = new OspfIntraAreaRib(this); _ospfIntraAreaStagingRib = new OspfIntraAreaRib(this); _ospfRib = new OspfRib(); _ripInternalRib = new RipInternalRib(); _ripInternalStagingRib = new RipInternalRib(); _ripRib = new RipRib(); _staticNextHopRib = new StaticRib(); _staticInterfaceRib = new StaticRib(); _bgpMultipathRib = new BgpMultipathRib(mpTieBreaker); _ebgpMultipathRib = new BgpMultipathRib(mpTieBreaker); _ibgpMultipathRib = new BgpMultipathRib(mpTieBreaker); BgpTieBreaker tieBreaker = _vrf.getBgpProcess() == null ? BgpTieBreaker.ARRIVAL_ORDER : _vrf.getBgpProcess().getTieBreaker(); _ebgpBestPathRib = new BgpBestPathRib(tieBreaker, null, _mainRib); _ibgpBestPathRib = new BgpBestPathRib(tieBreaker, null, _mainRib); _bgpBestPathRib = new BgpBestPathRib(tieBreaker, _receivedBgpRoutes, _mainRib); _mainRibRouteDeltaBuiler = new RibDelta.Builder<>(_mainRib); _bgpBestPathDeltaBuilder = new RibDelta.Builder<>(_bgpBestPathRib); _bgpMultiPathDeltaBuilder = new RibDelta.Builder<>(_bgpMultipathRib); } private boolean isL1Only() { IsisProcess proc = _vrf.getIsisProcess(); if (proc == null) { return false; } return proc.getLevel1() != null && proc.getLevel2() == null; } /** * Initialize the static route RIBs from the VRF config. Interface routes go into {@link * #_staticInterfaceRib}; routes that only have next-hop-ip go into {@link #_staticNextHopRib} */ @VisibleForTesting void initStaticRibs() { for (StaticRoute sr : _vrf.getStaticRoutes()) { if (isInterfaceRoute(sr)) { // We have an interface route, check if interface is active Interface nextHopInterface = _c.getInterfaces().get(sr.getNextHopInterface()); if (Interface.NULL_INTERFACE_NAME.equals(sr.getNextHopInterface()) || (nextHopInterface != null && (nextHopInterface.getActive()))) { // Interface is active (or special null interface), install route _staticInterfaceRib.mergeRouteGetDelta(sr); } } else { if (Route.UNSET_ROUTE_NEXT_HOP_IP.equals(sr.getNextHopIp())) { continue; } // We have a next-hop-ip route, keep in it that RIB _staticNextHopRib.mergeRouteGetDelta(sr); } } } /** * Compute a set of BGP advertisements to the outside of the network. Done after the dataplane * computation has converged. * * @param ipOwners mapping of IPs to their owners (nodes) * @return a number of sent out advertisements */ int computeBgpAdvertisementsToOutside(Map<Ip, Set<String>> ipOwners) { int numAdvertisements = 0; // If we have no BGP process, nothing to do if (_vrf.getBgpProcess() == null) { return numAdvertisements; } /* * This operation only really makes sense for active neighbors, otherwise we're missing required * information for which advertisements would be sent out. */ for (BgpActivePeerConfig neighbor : _vrf.getBgpProcess().getActiveNeighbors().values()) { String hostname = _c.getHostname(); Ip remoteIp = neighbor.getPeerAddress(); if (neighbor.getLocalIp() == null || remoteIp == null || neighbor.getLocalAs() == null || neighbor.getRemoteAs() == null || ipOwners.get(remoteIp) != null) { // Skip if neighbor is mis-configured or remote peer is inside the network continue; } long localAs = neighbor.getLocalAs(); long remoteAs = neighbor.getRemoteAs(); String remoteHostname = remoteIp.toString(); String remoteVrfName = _vrf.getName(); RoutingPolicy exportPolicy = _c.getRoutingPolicies().get(neighbor.getExportPolicy()); boolean ebgpSession = localAs != remoteAs; RoutingProtocol targetProtocol = ebgpSession ? RoutingProtocol.BGP : RoutingProtocol.IBGP; Set<AbstractRoute> candidateRoutes = Collections.newSetFromMap(new IdentityHashMap<>()); // Add IGP routes Set<AbstractRoute> activeRoutes = Collections.newSetFromMap(new IdentityHashMap<>()); activeRoutes.addAll(_mainRib.getRoutes()); for (AbstractRoute candidateRoute : activeRoutes) { if (candidateRoute.getProtocol() != RoutingProtocol.BGP && candidateRoute.getProtocol() != RoutingProtocol.IBGP) { candidateRoutes.add(candidateRoute); } } /* * bgp advertise-external * * When this is set, add best eBGP path independently of whether * it is preempted by an iBGP or IGP route. Only applicable to * iBGP sessions. */ boolean advertiseExternal = !ebgpSession && neighbor.getAdvertiseExternal(); if (advertiseExternal) { candidateRoutes.addAll(_ebgpBestPathRib.getRoutes()); } /* * bgp advertise-inactive * * When this is set, add best BGP path independently of whether * it is preempted by an IGP route. Only applicable to eBGP * sessions. */ boolean advertiseInactive = ebgpSession && neighbor.getAdvertiseInactive(); /* Add best bgp paths if they are active, or if advertise-inactive */ for (AbstractRoute candidateRoute : _bgpBestPathRib.getRoutes()) { if (advertiseInactive || activeRoutes.contains(candidateRoute)) { candidateRoutes.add(candidateRoute); } } /* Add all bgp paths if additional-paths active for this session */ boolean additionalPaths = !ebgpSession && neighbor.getAdditionalPathsSend() && neighbor.getAdditionalPathsSelectAll(); if (additionalPaths) { candidateRoutes.addAll(_bgpMultipathRib.getRoutes()); } for (AbstractRoute route : candidateRoutes) { // TODO: update this using BgpProtocolHelper BgpRoute.Builder transformedOutgoingRouteBuilder = new BgpRoute.Builder(); RoutingProtocol routeProtocol = route.getProtocol(); boolean routeIsBgp = routeProtocol == RoutingProtocol.IBGP || routeProtocol == RoutingProtocol.BGP; // originatorIP Ip originatorIp; if (!ebgpSession && routeProtocol == RoutingProtocol.IBGP) { BgpRoute bgpRoute = (BgpRoute) route; originatorIp = bgpRoute.getOriginatorIp(); } else { originatorIp = _vrf.getBgpProcess().getRouterId(); } transformedOutgoingRouteBuilder.setOriginatorIp(originatorIp); transformedOutgoingRouteBuilder.setReceivedFromIp(neighbor.getLocalIp()); /* * clusterList, receivedFromRouteReflectorClient, (originType for bgp remote route) */ if (routeIsBgp) { BgpRoute bgpRoute = (BgpRoute) route; transformedOutgoingRouteBuilder.setOriginType(bgpRoute.getOriginType()); if (ebgpSession && bgpRoute.getAsPath().containsAs(neighbor.getRemoteAs()) && !neighbor.getAllowRemoteAsOut()) { // skip routes containing peer's AS unless // disable-peer-as-check (getAllowRemoteAsOut) is set continue; } /* * route reflection: reflect everything received from * clients to clients and non-clients. reflect everything * received from non-clients to clients. Do not reflect to * originator */ Ip routeOriginatorIp = bgpRoute.getOriginatorIp(); /* * iBGP speaker should not send out routes to iBGP neighbor whose router-id is * same as originator id of advertisement */ if (!ebgpSession && remoteIp.equals(routeOriginatorIp)) { continue; } if (routeProtocol == RoutingProtocol.IBGP && !ebgpSession) { boolean routeReceivedFromRouteReflectorClient = bgpRoute.getReceivedFromRouteReflectorClient(); boolean sendingToRouteReflectorClient = neighbor.getRouteReflectorClient(); transformedOutgoingRouteBuilder.getClusterList().addAll(bgpRoute.getClusterList()); if (!routeReceivedFromRouteReflectorClient && !sendingToRouteReflectorClient) { continue; } if (sendingToRouteReflectorClient) { // sender adds its local cluster id to clusterlist of // new route transformedOutgoingRouteBuilder.getClusterList().add(neighbor.getClusterId()); } } } // Outgoing asPath // Outgoing communities if (routeIsBgp) { BgpRoute bgpRoute = (BgpRoute) route; transformedOutgoingRouteBuilder.setAsPath(bgpRoute.getAsPath().getAsSets()); if (neighbor.getSendCommunity()) { transformedOutgoingRouteBuilder.getCommunities().addAll(bgpRoute.getCommunities()); } } if (ebgpSession) { SortedSet<Long> newAsPathElement = new TreeSet<>(); newAsPathElement.add(localAs); transformedOutgoingRouteBuilder.getAsPath().add(0, newAsPathElement); } // Outgoing protocol transformedOutgoingRouteBuilder.setProtocol(targetProtocol); transformedOutgoingRouteBuilder.setNetwork(route.getNetwork()); // Outgoing metric if (routeIsBgp) { transformedOutgoingRouteBuilder.setMetric(route.getMetric()); } // Outgoing nextHopIp // Outgoing localPreference Ip nextHopIp; int localPreference; if (ebgpSession || !routeIsBgp) { nextHopIp = neighbor.getLocalIp(); localPreference = BgpRoute.DEFAULT_LOCAL_PREFERENCE; } else { nextHopIp = route.getNextHopIp(); BgpRoute ibgpRoute = (BgpRoute) route; localPreference = ibgpRoute.getLocalPreference(); } if (Route.UNSET_ROUTE_NEXT_HOP_IP.equals(nextHopIp)) { // should only happen for ibgp String nextHopInterface = route.getNextHopInterface(); InterfaceAddress nextHopAddress = _c.getInterfaces().get(nextHopInterface).getAddress(); if (nextHopAddress == null) { throw new BatfishException("route's nextHopInterface has no address"); } nextHopIp = nextHopAddress.getIp(); } transformedOutgoingRouteBuilder.setNextHopIp(nextHopIp); transformedOutgoingRouteBuilder.setLocalPreference(localPreference); // Outgoing srcProtocol transformedOutgoingRouteBuilder.setSrcProtocol(route.getProtocol()); /* * CREATE OUTGOING ROUTE */ boolean acceptOutgoing = exportPolicy.process( route, transformedOutgoingRouteBuilder, remoteIp, new Prefix(neighbor.getPeerAddress(), Prefix.MAX_PREFIX_LENGTH), remoteVrfName, Direction.OUT); if (!acceptOutgoing) { _prefixTracer.filtered( route.getNetwork(), remoteHostname, remoteIp, remoteVrfName, neighbor.getExportPolicy(), Direction.OUT); continue; } _prefixTracer.sentTo( route.getNetwork(), remoteHostname, remoteIp, remoteVrfName, neighbor.getExportPolicy()); BgpRoute transformedOutgoingRoute = transformedOutgoingRouteBuilder.build(); // Record sent advertisement BgpAdvertisementType sentType = ebgpSession ? BgpAdvertisementType.EBGP_SENT : BgpAdvertisementType.IBGP_SENT; Ip sentOriginatorIp = transformedOutgoingRoute.getOriginatorIp(); SortedSet<Long> sentClusterList = ImmutableSortedSet.copyOf(transformedOutgoingRoute.getClusterList()); AsPath sentAsPath = transformedOutgoingRoute.getAsPath(); SortedSet<Long> sentCommunities = ImmutableSortedSet.copyOf(transformedOutgoingRoute.getCommunities()); Prefix sentNetwork = route.getNetwork(); Ip sentNextHopIp; String sentSrcNode = hostname; String sentSrcVrf = _vrf.getName(); Ip sentSrcIp = neighbor.getLocalIp(); String sentDstNode = remoteHostname; String sentDstVrf = remoteVrfName; Ip sentDstIp = remoteIp; int sentWeight = -1; if (ebgpSession) { sentNextHopIp = nextHopIp; } else { sentNextHopIp = transformedOutgoingRoute.getNextHopIp(); } int sentLocalPreference = transformedOutgoingRoute.getLocalPreference(); long sentMed = transformedOutgoingRoute.getMetric(); OriginType sentOriginType = transformedOutgoingRoute.getOriginType(); RoutingProtocol sentSrcProtocol = targetProtocol; BgpAdvertisement sentAdvert = new BgpAdvertisement( sentType, sentNetwork, sentNextHopIp, sentSrcNode, sentSrcVrf, sentSrcIp, sentDstNode, sentDstVrf, sentDstIp, sentSrcProtocol, sentOriginType, sentLocalPreference, sentMed, sentOriginatorIp, sentAsPath, ImmutableSortedSet.copyOf(sentCommunities), ImmutableSortedSet.copyOf(sentClusterList), sentWeight); _sentBgpAdvertisements.add(sentAdvert); numAdvertisements++; } } return numAdvertisements; } /** * Process BGP messages from neighbors, return a list of delta changes to the RIBs * * @param bgpTopology the bgp peering relationships * @return List of {@link RibDelta objects} */ @Nullable Map<BgpMultipathRib, RibDelta<BgpRoute>> processBgpMessages( ValueGraph<BgpPeerConfigId, BgpSessionProperties> bgpTopology, NetworkConfigurations nc) { // If we have no BGP process, nothing to do if (_vrf.getBgpProcess() == null) { return null; } // Keep track of changes to the RIBs using delta builders, keyed by RIB type Map<BgpMultipathRib, RibDelta.Builder<BgpRoute>> ribDeltas = new IdentityHashMap<>(); ribDeltas.put(_ebgpStagingRib, new Builder<>(_ebgpStagingRib)); ribDeltas.put(_ibgpStagingRib, new Builder<>(_ibgpStagingRib)); // Process updates from each neighbor for (Entry<BgpEdgeId, Queue<RouteAdvertisement<BgpRoute>>> e : _bgpIncomingRoutes.entrySet()) { // Grab the queue containing all messages from remoteBgpPeerConfig Queue<RouteAdvertisement<BgpRoute>> queue = e.getValue(); // Setup helper vars BgpPeerConfigId remoteConfigId = e.getKey().src(); BgpPeerConfigId ourConfigId = e.getKey().dst(); BgpSessionProperties sessionProperties = getBgpSessionProperties(bgpTopology, new BgpEdgeId(remoteConfigId, ourConfigId)); BgpPeerConfig ourBgpConfig = requireNonNull(nc.getBgpPeerConfig(e.getKey().dst())); BgpPeerConfig remoteBgpConfig = requireNonNull(nc.getBgpPeerConfig(e.getKey().src())); BgpMultipathRib targetRib = sessionProperties.isEbgp() ? _ebgpStagingRib : _ibgpStagingRib; // Process all routes from neighbor while (queue.peek() != null) { RouteAdvertisement<BgpRoute> remoteRouteAdvert = queue.remove(); BgpRoute remoteRoute = remoteRouteAdvert.getRoute(); BgpRoute.Builder transformedIncomingRouteBuilder = BgpProtocolHelper.transformBgpRouteOnImport( ourBgpConfig, sessionProperties, remoteRoute, _c.getConfigurationFormat()); if (transformedIncomingRouteBuilder == null) { // Route could not be imported for core protocol reasons continue; } // Process route through import policy, if one exists String importPolicyName = ourBgpConfig.getImportPolicy(); boolean acceptIncoming = true; // TODO: ensure there is always an import policy if (importPolicyName != null) { RoutingPolicy importPolicy = _c.getRoutingPolicies().get(importPolicyName); if (importPolicy != null) { acceptIncoming = importPolicy.process( remoteRoute, transformedIncomingRouteBuilder, remoteBgpConfig.getLocalIp(), ourConfigId.getRemotePeerPrefix(), _key, Direction.IN); } } if (!acceptIncoming) { // Route could not be imported due to routing policy _prefixTracer.filtered( remoteRoute.getNetwork(), ourConfigId.getHostname(), remoteBgpConfig.getLocalIp(), remoteConfigId.getVrfName(), importPolicyName, Direction.IN); continue; } BgpRoute transformedIncomingRoute = transformedIncomingRouteBuilder.build(); if (remoteRouteAdvert.isWithdrawn()) { // Note this route was removed ribDeltas.get(targetRib).remove(transformedIncomingRoute, Reason.WITHDRAW); SortedSet<BgpRoute> b = _receivedBgpRoutes.get(transformedIncomingRoute.getNetwork()); if (b != null) { b.remove(transformedIncomingRoute); } } else { // Merge into staging rib, note delta ribDeltas.get(targetRib).from(targetRib.mergeRouteGetDelta(transformedIncomingRoute)); if (!remoteRouteAdvert.isWithdrawn()) { markReceivedBgpAdvertisement( ourConfigId, remoteConfigId, ourBgpConfig, remoteBgpConfig, sessionProperties, transformedIncomingRoute); _receivedBgpRoutes .computeIfAbsent(transformedIncomingRoute.getNetwork(), k -> new TreeSet<>()) .add(transformedIncomingRoute); _prefixTracer.installed( transformedIncomingRoute.getNetwork(), remoteConfigId.getHostname(), remoteBgpConfig.getLocalIp(), remoteConfigId.getVrfName(), importPolicyName); } } } } // Return built deltas from RibDelta builders Map<BgpMultipathRib, RibDelta<BgpRoute>> builtDeltas = new IdentityHashMap<>(); ribDeltas.forEach( (rib, deltaBuilder) -> { RibDelta<BgpRoute> delta = deltaBuilder.build(); if (delta != null) { builtDeltas.put(rib, delta); } }); return builtDeltas; } public @Nullable Entry<RibDelta<IsisRoute>, RibDelta<IsisRoute>> propagateIsisRoutes( final Map<String, Node> nodes) { if (_vrf.getIsisProcess() == null) { return null; } RibDelta.Builder<IsisRoute> l1DeltaBuilder = new RibDelta.Builder<>(_isisL1StagingRib); RibDelta.Builder<IsisRoute> l2DeltaBuilder = new RibDelta.Builder<>(_isisL2StagingRib); IsisRoute.Builder routeBuilder = new IsisRoute.Builder(); int l1Admin = RoutingProtocol.ISIS_L1.getDefaultAdministrativeCost(_c.getConfigurationFormat()); int l2Admin = RoutingProtocol.ISIS_L2.getDefaultAdministrativeCost(_c.getConfigurationFormat()); _isisIncomingRoutes.forEach( (edge, queue) -> { Ip nextHopIp = edge.getNode2().getInterface(nodes).getAddress().getIp(); Interface iface = edge.getNode1().getInterface(nodes); routeBuilder.setNextHopIp(nextHopIp); while (queue.peek() != null) { RouteAdvertisement<IsisRoute> routeAdvert = queue.remove(); IsisRoute neighborRoute = routeAdvert.getRoute(); routeBuilder .setNetwork(neighborRoute.getNetwork()) .setArea(neighborRoute.getArea()) .setAttach(neighborRoute.getAttach()) .setSystemId(neighborRoute.getSystemId()); boolean withdraw = routeAdvert.isWithdrawn(); // TODO: simplify if (neighborRoute.getLevel() == IsisLevel.LEVEL_1) { long incrementalMetric = firstNonNull(iface.getIsis().getLevel1().getCost(), IsisRoute.DEFAULT_METRIC); IsisRoute newL1Route = routeBuilder .setAdmin(l1Admin) .setLevel(IsisLevel.LEVEL_1) .setMetric(incrementalMetric + neighborRoute.getMetric()) .setProtocol(RoutingProtocol.ISIS_L1) .build(); if (withdraw) { l1DeltaBuilder.remove(newL1Route, Reason.WITHDRAW); SortedSet<IsisRoute> backups = _receivedIsisL1Routes.get(newL1Route.getNetwork()); if (backups != null) { backups.remove(newL1Route); } } else { l1DeltaBuilder.from(_isisL1StagingRib.mergeRouteGetDelta(newL1Route)); _receivedIsisL1Routes .computeIfAbsent(newL1Route.getNetwork(), k -> new TreeSet<>()) .add(newL1Route); } } else { // neighborRoute is level2 long incrementalMetric = firstNonNull(iface.getIsis().getLevel2().getCost(), IsisRoute.DEFAULT_METRIC); IsisRoute newL2Route = routeBuilder .setAdmin(l2Admin) .setLevel(IsisLevel.LEVEL_2) .setMetric(incrementalMetric + neighborRoute.getMetric()) .setProtocol(RoutingProtocol.ISIS_L2) .build(); if (withdraw) { l2DeltaBuilder.remove(newL2Route, Reason.WITHDRAW); SortedSet<IsisRoute> backups = _receivedIsisL2Routes.get(newL2Route.getNetwork()); if (backups != null) { backups.remove(newL2Route); } } else { l2DeltaBuilder.from(_isisL2StagingRib.mergeRouteGetDelta(newL2Route)); _receivedIsisL2Routes .computeIfAbsent(newL2Route.getNetwork(), k -> new TreeSet<>()) .add(newL2Route); } } } }); return new SimpleEntry<>(l1DeltaBuilder.build(), l2DeltaBuilder.build()); } /** * Propagate OSPF external routes from our neighbors by reading OSPF route "advertisements" from * our queues. * * @param allNodes map of all nodes, keyed by hostname * @param topology the Layer-3 network topology * @return a pair of {@link RibDelta}s, for Type1 and Type2 routes */ @Nullable public Entry<RibDelta<OspfExternalType1Route>, RibDelta<OspfExternalType2Route>> propagateOspfExternalRoutes(final Map<String, Node> allNodes, Topology topology) { String node = _c.getHostname(); OspfProcess proc = _vrf.getOspfProcess(); if (proc == null) { return null; } int admin = RoutingProtocol.OSPF.getDefaultAdministrativeCost(_c.getConfigurationFormat()); SortedSet<Edge> edges = topology.getNodeEdges().get(node); if (edges == null) { // there are no edges, so OSPF won't produce anything return null; } RibDelta.Builder<OspfExternalType1Route> builderType1 = new RibDelta.Builder<>(_ospfExternalType1StagingRib); RibDelta.Builder<OspfExternalType2Route> builderType2 = new RibDelta.Builder<>(_ospfExternalType2StagingRib); for (Edge edge : edges) { if (!edge.getNode1().equals(node)) { continue; } String connectingInterfaceName = edge.getInt1(); Interface connectingInterface = _vrf.getInterfaces().get(connectingInterfaceName); if (connectingInterface == null) { // wrong vrf, so skip continue; } String neighborName = edge.getNode2(); Node neighbor = allNodes.get(neighborName); String neighborInterfaceName = edge.getInt2(); OspfArea area = connectingInterface.getOspfArea(); Configuration nc = neighbor.getConfiguration(); Interface neighborInterface = nc.getInterfaces().get(neighborInterfaceName); String neighborVrfName = neighborInterface.getVrfName(); VirtualRouter neighborVirtualRouter = allNodes.get(neighborName).getVirtualRouters().get(neighborVrfName); OspfArea neighborArea = neighborInterface.getOspfArea(); if (connectingInterface.getOspfEnabled() && !connectingInterface.getOspfPassive() && neighborInterface.getOspfEnabled() && !neighborInterface.getOspfPassive() && area != null && neighborArea != null && area.getName().equals(neighborArea.getName())) { /* * We have an ospf neighbor relationship on this edge. So we * should add all ospf external type 1(2) routes from this * neighbor into our ospf external type 1(2) staging rib. For * type 1, the cost of the route increases each time. For type 2, * the cost remains constant, but we must keep track of cost to * advertiser as a tie-breaker. */ long connectingInterfaceCost = connectingInterface.getOspfCost(); long incrementalCost = proc.getMaxMetricTransitLinks() != null ? proc.getMaxMetricTransitLinks() : connectingInterfaceCost; Queue<RouteAdvertisement<OspfExternalRoute>> q = _ospfExternalIncomingRoutes.get(connectingInterface.getAddress().getPrefix()); while (q.peek() != null) { RouteAdvertisement<OspfExternalRoute> routeAdvert = q.remove(); OspfExternalRoute neighborRoute = routeAdvert.getRoute(); boolean withdraw = routeAdvert.isWithdrawn(); if (neighborRoute instanceof OspfExternalType1Route) { long oldArea = neighborRoute.getArea(); long connectionArea = area.getName(); long newArea; long baseMetric = neighborRoute.getMetric(); long baseCostToAdvertiser = neighborRoute.getCostToAdvertiser(); newArea = connectionArea; if (oldArea != OspfRoute.NO_AREA) { Long maxMetricSummaryNetworks = neighborVirtualRouter._vrf.getOspfProcess().getMaxMetricSummaryNetworks(); if (connectionArea != oldArea) { if (connectionArea != 0L && oldArea != 0L) { continue; } if (maxMetricSummaryNetworks != null) { baseMetric = maxMetricSummaryNetworks + neighborRoute.getLsaMetric(); baseCostToAdvertiser = maxMetricSummaryNetworks; } } } long newMetric = baseMetric + incrementalCost; long newCostToAdvertiser = baseCostToAdvertiser + incrementalCost; OspfExternalType1Route newRoute = new OspfExternalType1Route( neighborRoute.getNetwork(), neighborInterface.getAddress().getIp(), admin, newMetric, neighborRoute.getLsaMetric(), newArea, newCostToAdvertiser, neighborRoute.getAdvertiser()); if (withdraw) { builderType1.remove(newRoute, Reason.WITHDRAW); SortedSet<OspfExternalType1Route> backups = _receivedOspExternalType1Routes.get(newRoute.getNetwork()); if (backups != null) { backups.remove(newRoute); } } else { builderType1.from(_ospfExternalType1StagingRib.mergeRouteGetDelta(newRoute)); _receivedOspExternalType1Routes .computeIfAbsent(newRoute.getNetwork(), k -> new TreeSet<>()) .add(newRoute); } } else if (neighborRoute instanceof OspfExternalType2Route) { long oldArea = neighborRoute.getArea(); long connectionArea = area.getName(); long newArea; long baseCostToAdvertiser = neighborRoute.getCostToAdvertiser(); if (oldArea == OspfRoute.NO_AREA) { newArea = connectionArea; } else { newArea = oldArea; Long maxMetricSummaryNetworks = neighborVirtualRouter._vrf.getOspfProcess().getMaxMetricSummaryNetworks(); if (connectionArea != oldArea && maxMetricSummaryNetworks != null) { baseCostToAdvertiser = maxMetricSummaryNetworks; } } long newCostToAdvertiser = baseCostToAdvertiser + incrementalCost; OspfExternalType2Route newRoute = new OspfExternalType2Route( neighborRoute.getNetwork(), neighborInterface.getAddress().getIp(), admin, neighborRoute.getMetric(), neighborRoute.getLsaMetric(), newArea, newCostToAdvertiser, neighborRoute.getAdvertiser()); if (withdraw) { builderType2.remove(newRoute, Reason.WITHDRAW); SortedSet<OspfExternalType2Route> backups = _receivedOspExternalType2Routes.get(newRoute.getNetwork()); if (backups != null) { backups.remove(newRoute); } } else { builderType2.from(_ospfExternalType2StagingRib.mergeRouteGetDelta(newRoute)); _receivedOspExternalType2Routes .computeIfAbsent(newRoute.getNetwork(), k -> new TreeSet<>()) .add(newRoute); } } } } } return new SimpleEntry<>(builderType1.build(), builderType2.build()); } /** * Construct an OSPF Inter-Area route and put into our staging rib. Note, no route validity checks * are performed, (i.e., whether the route should even go into the staging rib). {@link * #propagateOspfInternalRoutesFromNeighbor} takes care of such logic. * * @param neighborRoute the route to propagate * @param nextHopIp nextHopIp for this route (the neighbor's IP) * @param incrementalCost OSPF cost of the interface from which this route came (added to route * cost) * @param adminCost OSPF administrative distance * @param areaNum area number of the route * @return True if the route was added to the inter-area staging RIB */ @VisibleForTesting boolean stageOspfInterAreaRoute( OspfInternalRoute neighborRoute, Long maxMetricSummaryNetworks, Ip nextHopIp, long incrementalCost, int adminCost, long areaNum) { long newCost; if (maxMetricSummaryNetworks != null) { newCost = maxMetricSummaryNetworks + incrementalCost; } else { newCost = neighborRoute.getMetric() + incrementalCost; } OspfInterAreaRoute newRoute = new OspfInterAreaRoute(neighborRoute.getNetwork(), nextHopIp, adminCost, newCost, areaNum); return _ospfInterAreaStagingRib.mergeRoute(newRoute); } boolean propagateOspfInterAreaRouteFromIntraAreaRoute( Configuration neighbor, OspfProcess neighborProc, OspfIntraAreaRoute neighborRoute, long incrementalCost, Interface neighborInterface, int adminCost, long linkAreaNum) { return OspfProtocolHelper.isOspfInterAreaFromIntraAreaPropagationAllowed( linkAreaNum, neighbor, neighborProc, neighborRoute, neighborInterface.getOspfArea()) && stageOspfInterAreaRoute( neighborRoute, neighborInterface.getVrf().getOspfProcess().getMaxMetricSummaryNetworks(), neighborInterface.getAddress().getIp(), incrementalCost, adminCost, linkAreaNum); } /** * Propagate OSPF Internal routes from a single neighbor. * * @param proc The receiving OSPF process * @param neighbor the neighbor * @param connectingInterface interface on which we are connected to the neighbor * @param neighborInterface interface that the neighbor uses to connect to us * @param adminCost route administrative distance * @return true if new routes have been added to our staging RIB */ boolean propagateOspfInternalRoutesFromNeighbor( OspfProcess proc, Node neighbor, Interface connectingInterface, Interface neighborInterface, int adminCost) { OspfArea area = connectingInterface.getOspfArea(); OspfArea neighborArea = neighborInterface.getOspfArea(); // Ensure that the link (i.e., both interfaces) has OSPF enabled and OSPF areas are set if (!connectingInterface.getOspfEnabled() || connectingInterface.getOspfPassive() || !neighborInterface.getOspfEnabled() || neighborInterface.getOspfPassive() || area == null || neighborArea == null || !area.getName().equals(neighborArea.getName())) { return false; } /* * An OSPF neighbor relationship exists on this edge. So we examine all intra- and inter-area * routes belonging to the neighbor to see what should be propagated to this router. We add the * incremental cost associated with our settings and the connecting interface, and use the * neighborInterface's address as the next hop ip. */ int connectingInterfaceCost = connectingInterface.getOspfCost(); long incrementalCost = proc.getMaxMetricTransitLinks() != null ? proc.getMaxMetricTransitLinks() : connectingInterfaceCost; Long linkAreaNum = area.getName(); Configuration neighborConfiguration = neighbor.getConfiguration(); String neighborVrfName = neighborInterface.getVrfName(); OspfProcess neighborProc = neighborConfiguration.getVrfs().get(neighborVrfName).getOspfProcess(); VirtualRouter neighborVirtualRouter = neighbor.getVirtualRouters().get(neighborVrfName); boolean changed = false; for (OspfIntraAreaRoute neighborRoute : neighborVirtualRouter._ospfIntraAreaRib.getRoutes()) { changed |= propagateOspfIntraAreaRoute( neighborRoute, incrementalCost, neighborInterface, adminCost, linkAreaNum); changed |= propagateOspfInterAreaRouteFromIntraAreaRoute( neighborConfiguration, neighborProc, neighborRoute, incrementalCost, neighborInterface, adminCost, linkAreaNum); } for (OspfInterAreaRoute neighborRoute : neighborVirtualRouter._ospfInterAreaRib.getRoutes()) { changed |= propagateOspfInterAreaRouteFromInterAreaRoute( proc, neighborConfiguration, neighborProc, neighborRoute, incrementalCost, neighborInterface, adminCost, linkAreaNum); } changed |= originateOspfStubAreaDefaultRoute( neighborProc, incrementalCost, neighborInterface, adminCost, linkAreaNum); return changed; } /** * If neighbor is an ABR and this is a stub area link, propagate * * @param neighborProc The adjacent {@link OspfProcess} * @param incrementalCost The cost to reach the propagator * @param neighborInterface The propagator's interface on the link * @param adminCost The administrative cost of the route to be installed * @param linkAreaNum The area ID of the link * @return whether this route changed the RIB into which we merged it */ private boolean originateOspfStubAreaDefaultRoute( OspfProcess neighborProc, long incrementalCost, Interface neighborInterface, int adminCost, long linkAreaNum) { return OspfProtocolHelper.isOspfInterAreaDefaultOriginationAllowed( _vrf.getOspfProcess(), neighborProc, neighborInterface.getOspfArea()) && _ospfInterAreaStagingRib.mergeRoute( new OspfInterAreaRoute( Prefix.ZERO, neighborInterface.getAddress().getIp(), adminCost, incrementalCost, linkAreaNum)); } boolean propagateOspfInterAreaRouteFromInterAreaRoute( OspfProcess proc, Configuration neighbor, OspfProcess neighborProc, OspfInterAreaRoute neighborRoute, long incrementalCost, Interface neighborInterface, int adminCost, long linkAreaNum) { return OspfProtocolHelper.isOspfInterAreaFromInterAreaPropagationAllowed( proc, linkAreaNum, neighbor, neighborProc, neighborRoute, neighborInterface.getOspfArea()) && stageOspfInterAreaRoute( neighborRoute, neighborInterface.getVrf().getOspfProcess().getMaxMetricSummaryNetworks(), neighborInterface.getAddress().getIp(), incrementalCost, adminCost, linkAreaNum); } boolean propagateOspfIntraAreaRoute( OspfIntraAreaRoute neighborRoute, long incrementalCost, Interface neighborInterface, int adminCost, long linkAreaNum) { long newCost = neighborRoute.getMetric() + incrementalCost; Ip nextHopIp = neighborInterface.getAddress().getIp(); OspfIntraAreaRoute newRoute = new OspfIntraAreaRoute( neighborRoute.getNetwork(), nextHopIp, adminCost, newCost, linkAreaNum); return neighborRoute.getArea() == linkAreaNum && (_ospfIntraAreaStagingRib.mergeRoute(newRoute)); } /** * Propagate OSPF internal routes from every valid OSPF neighbor * * @param nodes mapping of node names to instances. * @param topology network topology * @return true if new routes have been added to the staging RIB */ boolean propagateOspfInternalRoutes(Map<String, Node> nodes, Topology topology) { OspfProcess proc = _vrf.getOspfProcess(); if (proc == null) { return false; // nothing to do } boolean changed = false; String node = _c.getHostname(); // Default OSPF admin cost for constructing new routes int adminCost = RoutingProtocol.OSPF.getDefaultAdministrativeCost(_c.getConfigurationFormat()); SortedSet<Edge> edges = topology.getNodeEdges().get(node); if (edges == null) { // there are no edges, so OSPF won't produce anything return false; } for (Edge edge : edges) { if (!edge.getNode1().equals(node)) { continue; } String connectingInterfaceName = edge.getInt1(); Interface connectingInterface = _vrf.getInterfaces().get(connectingInterfaceName); if (connectingInterface == null) { // wrong vrf, so skip continue; } String neighborName = edge.getNode2(); Node neighbor = nodes.get(neighborName); Interface neighborInterface = neighbor.getConfiguration().getInterfaces().get(edge.getInt2()); changed |= propagateOspfInternalRoutesFromNeighbor( proc, neighbor, connectingInterface, neighborInterface, adminCost); } return changed; } /** * Process RIP routes from our neighbors. * * @param nodes Mapping of node names to Node instances * @param topology The network topology * @return True if the rib has changed as a result of route propagation */ boolean propagateRipInternalRoutes(Map<String, Node> nodes, Topology topology) { boolean changed = false; // No rip process, nothing to do if (_vrf.getRipProcess() == null) { return false; } String node = _c.getHostname(); int admin = RoutingProtocol.RIP.getDefaultAdministrativeCost(_c.getConfigurationFormat()); SortedSet<Edge> edges = topology.getNodeEdges().get(node); if (edges == null) { // there are no edges, so RIP won't produce anything return false; } for (Edge edge : edges) { // Do not accept routes from ourselves if (!edge.getNode1().equals(node)) { continue; } // Get interface String connectingInterfaceName = edge.getInt1(); Interface connectingInterface = _vrf.getInterfaces().get(connectingInterfaceName); if (connectingInterface == null) { // wrong vrf, so skip continue; } // Get the neighbor and its interface + VRF String neighborName = edge.getNode2(); Node neighbor = nodes.get(neighborName); String neighborInterfaceName = edge.getInt2(); Interface neighborInterface = neighbor.getConfiguration().getInterfaces().get(neighborInterfaceName); String neighborVrfName = neighborInterface.getVrfName(); VirtualRouter neighborVirtualRouter = nodes.get(neighborName).getVirtualRouters().get(neighborVrfName); if (connectingInterface.getRipEnabled() && !connectingInterface.getRipPassive() && neighborInterface.getRipEnabled() && !neighborInterface.getRipPassive()) { /* * We have a RIP neighbor relationship on this edge. So we should add all RIP routes * from this neighbor into our RIP internal staging rib, adding the incremental cost * (?), and using the neighborInterface's address as the next hop ip */ for (RipInternalRoute neighborRoute : neighborVirtualRouter._ripInternalRib.getRoutes()) { long newCost = neighborRoute.getMetric() + RipProcess.DEFAULT_RIP_COST; Ip nextHopIp = neighborInterface.getAddress().getIp(); RipInternalRoute newRoute = new RipInternalRoute(neighborRoute.getNetwork(), nextHopIp, admin, newCost); if (_ripInternalStagingRib.mergeRouteGetDelta(newRoute) != null) { changed = true; } } } } return changed; } /** * Queue advertised BGP routes to all BGP neighbors. * * @param ebgpBestPathDelta {@link RibDelta} indicating what changed in the {@link * #_bgpBestPathRib} * @param bgpMultiPathDelta a {@link RibDelta} indicating what changed in the {@link * #_bgpMultipathRib} * @param mainDelta a {@link RibDelta} indicating what changed in the {@link #_mainRib} * @param allNodes map of all nodes in the network, keyed by hostname * @param bgpTopology the bgp peering relationships */ private void queueOutgoingBgpRoutes( RibDelta<BgpRoute> ebgpBestPathDelta, @Nullable RibDelta<BgpRoute> bgpMultiPathDelta, @Nullable RibDelta<AbstractRoute> mainDelta, final Map<String, Node> allNodes, ValueGraph<BgpPeerConfigId, BgpSessionProperties> bgpTopology, NetworkConfigurations networkConfigurations) { for (BgpEdgeId edge : _bgpIncomingRoutes.keySet()) { final BgpSessionProperties session = getBgpSessionProperties(bgpTopology, edge); BgpPeerConfigId remoteConfigId = edge.src(); BgpPeerConfigId ourConfigId = edge.dst(); BgpPeerConfig ourConfig = networkConfigurations.getBgpPeerConfig(edge.dst()); BgpPeerConfig remoteConfig = networkConfigurations.getBgpPeerConfig(edge.src()); VirtualRouter remoteVirtualRouter = getRemoteBgpNeighborVR(remoteConfigId, allNodes); if (remoteVirtualRouter == null) { continue; } Builder<AbstractRoute> finalBuilder = new Builder<>(null); // Definitely queue mainRib updates finalBuilder.from(mainDelta); // These knobs control which additional BGP routes get advertised if (session.getAdvertiseExternal()) { /* * Advertise external ensures that even if we withdrew an external route from the RIB */ finalBuilder.from(ebgpBestPathDelta); } if (session.getAdvertiseInactive()) { /* * In case BGP routes were deleted from the main RIB * (e.g., preempted by a better IGP route) * and advertiseInactive is true, re-add inactive BGP routes from the BGP best-path RIB. * If the BGP routes are already active, this will have no effect. */ if (mainDelta != null) { for (Prefix p : mainDelta.getPrefixes()) { if (_bgpBestPathRib.getRoutes(p) == null) { continue; } finalBuilder.add(_bgpBestPathRib.getRoutes(p)); } } } if (session.getAdditionalPaths()) { finalBuilder.from(bgpMultiPathDelta); } RibDelta<AbstractRoute> routesToExport = finalBuilder.build(); if (routesToExport == null) { continue; } // Compute a set of advertisements that can be queued on remote VR Set<RouteAdvertisement<BgpRoute>> exportedAdvertisements = routesToExport .getActions() .stream() .map( adv -> { BgpRoute transformedRoute = exportBgpRoute( adv.getRoute(), ourConfigId, remoteConfigId, ourConfig, remoteConfig, allNodes, session); return transformedRoute == null ? null : new RouteAdvertisement<>( // REPLACE does not make sense across routers, update with WITHDRAW transformedRoute, adv.isWithdrawn(), adv.getReason() == Reason.REPLACE ? Reason.WITHDRAW : adv.getReason()); }) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); // Call this on the REMOTE VR and REVERSE the edge! remoteVirtualRouter.enqueueBgpMessages(edge.reverse(), exportedAdvertisements); // Note what we sent markSentBgpAdvertisements( ourConfigId, remoteConfigId, ourConfig, remoteConfig, session, exportedAdvertisements); } } private static BgpSessionProperties getBgpSessionProperties( ValueGraph<BgpPeerConfigId, BgpSessionProperties> bgpTopology, BgpEdgeId edge) { /* BGP topology edges not guaranteed to be symmetrical (in case of dynamic neighbors). So to get session properties, we might need to flip the src/dst edge */ BgpSessionProperties tmpSession; try { tmpSession = bgpTopology.edgeValue(edge.src(), edge.dst()); } catch (IllegalArgumentException e) { tmpSession = bgpTopology.edgeValue(edge.dst(), edge.src()); } return tmpSession; } private void queueOutgoingIsisRoutes( @Nonnull Map<String, Node> allNodes, @Nullable RibDelta<IsisRoute> l1delta, @Nullable RibDelta<IsisRoute> l2delta) { if (_vrf.getIsisProcess() == null || _isisIncomingRoutes == null) { return; } // Loop over neighbors, enqueue messages _isisIncomingRoutes .keySet() .forEach( edge -> { VirtualRouter remoteVr = allNodes .get(edge.getNode1().getHostname()) .getVirtualRouters() .get(edge.getNode1().getInterface(allNodes).getVrfName()); Queue<RouteAdvertisement<IsisRoute>> queue = remoteVr._isisIncomingRoutes.get(edge.reverse()); IsisLevel circuitType = edge.getCircuitType(); if (circuitType == IsisLevel.LEVEL_1_2 || circuitType == IsisLevel.LEVEL_1) { queueDelta(queue, l1delta); } if (circuitType == IsisLevel.LEVEL_1_2 || circuitType == IsisLevel.LEVEL_2) { queueDelta(queue, l2delta); if (_vrf.getIsisProcess().getLevel1() != null && _vrf.getIsisProcess().getLevel2() != null && l1delta != null) { // We are a L1_L2 router, we must "upgrade" L1 routes to L2 routes // TODO: a little cumbersome, simplify later RibDelta.Builder<IsisRoute> upgradedRoutes = new RibDelta.Builder<>(null); l1delta .getActions() .forEach( ra -> { Optional<IsisRoute> newRoute = convertRouteLevel1ToLevel2( ra.getRoute(), RoutingProtocol.ISIS_L2.getDefaultAdministrativeCost( _c.getConfigurationFormat())); if (newRoute.isPresent()) { if (ra.isWithdrawn()) { upgradedRoutes.remove(newRoute.get(), ra.getReason()); } else { upgradedRoutes.add(newRoute.get()); } } }); queueDelta(queue, upgradedRoutes.build()); } } }); } /** * Send out OSPF External route updates to our neighbors * * @param type1delta A {@link RibDelta} containing diffs with respect to OSPF Type1 external * routes * @param type2delta A {@link RibDelta} containing diffs with respect to OSPF Type2 external * routes */ private void queueOutgoingOspfExternalRoutes( @Nullable RibDelta<OspfExternalType1Route> type1delta, @Nullable RibDelta<OspfExternalType2Route> type2delta) { if (_vrf.getOspfProcess() == null) { return; } if (_ospfNeighbors != null) { _ospfNeighbors.forEach( (key, ospfLink) -> { if (ospfLink._localOspfArea.getStubType() == StubType.STUB) { return; } // Get remote neighbor's queue by prefix Queue<RouteAdvertisement<OspfExternalRoute>> q = ospfLink._remoteVirtualRouter._ospfExternalIncomingRoutes.get(key); queueDelta(q, type1delta); queueDelta(q, type2delta); }); } } /** * Propagate BGP routes received from neighbours into the appropriate RIBs. As the propagation is * happening, queue appropriate outgoing messages to neighbors as well. * * @param multipathEbgp whether or not EBGP is multipath * @param multipathIbgp whether or not IBGP is multipath * @param stagingDeltas a map of RIB to corresponding delta. Keys are expected to contain {@link * #_ebgpStagingRib} and {@link #_ibgpStagingRib} * @param bgpTopology the bgp peering relationships */ void finalizeBgpRoutesAndQueueOutgoingMessages( boolean multipathEbgp, boolean multipathIbgp, Map<BgpMultipathRib, RibDelta<BgpRoute>> stagingDeltas, final Map<String, Node> allNodes, ValueGraph<BgpPeerConfigId, BgpSessionProperties> bgpTopology, NetworkConfigurations networkConfigurations) { RibDelta<BgpRoute> ebgpStagingDelta = stagingDeltas.get(_ebgpStagingRib); RibDelta<BgpRoute> ibgpStagingDelta = stagingDeltas.get(_ibgpStagingRib); Entry<RibDelta<BgpRoute>, RibDelta<BgpRoute>> e; RibDelta<BgpRoute> ebgpBestPathDelta; if (multipathEbgp) { e = syncBgpDeltaPropagation(_bgpBestPathRib, _bgpMultipathRib, ebgpStagingDelta); ebgpBestPathDelta = e.getKey(); _bgpBestPathDeltaBuilder.from(e.getKey()); _bgpMultiPathDeltaBuilder.from(e.getValue()); } else { ebgpBestPathDelta = importRibDelta(_bgpBestPathRib, ebgpStagingDelta); _bgpBestPathDeltaBuilder.from(ebgpBestPathDelta); _bgpMultiPathDeltaBuilder.from(ebgpBestPathDelta); } if (multipathIbgp) { e = syncBgpDeltaPropagation(_bgpBestPathRib, _bgpMultipathRib, ibgpStagingDelta); _bgpBestPathDeltaBuilder.from(e.getKey()); _bgpMultiPathDeltaBuilder.from(e.getValue()); } else { RibDelta<BgpRoute> ibgpBestPathDelta = importRibDelta(_bgpBestPathRib, ibgpStagingDelta); _bgpBestPathDeltaBuilder.from(ibgpBestPathDelta); _bgpMultiPathDeltaBuilder.from(ibgpBestPathDelta); } _mainRibRouteDeltaBuiler.from(importRibDelta(_mainRib, _bgpMultiPathDeltaBuilder.build())); queueOutgoingBgpRoutes( ebgpBestPathDelta, _bgpMultiPathDeltaBuilder.build(), _mainRibRouteDeltaBuiler.build(), allNodes, bgpTopology, networkConfigurations); } /** * Move IS-IS routes from L1/L2 staging RIBs into their respective "proper" RIBs. Following that, * move any resulting deltas into the combined IS-IS RIB, and finally, main RIB. * * @param allNodes all network nodes, keyed by hostname * @param l1Delta staging Level 1 delta * @param l2Delta staging Level 2 delta * @return true if any routes from given deltas were merged into the combined IS-IS RIB. */ boolean unstageIsisRoutes( Map<String, Node> allNodes, RibDelta<IsisRoute> l1Delta, RibDelta<IsisRoute> l2Delta) { RibDelta<IsisRoute> d1 = importRibDelta(_isisL1Rib, l1Delta); RibDelta<IsisRoute> d2 = importRibDelta(_isisL2Rib, l2Delta); queueOutgoingIsisRoutes(allNodes, d1, d2); Builder<IsisRoute> isisDeltaBuilder = new Builder<>(_isisRib); isisDeltaBuilder.from(importRibDelta(_isisRib, d1)); isisDeltaBuilder.from(importRibDelta(_isisRib, d2)); _mainRibRouteDeltaBuiler.from(importRibDelta(_mainRib, isisDeltaBuilder.build())); return d1 != null || d2 != null; } /** * Merges staged OSPF external routes into the "real" OSPF-external RIBs * * @param type1Delta a {@link RibDelta} indicating changes to be made to {@link * #_ospfExternalType1Rib} * @param type2Delta a {@link RibDelta} indicating changes to be made to {@link * #_ospfExternalType2Rib} */ boolean unstageOspfExternalRoutes( RibDelta<OspfExternalType1Route> type1Delta, RibDelta<OspfExternalType2Route> type2Delta) { RibDelta<OspfExternalType1Route> d1 = importRibDelta(_ospfExternalType1Rib, type1Delta); RibDelta<OspfExternalType2Route> d2 = importRibDelta(_ospfExternalType2Rib, type2Delta); queueOutgoingOspfExternalRoutes(d1, d2); Builder<OspfRoute> ospfDeltaBuilder = new Builder<>(_ospfRib); ospfDeltaBuilder.from(importRibDelta(_ospfRib, d1)); ospfDeltaBuilder.from(importRibDelta(_ospfRib, d2)); _mainRibRouteDeltaBuiler.from(importRibDelta(_mainRib, ospfDeltaBuilder.build())); return d1 != null || d2 != null; } /** Merges staged OSPF internal routes into the "real" OSPF-internal RIBs */ void unstageOspfInternalRoutes() { importRib(_ospfIntraAreaRib, _ospfIntraAreaStagingRib); importRib(_ospfInterAreaRib, _ospfInterAreaStagingRib); } /** Merges staged RIP routes into the "real" RIP RIB */ void unstageRipInternalRoutes() { importRib(_ripInternalRib, _ripInternalStagingRib); } /** Re-initialize RIBs (at the start of each iteration). */ void reinitForNewIteration() { _mainRibRouteDeltaBuiler = new Builder<>(_mainRib); _bgpBestPathDeltaBuilder = new RibDelta.Builder<>(_bgpBestPathRib); _bgpMultiPathDeltaBuilder = new RibDelta.Builder<>(_bgpMultipathRib); _ospfExternalDeltaBuiler = new RibDelta.Builder<>(null); /* * RIBs not read from can just be re-initialized */ _ospfRib = new OspfRib(); _ripRib = new RipRib(); /* * Staging RIBs can also be re-initialized */ MultipathEquivalentAsPathMatchMode mpTieBreaker = _vrf.getBgpProcess() == null ? EXACT_PATH : _vrf.getBgpProcess().getMultipathEquivalentAsPathMatchMode(); _ebgpStagingRib = new BgpMultipathRib(mpTieBreaker); _ibgpStagingRib = new BgpMultipathRib(mpTieBreaker); _ospfExternalType1StagingRib = new OspfExternalType1Rib(getHostname(), null); _ospfExternalType2StagingRib = new OspfExternalType2Rib(getHostname(), null); /* * Add routes that cannot change (does not affect below computation) */ _mainRibRouteDeltaBuiler.from(importRib(_mainRib, _independentRib)); /* * Re-add independent OSPF routes to ospfRib for tie-breaking */ importRib(_ospfRib, _ospfIntraAreaRib); importRib(_ospfRib, _ospfInterAreaRib); /* * Re-add independent RIP routes to ripRib for tie-breaking */ importRib(_ripRib, _ripInternalRib); } /** * Merge intra/inter OSPF RIBs into a general OSPF RIB, then merge that into the independent RIB */ void importOspfInternalRoutes() { importRib(_ospfRib, _ospfIntraAreaRib); importRib(_ospfRib, _ospfInterAreaRib); importRib(_independentRib, _ospfRib); } /** * Check if RIBs that contribute to the dataplane "dependent routes" computation have any routes * that still need to be merged. I.e., if this method returns true, we cannot converge yet. * * @return true if there are any routes remaining, in need of merging in to the RIBs */ boolean hasOutstandingRoutes() { return _ospfExternalDeltaBuiler.build() != null || _mainRibRouteDeltaBuiler.build() != null || _bgpBestPathDeltaBuilder.build() != null || _bgpMultiPathDeltaBuilder.build() != null; } /** * Check if this router has processed all its incoming BGP messages (i.e., all router queues are * empty) * * @return true if all queues are empty. */ boolean hasProcessedAllMessages() { boolean processedAll = true; // Check the BGP message queues if (_vrf.getBgpProcess() != null) { processedAll = _bgpIncomingRoutes .values() .stream() .map(Queue::isEmpty) .noneMatch(Predicate.isEqual(false)); } // Check the OSPF external message queues if (_vrf.getOspfProcess() != null) { for (Queue<RouteAdvertisement<OspfExternalRoute>> queue : _ospfExternalIncomingRoutes.values()) { if (!queue.isEmpty()) { return false; } } } if (_vrf.getIsisProcess() != null) { for (Queue<RouteAdvertisement<IsisRoute>> queue : _isisIncomingRoutes.values()) { if (!queue.isEmpty()) { return false; } } } return processedAll; } /** * Queues initial round of outgoing BGP messages based on the state of the RIBs prior to any data * plane iterations. */ void queueInitialBgpMessages( final ValueGraph<BgpPeerConfigId, BgpSessionProperties> bgpTopology, final Map<String, Node> allNodes, NetworkConfigurations nc) { if (_vrf.getBgpProcess() == null) { // nothing to do return; } for (BgpEdgeId edge : _bgpIncomingRoutes.keySet()) { newBgpSessionEstablishedHook(edge, getBgpSessionProperties(bgpTopology, edge), allNodes, nc); } } /** * Utility "message passing" method between virtual routers. Take a set of BGP {@link * RouteAdvertisement}s and puts them onto a local queue corresponding to the session between * given neighbors. * * @param routes a set of BGP routes that are being exchanged */ private void enqueueBgpMessages( @Nonnull BgpEdgeId edgeId, @Nonnull Set<RouteAdvertisement<BgpRoute>> routes) { _bgpIncomingRoutes.get(edgeId).addAll(routes); } /** Note which advertisement we sent, in full {@link BgpAdvertisement} form. */ private void markSentBgpAdvertisements( BgpPeerConfigId localNeighborId, BgpPeerConfigId remoteNeighborId, BgpPeerConfig localNeighbor, BgpPeerConfig remoteNeighbor, BgpSessionProperties sessionProperties, Set<RouteAdvertisement<BgpRoute>> routeAdvertisements) { for (RouteAdvertisement<BgpRoute> routeAdvertisement : routeAdvertisements) { if (!routeAdvertisement.isWithdrawn()) { BgpRoute route = routeAdvertisement.getRoute(); _sentBgpAdvertisements.add( BgpAdvertisement.builder() .setType( sessionProperties.isEbgp() ? BgpAdvertisementType.EBGP_SENT : BgpAdvertisementType.IBGP_SENT) .setNetwork(route.getNetwork()) .setNextHopIp(route.getNextHopIp()) .setSrcNode(getHostname()) .setSrcVrf(localNeighborId.getVrfName()) .setSrcIp(localNeighbor.getLocalIp()) .setDstNode(remoteNeighborId.getHostname()) .setDstVrf(remoteNeighborId.getVrfName()) .setDstIp(remoteNeighbor.getLocalIp()) .setSrcProtocol( sessionProperties.isEbgp() ? RoutingProtocol.BGP : RoutingProtocol.IBGP) .setOriginType(route.getOriginType()) .setLocalPreference(route.getLocalPreference()) .setMed(route.getMetric()) .setOriginatorIp(route.getOriginatorIp()) .setAsPath(route.getAsPath()) .setCommunities(route.getCommunities()) .setClusterList(route.getClusterList()) .setWeight(-1) .build()); } } } /** Note which advertisement we received, in full {@link BgpAdvertisement} form. */ private void markReceivedBgpAdvertisement( BgpPeerConfigId localNeighborId, BgpPeerConfigId remoteNeighborId, BgpPeerConfig localNeighbor, BgpPeerConfig remoteNeighbor, BgpSessionProperties sessionProperties, BgpRoute route) { _receivedBgpAdvertisements.add( BgpAdvertisement.builder() .setType( sessionProperties.isEbgp() ? BgpAdvertisementType.EBGP_RECEIVED : BgpAdvertisementType.IBGP_RECEIVED) .setNetwork(route.getNetwork()) .setNextHopIp(route.getNextHopIp()) .setSrcNode(remoteNeighborId.getHostname()) .setSrcVrf(remoteNeighborId.getVrfName()) .setSrcIp(remoteNeighbor.getLocalIp()) .setDstNode(getHostname()) .setDstVrf(localNeighborId.getVrfName()) .setDstIp(localNeighbor.getLocalIp()) .setSrcProtocol(route.getProtocol()) .setOriginType(route.getOriginType()) .setLocalPreference(route.getLocalPreference()) .setMed(route.getMetric()) .setOriginatorIp(route.getOriginatorIp()) .setAsPath(route.getAsPath()) .setCommunities(route.getCommunities()) .setClusterList(route.getClusterList()) .setWeight(route.getWeight()) .build()); } /** Deal with a newly established BGP session. */ private void newBgpSessionEstablishedHook( @Nonnull BgpEdgeId edge, @Nonnull BgpSessionProperties sessionProperties, @Nonnull Map<String, Node> allNodes, NetworkConfigurations nc) { BgpPeerConfigId localConfigId = edge.dst(); BgpPeerConfigId remoteConfigId = edge.src(); BgpPeerConfig localConfig = nc.getBgpPeerConfig(localConfigId); BgpPeerConfig remoteConfig = nc.getBgpPeerConfig(remoteConfigId); VirtualRouter remoteVr = getRemoteBgpNeighborVR(remoteConfigId, allNodes); if (remoteVr == null) { return; } // Note prefixes we tried to originate _mainRib.getRoutes().forEach(r -> _prefixTracer.originated(r.getNetwork())); /* * Export route advertisements by looking at main RIB */ Set<RouteAdvertisement<BgpRoute>> exportedRoutes = _mainRib .getRoutes() .stream() // This performs transformations and filtering using the export policy .map( r -> exportBgpRoute( r, localConfigId, remoteConfigId, localConfig, remoteConfig, allNodes, sessionProperties)) .filter(Objects::nonNull) .map(RouteAdvertisement::new) .collect(ImmutableSet.toImmutableSet()); // Call this on the neighbor's VR! remoteVr.enqueueBgpMessages(edge.reverse(), exportedRoutes); /* * Export neighbor-specific generated routes, these routes skip global export policy */ Set<RouteAdvertisement<BgpRoute>> exportedNeighborSpecificRoutes = localConfig .getGeneratedRoutes() .stream() .map(this::processNeighborSpecificGeneratedRoute) .filter(Objects::nonNull) .map(RouteAdvertisement::new) .collect(ImmutableSet.toImmutableSet()); // Call this on the neighbor's VR, and reverse the egde! remoteVr.enqueueBgpMessages(edge.reverse(), exportedNeighborSpecificRoutes); // Note which BGP advertisements were sent markSentBgpAdvertisements( localConfigId, remoteConfigId, localConfig, remoteConfig, sessionProperties, exportedRoutes); markSentBgpAdvertisements( localConfigId, remoteConfigId, localConfig, remoteConfig, sessionProperties, exportedNeighborSpecificRoutes); } /** * Check whether given {@link GeneratedRoute} should be sent to a BGP neighbor. This checks * activation conditions for the generated route, and converts it to a {@link BgpRoute}. No export * policy computation is performed. * * @param generatedRoute route to process * @return a new {@link BgpRoute} if the {@code generatedRoute} was activated. */ @Nullable private BgpRoute processNeighborSpecificGeneratedRoute(@Nonnull GeneratedRoute generatedRoute) { String policyName = generatedRoute.getGenerationPolicy(); RoutingPolicy policy = policyName != null ? _c.getRoutingPolicies().get(policyName) : null; GeneratedRoute.Builder builder = GeneratedRouteHelper.activateGeneratedRoute( generatedRoute, policy, _mainRib.getRoutes(), _vrf.getName()); return builder != null ? BgpProtocolHelper.convertGeneratedRouteToBgp( builder.build(), _vrf.getBgpProcess().getRouterId()) : null; } /** * Compute our OSPF neighbors. * * @param allNodes map of all network nodes, keyed by hostname * @param topology the Layer-3 network topology * @return A sorted map of neighbor prefixes to links to which they correspond */ @Nullable SortedMap<Prefix, OspfLink> getOspfNeighbors( final Map<String, Node> allNodes, Topology topology) { // Check we have ospf process OspfProcess proc = _vrf.getOspfProcess(); if (proc == null) { return null; } String node = _c.getHostname(); SortedSet<Edge> edges = topology.getNodeEdges().get(node); if (edges == null) { // there are no edges, so OSPF won't produce anything return null; } SortedMap<Prefix, OspfLink> neighbors = new TreeMap<>(); for (Edge edge : edges) { if (!edge.getNode1().equals(node)) { continue; } String connectingInterfaceName = edge.getInt1(); Interface connectingInterface = _vrf.getInterfaces().get(connectingInterfaceName); if (connectingInterface == null) { // wrong vrf, so skip continue; } String neighborName = edge.getNode2(); Node neighbor = allNodes.get(neighborName); String neighborInterfaceName = edge.getInt2(); OspfArea area = connectingInterface.getOspfArea(); Configuration nc = neighbor.getConfiguration(); Interface neighborInterface = nc.getInterfaces().get(neighborInterfaceName); String neighborVrfName = neighborInterface.getVrfName(); VirtualRouter neighborVirtualRouter = allNodes.get(neighborName).getVirtualRouters().get(neighborVrfName); OspfArea neighborArea = neighborInterface.getOspfArea(); if (connectingInterface.getOspfEnabled() && !connectingInterface.getOspfPassive() && neighborInterface.getOspfEnabled() && !neighborInterface.getOspfPassive() && area != null && neighborArea != null && area.getName().equals(neighborArea.getName())) { neighbors.put( connectingInterface.getAddress().getPrefix(), new OspfLink(area, neighborArea, neighborVirtualRouter)); } } return ImmutableSortedMap.copyOf(neighbors); } public Configuration getConfiguration() { return _c; } ConnectedRib getConnectedRib() { return _connectedRib; } public Fib getFib() { return _fib; } Rib getMainRib() { return _mainRib; } BgpBestPathRib getBgpBestPathRib() { return _bgpBestPathRib; } /** Convenience method to get the VirtualRouter's hostname */ String getHostname() { return _c.getHostname(); } /** * Compute the "hashcode" of this router for the iBDP purposes. The hashcode is computed from the * following data structures: * * <ul> * <li>"external" RIBs ({@link #_mainRib}, {@link #_ospfExternalType1Rib}, {@link * #_ospfExternalType2Rib} * <li>message queues ({@link #_bgpIncomingRoutes} and {@link #_ospfExternalIncomingRoutes}) * </ul> * * @return integer hashcode */ int computeIterationHashCode() { return _mainRib.getRoutes().hashCode() + _ospfExternalType1Rib.getRoutes().hashCode() + _ospfExternalType2Rib.getRoutes().hashCode() + _bgpIncomingRoutes .values() .stream() .flatMap(Queue::stream) .mapToInt(RouteAdvertisement::hashCode) .sum() + _ospfExternalIncomingRoutes .values() .stream() .flatMap(Queue::stream) .mapToInt(RouteAdvertisement::hashCode) .sum() + _isisIncomingRoutes .values() .stream() .flatMap(Queue::stream) .mapToInt(RouteAdvertisement::hashCode) .sum(); } PrefixTracer getPrefixTracer() { return _prefixTracer; } /** * Given an {@link AbstractRoute}, run it through the BGP outbound transformations and export * routing policy. * * @param exportCandidate a route to try and export * @param ourConfig {@link BgpPeerConfig} that sends the route * @param remoteConfig {@link BgpPeerConfig} that will be receiving the route * @param allNodes all nodes in the network * @return The transformed route as a {@link BgpRoute}, or {@code null} if the route should not be * exported. */ @Nullable private BgpRoute exportBgpRoute( @Nonnull AbstractRoute exportCandidate, @Nonnull BgpPeerConfigId ourConfigId, @Nonnull BgpPeerConfigId remoteConfigId, @Nonnull BgpPeerConfig ourConfig, @Nonnull BgpPeerConfig remoteConfig, @Nonnull Map<String, Node> allNodes, @Nonnull BgpSessionProperties sessionProperties) { RoutingPolicy exportPolicy = _c.getRoutingPolicies().get(ourConfig.getExportPolicy()); BgpRoute.Builder transformedOutgoingRouteBuilder; try { transformedOutgoingRouteBuilder = BgpProtocolHelper.transformBgpRouteOnExport( ourConfig, remoteConfig, sessionProperties, _vrf, requireNonNull(getRemoteBgpNeighborVR(remoteConfigId, allNodes))._vrf, exportCandidate); } catch (BgpRoutePropagationException e) { // TODO: Log a warning return null; } if (transformedOutgoingRouteBuilder == null) { // This route could not be exported for core bgp protocol reasons return null; } // Process transformed outgoing route by the export policy boolean shouldExport = exportPolicy.process( exportCandidate, transformedOutgoingRouteBuilder, remoteConfig.getLocalIp(), ourConfigId.getRemotePeerPrefix(), ourConfigId.getVrfName(), Direction.OUT); VirtualRouter remoteVr = getRemoteBgpNeighborVR(remoteConfigId, allNodes); if (!shouldExport) { // This route could not be exported due to export policy _prefixTracer.filtered( exportCandidate.getNetwork(), requireNonNull(remoteVr).getHostname(), remoteConfig.getLocalIp(), remoteConfigId.getVrfName(), ourConfig.getExportPolicy(), Direction.OUT); return null; } // Successfully exported route BgpRoute transformedOutgoingRoute = transformedOutgoingRouteBuilder.build(); _prefixTracer.sentTo( transformedOutgoingRoute.getNetwork(), requireNonNull(remoteVr).getHostname(), remoteConfig.getLocalIp(), remoteConfigId.getVrfName(), ourConfig.getExportPolicy()); return transformedOutgoingRoute; } Set<BgpAdvertisement> getReceivedBgpAdvertisements() { return _receivedBgpAdvertisements; } Set<BgpAdvertisement> getSentBgpAdvertisements() { return _sentBgpAdvertisements; } public BgpMultipathRib getBgpMultipathRib() { return _bgpMultipathRib; } }
ISIS: fix next hop ip (#1849)
projects/batfish/src/main/java/org/batfish/dataplane/ibdp/VirtualRouter.java
ISIS: fix next hop ip (#1849)
<ide><path>rojects/batfish/src/main/java/org/batfish/dataplane/ibdp/VirtualRouter.java <ide> int l2Admin = RoutingProtocol.ISIS_L2.getDefaultAdministrativeCost(_c.getConfigurationFormat()); <ide> _isisIncomingRoutes.forEach( <ide> (edge, queue) -> { <del> Ip nextHopIp = edge.getNode2().getInterface(nodes).getAddress().getIp(); <del> Interface iface = edge.getNode1().getInterface(nodes); <add> Ip nextHopIp = edge.getNode1().getInterface(nodes).getAddress().getIp(); <add> Interface iface = edge.getNode2().getInterface(nodes); <ide> routeBuilder.setNextHopIp(nextHopIp); <ide> while (queue.peek() != null) { <ide> RouteAdvertisement<IsisRoute> routeAdvert = queue.remove();
Java
agpl-3.0
5b256fbc7190e413d2a4c6bfe4d13cb0ff6fccc5
0
akvo/akvo-flow,akvo/akvo-flow,akvo/akvo-flow,akvo/akvo-flow,akvo/akvo-flow
package org.waterforpeople.mapping.app.web; import static com.google.appengine.api.labs.taskqueue.TaskOptions.Builder.url; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Random; import java.util.TreeMap; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.bind.JAXBException; import org.apache.commons.lang.StringEscapeUtils; import org.apache.log4j.Logger; import org.waterforpeople.mapping.app.web.dto.SurveyAssemblyRequest; import org.waterforpeople.mapping.dao.SurveyContainerDao; import com.gallatinsystems.common.domain.UploadStatusContainer; import com.gallatinsystems.common.util.PropertyUtil; import com.gallatinsystems.common.util.UploadUtil; import com.gallatinsystems.common.util.ZipUtil; import com.gallatinsystems.framework.rest.AbstractRestApiServlet; import com.gallatinsystems.framework.rest.RestRequest; import com.gallatinsystems.framework.rest.RestResponse; import com.gallatinsystems.messaging.dao.MessageDao; import com.gallatinsystems.messaging.domain.Message; import com.gallatinsystems.survey.dao.QuestionDao; import com.gallatinsystems.survey.dao.QuestionGroupDao; import com.gallatinsystems.survey.dao.SurveyDAO; import com.gallatinsystems.survey.dao.SurveyXMLFragmentDao; import com.gallatinsystems.survey.domain.Question; import com.gallatinsystems.survey.domain.QuestionGroup; import com.gallatinsystems.survey.domain.QuestionHelpMedia; import com.gallatinsystems.survey.domain.QuestionOption; import com.gallatinsystems.survey.domain.ScoringRule; import com.gallatinsystems.survey.domain.Survey; import com.gallatinsystems.survey.domain.SurveyContainer; import com.gallatinsystems.survey.domain.SurveyXMLFragment; import com.gallatinsystems.survey.domain.SurveyXMLFragment.FRAGMENT_TYPE; import com.gallatinsystems.survey.domain.Translation; import com.gallatinsystems.survey.domain.xml.AltText; import com.gallatinsystems.survey.domain.xml.Dependency; import com.gallatinsystems.survey.domain.xml.Help; import com.gallatinsystems.survey.domain.xml.ObjectFactory; import com.gallatinsystems.survey.domain.xml.Option; import com.gallatinsystems.survey.domain.xml.Options; import com.gallatinsystems.survey.domain.xml.Score; import com.gallatinsystems.survey.domain.xml.Scoring; import com.gallatinsystems.survey.domain.xml.ValidationRule; import com.gallatinsystems.survey.xml.SurveyXMLAdapter; import com.google.appengine.api.backends.BackendServiceFactory; import com.google.appengine.api.datastore.Text; import com.google.appengine.api.labs.taskqueue.Queue; import com.google.appengine.api.labs.taskqueue.QueueFactory; import com.google.appengine.api.labs.taskqueue.TaskOptions; public class SurveyAssemblyServlet extends AbstractRestApiServlet { private static final Logger log = Logger .getLogger(SurveyAssemblyServlet.class.getName()); private static final int BACKEND_QUESTION_THRESHOLD = 60; private static final String BACKEND_PUBLISH_PROP = "backendpublish"; private static final long serialVersionUID = -6044156962558183224L; private static final String OPTION_RENDER_MODE_PROP = "optionRenderMode"; public static final String FREE_QUESTION_TYPE = "free"; public static final String OPTION_QUESTION_TYPE = "option"; public static final String GEO_QUESTION_TYPE = "geo"; public static final String VIDEO_QUESTION_TYPE = "video"; public static final String PHOTO_QUESTION_TYPE = "photo"; public static final String SCAN_QUESTION_TYPE = "scan"; public static final String STRENGTH_QUESTION_TYPE = "strength"; public static final String DATE_QUESTION_TYPE = "date"; private static final String SURVEY_UPLOAD_URL = "surveyuploadurl"; private static final String SURVEY_UPLOAD_DIR = "surveyuploaddir"; private static final String SURVEY_UPLOAD_SIG = "surveyuploadsig"; private static final String SURVEY_UPLOAD_POLICY = "surveyuploadpolicy"; private static final String S3_ID = "aws_identifier"; @Override protected RestRequest convertRequest() throws Exception { HttpServletRequest req = getRequest(); RestRequest restRequest = new SurveyAssemblyRequest(); restRequest.populateFromHttpRequest(req); return restRequest; } @Override protected RestResponse handleRequest(RestRequest req) throws Exception { RestResponse response = new RestResponse(); SurveyAssemblyRequest importReq = (SurveyAssemblyRequest) req; if (SurveyAssemblyRequest.ASSEMBLE_SURVEY.equalsIgnoreCase(importReq .getAction())) { QuestionDao questionDao = new QuestionDao(); boolean useBackend = false; // make sure we're not already running on a backend and that we are // allowed to use one if (!importReq.getIsForwarded() && "true".equalsIgnoreCase(PropertyUtil .getProperty(BACKEND_PUBLISH_PROP))) { // if we're allowed to use a backend, then check to see if we // need to (based on survey size) List<Question> questionList = questionDao .listQuestionsBySurvey(importReq.getSurveyId()); if (questionList != null && questionList.size() > BACKEND_QUESTION_THRESHOLD) { useBackend = true; } } if (useBackend) { com.google.appengine.api.taskqueue.TaskOptions options = com.google.appengine.api.taskqueue.TaskOptions.Builder .withUrl("/app_worker/surveyassembly") .param(SurveyAssemblyRequest.ACTION_PARAM, SurveyAssemblyRequest.ASSEMBLE_SURVEY) .param(SurveyAssemblyRequest.IS_FWD_PARAM, "true") .param(SurveyAssemblyRequest.SURVEY_ID_PARAM, importReq.getSurveyId().toString()); // change the host so the queue invokes the backend options = options .header("Host", BackendServiceFactory.getBackendService() .getBackendAddress("dataprocessor")); com.google.appengine.api.taskqueue.Queue queue = com.google.appengine.api.taskqueue.QueueFactory .getQueue("surveyAssembly"); queue.add(options); } else { // assembleSurvey(importReq.getSurveyId()); assembleSurveyOnePass(importReq.getSurveyId()); } } else if (SurveyAssemblyRequest.DISPATCH_ASSEMBLE_QUESTION_GROUP .equalsIgnoreCase(importReq.getAction())) { this.dispatchAssembleQuestionGroup(importReq.getSurveyId(), importReq.getQuestionGroupId(), importReq.getTransactionId()); } else if (SurveyAssemblyRequest.ASSEMBLE_QUESTION_GROUP .equalsIgnoreCase(importReq.getAction())) { assembleQuestionGroups(importReq.getSurveyId(), importReq.getTransactionId()); } else if (SurveyAssemblyRequest.DISTRIBUTE_SURVEY .equalsIgnoreCase(importReq.getAction())) { uploadSurvey(importReq.getSurveyId(), importReq.getTransactionId()); } else if (SurveyAssemblyRequest.CLEANUP.equalsIgnoreCase(importReq .getAction())) { cleanupFragments(importReq.getSurveyId(), importReq.getTransactionId()); } return response; } /** * uploads full survey XML to S3 * * @param surveyId */ private void uploadSurvey(Long surveyId, Long transactionId) { SurveyContainerDao scDao = new SurveyContainerDao(); SurveyContainer sc = scDao.findBySurveyId(surveyId); Properties props = System.getProperties(); String document = sc.getSurveyDocument().getValue(); boolean uploadedFile = UploadUtil.sendStringAsFile(sc.getSurveyId() + ".xml", document, props.getProperty(SURVEY_UPLOAD_DIR), props.getProperty(SURVEY_UPLOAD_URL), props.getProperty(S3_ID), props.getProperty(SURVEY_UPLOAD_POLICY), props.getProperty(SURVEY_UPLOAD_SIG), "text/xml"); ByteArrayOutputStream os = ZipUtil.generateZip(document, sc.getSurveyId() + ".xml"); boolean uploadedZip = UploadUtil.upload(os, sc.getSurveyId() + ".zip", props.getProperty(SURVEY_UPLOAD_DIR), props.getProperty(SURVEY_UPLOAD_URL), props.getProperty(S3_ID), props.getProperty(SURVEY_UPLOAD_POLICY), props.getProperty(SURVEY_UPLOAD_SIG), "application/zip", null); sendQueueMessage(SurveyAssemblyRequest.CLEANUP, surveyId, null, transactionId); Message message = new Message(); message.setActionAbout("surveyAssembly"); message.setObjectId(surveyId); // String messageText = CONSTANTS.surveyPublishOkMessage() + " " // + url; if (uploadedFile && uploadedZip) { // increment the version so devices know to pick up the changes SurveyDAO surveyDao = new SurveyDAO(); surveyDao.incrementVersion(surveyId); String messageText = "Published. Please check: " + props.getProperty(SURVEY_UPLOAD_URL) + props.getProperty(SURVEY_UPLOAD_DIR) + "/" + surveyId + ".xml"; message.setShortMessage(messageText); Survey s = surveyDao.getById(surveyId); if (s != null) { message.setObjectTitle(s.getPath() + "/" + s.getName()); } message.setTransactionUUID(transactionId.toString()); MessageDao messageDao = new MessageDao(); messageDao.save(message); } else { // String messageText = // CONSTANTS.surveyPublishErrorMessage(); String messageText = "Failed to publish: " + surveyId + "\n"; message.setTransactionUUID(transactionId.toString()); message.setMessage(messageText); MessageDao messageDao = new MessageDao(); messageDao.save(message); } } /** * deletes fragments for the survey * * @param surveyId */ private void cleanupFragments(Long surveyId, Long transactionId) { SurveyXMLFragmentDao sxmlfDao = new SurveyXMLFragmentDao(); sxmlfDao.deleteFragmentsForSurvey(surveyId, transactionId); } @Override protected void writeOkResponse(RestResponse resp) throws Exception { HttpServletResponse httpResp = getResponse(); httpResp.setStatus(HttpServletResponse.SC_OK); httpResp.setContentType("text/plain"); httpResp.getWriter().print("OK"); } private void assembleSurveyOnePass(Long surveyId) { /************** * 1, Select survey based on surveyId 2. Retrieve all question groups * fire off queue tasks */ log.warn("Starting assembly of "+surveyId); // Swap with proper UUID SurveyDAO surveyDao = new SurveyDAO(); Survey s = surveyDao.getById(surveyId); Long transactionId = new Random().nextLong(); String surveyHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><survey"; String lang = "en"; if (s != null && s.getDefaultLanguageCode() != null) { lang = s.getDefaultLanguageCode(); } surveyHeader += " defaultLanguageCode='" + lang + "'>"; String surveyFooter = "</survey>"; QuestionGroupDao qgDao = new QuestionGroupDao(); TreeMap<Integer, QuestionGroup> qgList = qgDao .listQuestionGroupsBySurvey(surveyId); if (qgList != null) { StringBuilder surveyXML = new StringBuilder(); surveyXML.append(surveyHeader); for (QuestionGroup item : qgList.values()) { log.warn("Assembling group "+item.getKey().getId()+" for survey "+surveyId); surveyXML.append(buildQuestionGroupXML(item)); } surveyXML.append(surveyFooter); log.warn("Uploading "+surveyId); UploadStatusContainer uc = uploadSurveyXML(surveyId, surveyXML.toString()); Message message = new Message(); message.setActionAbout("surveyAssembly"); message.setObjectId(surveyId); // String messageText = CONSTANTS.surveyPublishOkMessage() + " " // + url; if (uc.getUploadedFile() && uc.getUploadedZip()) { // increment the version so devices know to pick up the changes log.warn("Finishing assembly of "+surveyId); surveyDao.incrementVersion(surveyId); String messageText = "Published. Please check: " + uc.getUrl(); message.setShortMessage(messageText); if (qgList != null && qgList.size() > 0) { for (QuestionGroup g : qgList.values()) { if (g.getPath() != null) { message.setObjectTitle(g.getPath()); break; } } } message.setTransactionUUID(transactionId.toString()); MessageDao messageDao = new MessageDao(); messageDao.save(message); } else { // String messageText = // CONSTANTS.surveyPublishErrorMessage(); String messageText = "Failed to publish: " + surveyId + "\n" + uc.getMessage(); message.setTransactionUUID(transactionId.toString()); message.setMessage(messageText); MessageDao messageDao = new MessageDao(); messageDao.save(message); } log.warn("Completed onepass aseembly method for "+surveyId); } } public UploadStatusContainer uploadSurveyXML(Long surveyId, String surveyXML) { Properties props = System.getProperties(); String document = surveyXML; Boolean uploadedFile = UploadUtil.sendStringAsFile(surveyId + ".xml", document, props.getProperty(SURVEY_UPLOAD_DIR), props.getProperty(SURVEY_UPLOAD_URL), props.getProperty(S3_ID), props.getProperty(SURVEY_UPLOAD_POLICY), props.getProperty(SURVEY_UPLOAD_SIG), "text/xml"); ByteArrayOutputStream os = ZipUtil.generateZip(document, surveyId + ".xml"); UploadStatusContainer uc = new UploadStatusContainer(); Boolean uploadedZip = UploadUtil.upload(os, surveyId + ".zip", props.getProperty(SURVEY_UPLOAD_DIR), props.getProperty(SURVEY_UPLOAD_URL), props.getProperty(S3_ID), props.getProperty(SURVEY_UPLOAD_POLICY), props.getProperty(SURVEY_UPLOAD_SIG), "application/zip", uc); uc.setUploadedFile(uploadedFile); uc.setUploadedZip(uploadedZip); uc.setUrl(props.getProperty(SURVEY_UPLOAD_URL) + props.getProperty(SURVEY_UPLOAD_DIR) + "/" + surveyId + ".xml"); return uc; } public String buildQuestionGroupXML(QuestionGroup item) { QuestionDao questionDao = new QuestionDao(); QuestionGroupDao questionGroupDao = new QuestionGroupDao(); QuestionGroup group = questionGroupDao.getByKey(item.getKey().getId()); TreeMap<Integer, Question> questionList = questionDao .listQuestionsByQuestionGroup(item.getKey().getId(), true); StringBuilder sb = new StringBuilder("<questionGroup><heading>") .append(StringEscapeUtils.escapeXml(group.getCode())).append( "</heading>"); int count = 0; if (questionList != null) { for (Question q : questionList.values()) { sb.append(marshallQuestion(q)); count++; } } return sb.toString() + "</questionGroup>"; } private void assembleSurvey(Long surveyId) { /************** * 1, Select survey based on surveyId 2. Retrieve all question groups * fire off queue tasks */ QuestionGroupDao qgDao = new QuestionGroupDao(); TreeMap<Integer, QuestionGroup> qgList = qgDao .listQuestionGroupsBySurvey(surveyId); if (qgList != null) { ArrayList<Long> questionGroupIdList = new ArrayList<Long>(); StringBuilder builder = new StringBuilder(); int count = 1; for (QuestionGroup item : qgList.values()) { questionGroupIdList.add(item.getKey().getId()); builder.append(item.getKey().getId()); if (count < qgList.size()) { builder.append(","); } count++; } count = 0; Long transactionId = new Random().nextLong(); sendQueueMessage( SurveyAssemblyRequest.DISPATCH_ASSEMBLE_QUESTION_GROUP, surveyId, builder.toString(), transactionId); } } /** * sends a message to the task queue for survey assembly * * @param action * @param surveyId * @param questionGroups */ private void sendQueueMessage(String action, Long surveyId, String questionGroups, Long transactionId) { Queue surveyAssemblyQueue = QueueFactory.getQueue("surveyAssembly"); TaskOptions task = url("/app_worker/surveyassembly").param("action", action).param("surveyId", surveyId.toString()); if (questionGroups != null) { task.param("questionGroupId", questionGroups); } if (transactionId != null) { task.param("transactionId", transactionId.toString()); } surveyAssemblyQueue.add(task); } private void dispatchAssembleQuestionGroup(Long surveyId, String questionGroupIds, Long transactionId) { boolean isLast = true; String currentId = questionGroupIds; String remainingIds = null; if (questionGroupIds.contains(",")) { isLast = false; currentId = questionGroupIds.substring(0, questionGroupIds.indexOf(",")); remainingIds = questionGroupIds.substring(questionGroupIds .indexOf(",") + 1); } QuestionDao questionDao = new QuestionDao(); QuestionGroupDao questionGroupDao = new QuestionGroupDao(); QuestionGroup group = questionGroupDao.getByKey(Long .parseLong(currentId)); TreeMap<Integer, Question> questionList = questionDao .listQuestionsByQuestionGroup(Long.parseLong(currentId), true); StringBuilder sb = new StringBuilder("<questionGroup><heading>") .append(group.getCode()).append("</heading>"); int count = 0; if (questionList != null) { for (Question q : questionList.values()) { sb.append(marshallQuestion(q)); count++; } } SurveyXMLFragment sxf = new SurveyXMLFragment(); sxf.setSurveyId(surveyId); sxf.setQuestionGroupId(Long.parseLong(currentId)); sxf.setFragmentOrder(group.getOrder()); sxf.setFragment(new Text(sb.append("</questionGroup>").toString())); sxf.setTransactionId(transactionId); sxf.setFragmentType(FRAGMENT_TYPE.QUESTION_GROUP); SurveyXMLFragmentDao sxmlfDao = new SurveyXMLFragmentDao(); sxmlfDao.save(sxf); if (isLast) { // Assemble the fragments sendQueueMessage(SurveyAssemblyRequest.ASSEMBLE_QUESTION_GROUP, surveyId, null, transactionId); } else { sendQueueMessage( SurveyAssemblyRequest.DISPATCH_ASSEMBLE_QUESTION_GROUP, surveyId, remainingIds, transactionId); } } private String marshallQuestion(Question q) { SurveyXMLAdapter sax = new SurveyXMLAdapter(); ObjectFactory objFactory = new ObjectFactory(); com.gallatinsystems.survey.domain.xml.Question qXML = objFactory .createQuestion(); qXML.setId(new String("" + q.getKey().getId() + "")); // ToDo fix qXML.setMandatory("false"); if (q.getText() != null) { com.gallatinsystems.survey.domain.xml.Text t = new com.gallatinsystems.survey.domain.xml.Text(); t.setContent(q.getText()); qXML.setText(t); } List<Help> helpList = new ArrayList<Help>(); // this is here for backward compatibility if (q.getTip() != null) { Help tip = new Help(); com.gallatinsystems.survey.domain.xml.Text t = new com.gallatinsystems.survey.domain.xml.Text(); t.setContent(q.getTip()); tip.setText(t); tip.setType("tip"); if (q.getTip() != null && q.getTip().trim().length() > 0 && !"null".equalsIgnoreCase(q.getTip().trim())) { helpList.add(tip); } } if (q.getQuestionHelpMediaMap() != null) { for (QuestionHelpMedia helpItem : q.getQuestionHelpMediaMap() .values()) { Help tip = new Help(); com.gallatinsystems.survey.domain.xml.Text t = new com.gallatinsystems.survey.domain.xml.Text(); t.setContent(helpItem.getText()); if (helpItem.getType() == QuestionHelpMedia.Type.TEXT) { tip.setType("tip"); } else { tip.setType(helpItem.getType().toString().toLowerCase()); } if (helpItem.getTranslationMap() != null) { List<AltText> translationList = new ArrayList<AltText>(); for (Translation trans : helpItem.getTranslationMap() .values()) { AltText aText = new AltText(); aText.setContent(trans.getText()); aText.setLanguage(trans.getLanguageCode()); aText.setType("translation"); translationList.add(aText); } if (translationList.size() > 0) { tip.setAltText(translationList); } } helpList.add(tip); } } if (helpList.size() > 0) { qXML.setHelp(helpList); } if (q.getValidationRule() != null) { ValidationRule validationRule = objFactory.createValidationRule(); // TODO set validation rule xml // validationRule.setAllowDecimal(value) } qXML.setAltText(formAltText(q.getTranslationMap())); if (q.getType().equals(Question.Type.FREE_TEXT)) { qXML.setType(FREE_QUESTION_TYPE); } else if (q.getType().equals(Question.Type.GEO)) { qXML.setType(GEO_QUESTION_TYPE); } else if (q.getType().equals(Question.Type.NUMBER)) { qXML.setType(FREE_QUESTION_TYPE); ValidationRule vrule = new ValidationRule(); vrule.setValidationType("numeric"); vrule.setSigned("false"); qXML.setValidationRule(vrule); } else if (q.getType().equals(Question.Type.OPTION)) { qXML.setType(OPTION_QUESTION_TYPE); } else if (q.getType().equals(Question.Type.PHOTO)) { qXML.setType(PHOTO_QUESTION_TYPE); } else if (q.getType().equals(Question.Type.VIDEO)) { qXML.setType(VIDEO_QUESTION_TYPE); } else if (q.getType().equals(Question.Type.SCAN)) { qXML.setType(SCAN_QUESTION_TYPE); } else if (q.getType().equals(Question.Type.NAME)) { qXML.setType(FREE_QUESTION_TYPE); ValidationRule vrule = new ValidationRule(); vrule.setValidationType("name"); qXML.setValidationRule(vrule); } else if (q.getType().equals(Question.Type.STRENGTH)) { qXML.setType(STRENGTH_QUESTION_TYPE); } else if (q.getType().equals(Question.Type.DATE)) { qXML.setType(DATE_QUESTION_TYPE); } if (q.getOrder() != null) { qXML.setOrder(q.getOrder().toString()); } if (q.getMandatoryFlag() != null) { qXML.setMandatory(q.getMandatoryFlag().toString()); } Dependency dependency = objFactory.createDependency(); if (q.getDependentQuestionId() != null) { dependency.setQuestion(q.getDependentQuestionId().toString()); dependency.setAnswerValue(q.getDependentQuestionAnswer()); qXML.setDependency(dependency); } if (q.getQuestionOptionMap() != null && q.getQuestionOptionMap().size() > 0) { Options options = objFactory.createOptions(); if (q.getAllowOtherFlag() != null) { options.setAllowOther(q.getAllowOtherFlag().toString()); } if (q.getAllowMultipleFlag() != null) { options.setAllowMultiple(q.getAllowMultipleFlag().toString()); } if (options.getAllowMultiple() == null || "false".equals(options.getAllowMultiple())) { options.setRenderType(PropertyUtil .getProperty(OPTION_RENDER_MODE_PROP)); } ArrayList<Option> optionList = new ArrayList<Option>(); for (QuestionOption qo : q.getQuestionOptionMap().values()) { Option option = objFactory.createOption(); com.gallatinsystems.survey.domain.xml.Text t = new com.gallatinsystems.survey.domain.xml.Text(); t.setContent(qo.getText()); option.addContent(t); option.setValue(qo.getCode() != null ? qo.getCode() : qo .getText()); List<AltText> altTextList = formAltText(qo.getTranslationMap()); if (altTextList != null) { for (AltText alt : altTextList) { option.addContent(alt); } } optionList.add(option); } options.setOption(optionList); qXML.setOptions(options); } if (q.getScoringRules() != null) { Scoring scoring = new Scoring(); for (ScoringRule rule : q.getScoringRules()) { Score score = new Score(); if (scoring.getType() == null) { scoring.setType(rule.getType().toLowerCase()); } score.setRangeHigh(rule.getRangeMax()); score.setRangeLow(rule.getRangeMin()); score.setValue(rule.getValue()); scoring.addScore(score); } if (scoring.getScore() != null && scoring.getScore().size() > 0) { qXML.setScoring(scoring); } } String questionDocument = null; try { questionDocument = sax.marshal(qXML); } catch (JAXBException e) { log.warn("Could not marshal question: " + qXML, e); } questionDocument = questionDocument .replace( "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>", ""); return questionDocument; } private List<AltText> formAltText(Map<String, Translation> translationMap) { List<AltText> altTextList = new ArrayList<AltText>(); if (translationMap != null) { for (Translation lang : translationMap.values()) { AltText alt = new AltText(); alt.setContent(lang.getText()); alt.setType("translation"); alt.setLanguage(lang.getLanguageCode()); altTextList.add(alt); } } return altTextList; } private void assembleQuestionGroups(Long surveyId, Long transactionId) { SurveyXMLFragmentDao sxmlfDao = new SurveyXMLFragmentDao(); List<SurveyXMLFragment> sxmlfList = sxmlfDao.listSurveyFragments( surveyId, SurveyXMLFragment.FRAGMENT_TYPE.QUESTION_GROUP, transactionId); StringBuilder sbQG = new StringBuilder(); for (SurveyXMLFragment item : sxmlfList) { sbQG.append(item.getFragment().getValue()); } StringBuilder completeSurvey = new StringBuilder(); String surveyHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><survey>"; String surveyFooter = "</survey>"; completeSurvey.append(surveyHeader); completeSurvey.append(sbQG.toString()); sbQG = null; completeSurvey.append(surveyFooter); SurveyContainerDao scDao = new SurveyContainerDao(); SurveyContainer sc = scDao.findBySurveyId(surveyId); if (sc == null) { sc = new SurveyContainer(); } sc.setSurveyDocument(new Text(completeSurvey.toString())); sc.setSurveyId(surveyId); scDao.save(sc); sendQueueMessage(SurveyAssemblyRequest.DISTRIBUTE_SURVEY, surveyId, null, transactionId); } }
GAE/src/org/waterforpeople/mapping/app/web/SurveyAssemblyServlet.java
package org.waterforpeople.mapping.app.web; import static com.google.appengine.api.labs.taskqueue.TaskOptions.Builder.url; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Random; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.bind.JAXBException; import org.apache.commons.lang.StringEscapeUtils; import org.waterforpeople.mapping.app.web.dto.SurveyAssemblyRequest; import org.waterforpeople.mapping.dao.SurveyContainerDao; import com.gallatinsystems.common.domain.UploadStatusContainer; import com.gallatinsystems.common.util.PropertyUtil; import com.gallatinsystems.common.util.UploadUtil; import com.gallatinsystems.common.util.ZipUtil; import com.gallatinsystems.framework.rest.AbstractRestApiServlet; import com.gallatinsystems.framework.rest.RestRequest; import com.gallatinsystems.framework.rest.RestResponse; import com.gallatinsystems.messaging.dao.MessageDao; import com.gallatinsystems.messaging.domain.Message; import com.gallatinsystems.survey.dao.QuestionDao; import com.gallatinsystems.survey.dao.QuestionGroupDao; import com.gallatinsystems.survey.dao.SurveyDAO; import com.gallatinsystems.survey.dao.SurveyXMLFragmentDao; import com.gallatinsystems.survey.domain.Question; import com.gallatinsystems.survey.domain.QuestionGroup; import com.gallatinsystems.survey.domain.QuestionHelpMedia; import com.gallatinsystems.survey.domain.QuestionOption; import com.gallatinsystems.survey.domain.ScoringRule; import com.gallatinsystems.survey.domain.Survey; import com.gallatinsystems.survey.domain.SurveyContainer; import com.gallatinsystems.survey.domain.SurveyXMLFragment; import com.gallatinsystems.survey.domain.SurveyXMLFragment.FRAGMENT_TYPE; import com.gallatinsystems.survey.domain.Translation; import com.gallatinsystems.survey.domain.xml.AltText; import com.gallatinsystems.survey.domain.xml.Dependency; import com.gallatinsystems.survey.domain.xml.Help; import com.gallatinsystems.survey.domain.xml.ObjectFactory; import com.gallatinsystems.survey.domain.xml.Option; import com.gallatinsystems.survey.domain.xml.Options; import com.gallatinsystems.survey.domain.xml.Score; import com.gallatinsystems.survey.domain.xml.Scoring; import com.gallatinsystems.survey.domain.xml.ValidationRule; import com.gallatinsystems.survey.xml.SurveyXMLAdapter; import com.google.appengine.api.backends.BackendServiceFactory; import com.google.appengine.api.datastore.Text; import com.google.appengine.api.labs.taskqueue.Queue; import com.google.appengine.api.labs.taskqueue.QueueFactory; import com.google.appengine.api.labs.taskqueue.TaskOptions; public class SurveyAssemblyServlet extends AbstractRestApiServlet { private static final Logger log = Logger .getLogger(SurveyAssemblyServlet.class.getName()); private static final int BACKEND_QUESTION_THRESHOLD = 60; private static final String BACKEND_PUBLISH_PROP = "backendpublish"; private static final long serialVersionUID = -6044156962558183224L; private static final String OPTION_RENDER_MODE_PROP = "optionRenderMode"; public static final String FREE_QUESTION_TYPE = "free"; public static final String OPTION_QUESTION_TYPE = "option"; public static final String GEO_QUESTION_TYPE = "geo"; public static final String VIDEO_QUESTION_TYPE = "video"; public static final String PHOTO_QUESTION_TYPE = "photo"; public static final String SCAN_QUESTION_TYPE = "scan"; public static final String STRENGTH_QUESTION_TYPE = "strength"; public static final String DATE_QUESTION_TYPE = "date"; private static final String SURVEY_UPLOAD_URL = "surveyuploadurl"; private static final String SURVEY_UPLOAD_DIR = "surveyuploaddir"; private static final String SURVEY_UPLOAD_SIG = "surveyuploadsig"; private static final String SURVEY_UPLOAD_POLICY = "surveyuploadpolicy"; private static final String S3_ID = "aws_identifier"; @Override protected RestRequest convertRequest() throws Exception { HttpServletRequest req = getRequest(); RestRequest restRequest = new SurveyAssemblyRequest(); restRequest.populateFromHttpRequest(req); return restRequest; } @Override protected RestResponse handleRequest(RestRequest req) throws Exception { RestResponse response = new RestResponse(); SurveyAssemblyRequest importReq = (SurveyAssemblyRequest) req; if (SurveyAssemblyRequest.ASSEMBLE_SURVEY.equalsIgnoreCase(importReq .getAction())) { QuestionDao questionDao = new QuestionDao(); boolean useBackend = false; // make sure we're not already running on a backend and that we are // allowed to use one if (!importReq.getIsForwarded() && "true".equalsIgnoreCase(PropertyUtil .getProperty(BACKEND_PUBLISH_PROP))) { // if we're allowed to use a backend, then check to see if we // need to (based on survey size) List<Question> questionList = questionDao .listQuestionsBySurvey(importReq.getSurveyId()); if (questionList != null && questionList.size() > BACKEND_QUESTION_THRESHOLD) { useBackend = true; } } if (useBackend) { com.google.appengine.api.taskqueue.TaskOptions options = com.google.appengine.api.taskqueue.TaskOptions.Builder .withUrl("/app_worker/surveyassembly") .param(SurveyAssemblyRequest.ACTION_PARAM, SurveyAssemblyRequest.ASSEMBLE_SURVEY) .param(SurveyAssemblyRequest.IS_FWD_PARAM, "true") .param(SurveyAssemblyRequest.SURVEY_ID_PARAM, importReq.getSurveyId().toString()); // change the host so the queue invokes the backend options = options .header("Host", BackendServiceFactory.getBackendService() .getBackendAddress("dataprocessor")); com.google.appengine.api.taskqueue.Queue queue = com.google.appengine.api.taskqueue.QueueFactory .getQueue("surveyAssembly"); queue.add(options); } else { // assembleSurvey(importReq.getSurveyId()); assembleSurveyOnePass(importReq.getSurveyId()); } } else if (SurveyAssemblyRequest.DISPATCH_ASSEMBLE_QUESTION_GROUP .equalsIgnoreCase(importReq.getAction())) { this.dispatchAssembleQuestionGroup(importReq.getSurveyId(), importReq.getQuestionGroupId(), importReq.getTransactionId()); } else if (SurveyAssemblyRequest.ASSEMBLE_QUESTION_GROUP .equalsIgnoreCase(importReq.getAction())) { assembleQuestionGroups(importReq.getSurveyId(), importReq.getTransactionId()); } else if (SurveyAssemblyRequest.DISTRIBUTE_SURVEY .equalsIgnoreCase(importReq.getAction())) { uploadSurvey(importReq.getSurveyId(), importReq.getTransactionId()); } else if (SurveyAssemblyRequest.CLEANUP.equalsIgnoreCase(importReq .getAction())) { cleanupFragments(importReq.getSurveyId(), importReq.getTransactionId()); } return response; } /** * uploads full survey XML to S3 * * @param surveyId */ private void uploadSurvey(Long surveyId, Long transactionId) { SurveyContainerDao scDao = new SurveyContainerDao(); SurveyContainer sc = scDao.findBySurveyId(surveyId); Properties props = System.getProperties(); String document = sc.getSurveyDocument().getValue(); boolean uploadedFile = UploadUtil.sendStringAsFile(sc.getSurveyId() + ".xml", document, props.getProperty(SURVEY_UPLOAD_DIR), props.getProperty(SURVEY_UPLOAD_URL), props.getProperty(S3_ID), props.getProperty(SURVEY_UPLOAD_POLICY), props.getProperty(SURVEY_UPLOAD_SIG), "text/xml"); ByteArrayOutputStream os = ZipUtil.generateZip(document, sc.getSurveyId() + ".xml"); boolean uploadedZip = UploadUtil.upload(os, sc.getSurveyId() + ".zip", props.getProperty(SURVEY_UPLOAD_DIR), props.getProperty(SURVEY_UPLOAD_URL), props.getProperty(S3_ID), props.getProperty(SURVEY_UPLOAD_POLICY), props.getProperty(SURVEY_UPLOAD_SIG), "application/zip", null); sendQueueMessage(SurveyAssemblyRequest.CLEANUP, surveyId, null, transactionId); Message message = new Message(); message.setActionAbout("surveyAssembly"); message.setObjectId(surveyId); // String messageText = CONSTANTS.surveyPublishOkMessage() + " " // + url; if (uploadedFile && uploadedZip) { // increment the version so devices know to pick up the changes SurveyDAO surveyDao = new SurveyDAO(); surveyDao.incrementVersion(surveyId); String messageText = "Published. Please check: " + props.getProperty(SURVEY_UPLOAD_URL) + props.getProperty(SURVEY_UPLOAD_DIR) + "/" + surveyId + ".xml"; message.setShortMessage(messageText); Survey s = surveyDao.getById(surveyId); if (s != null) { message.setObjectTitle(s.getPath() + "/" + s.getName()); } message.setTransactionUUID(transactionId.toString()); MessageDao messageDao = new MessageDao(); messageDao.save(message); } else { // String messageText = // CONSTANTS.surveyPublishErrorMessage(); String messageText = "Failed to publish: " + surveyId + "\n"; message.setTransactionUUID(transactionId.toString()); message.setMessage(messageText); MessageDao messageDao = new MessageDao(); messageDao.save(message); } } /** * deletes fragments for the survey * * @param surveyId */ private void cleanupFragments(Long surveyId, Long transactionId) { SurveyXMLFragmentDao sxmlfDao = new SurveyXMLFragmentDao(); sxmlfDao.deleteFragmentsForSurvey(surveyId, transactionId); } @Override protected void writeOkResponse(RestResponse resp) throws Exception { HttpServletResponse httpResp = getResponse(); httpResp.setStatus(HttpServletResponse.SC_OK); httpResp.setContentType("text/plain"); httpResp.getWriter().print("OK"); } private void assembleSurveyOnePass(Long surveyId) { /************** * 1, Select survey based on surveyId 2. Retrieve all question groups * fire off queue tasks */ log.info("Starting assembly of "+surveyId); // Swap with proper UUID SurveyDAO surveyDao = new SurveyDAO(); Survey s = surveyDao.getById(surveyId); Long transactionId = new Random().nextLong(); String surveyHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><survey"; String lang = "en"; if (s != null && s.getDefaultLanguageCode() != null) { lang = s.getDefaultLanguageCode(); } surveyHeader += " defaultLanguageCode='" + lang + "'>"; String surveyFooter = "</survey>"; QuestionGroupDao qgDao = new QuestionGroupDao(); TreeMap<Integer, QuestionGroup> qgList = qgDao .listQuestionGroupsBySurvey(surveyId); if (qgList != null) { StringBuilder surveyXML = new StringBuilder(); surveyXML.append(surveyHeader); for (QuestionGroup item : qgList.values()) { log.info("Assembling group "+item.getKey().getId()+" for survey "+surveyId); surveyXML.append(buildQuestionGroupXML(item)); } surveyXML.append(surveyFooter); log.info("Uploading "+surveyId); UploadStatusContainer uc = uploadSurveyXML(surveyId, surveyXML.toString()); Message message = new Message(); message.setActionAbout("surveyAssembly"); message.setObjectId(surveyId); // String messageText = CONSTANTS.surveyPublishOkMessage() + " " // + url; if (uc.getUploadedFile() && uc.getUploadedZip()) { // increment the version so devices know to pick up the changes log.info("Finishing assembly of "+surveyId); surveyDao.incrementVersion(surveyId); String messageText = "Published. Please check: " + uc.getUrl(); message.setShortMessage(messageText); if (qgList != null && qgList.size() > 0) { for (QuestionGroup g : qgList.values()) { if (g.getPath() != null) { message.setObjectTitle(g.getPath()); break; } } } message.setTransactionUUID(transactionId.toString()); MessageDao messageDao = new MessageDao(); messageDao.save(message); } else { // String messageText = // CONSTANTS.surveyPublishErrorMessage(); String messageText = "Failed to publish: " + surveyId + "\n" + uc.getMessage(); message.setTransactionUUID(transactionId.toString()); message.setMessage(messageText); MessageDao messageDao = new MessageDao(); messageDao.save(message); } log.info("Completed onepass aseembly method for "+surveyId); } } public UploadStatusContainer uploadSurveyXML(Long surveyId, String surveyXML) { Properties props = System.getProperties(); String document = surveyXML; Boolean uploadedFile = UploadUtil.sendStringAsFile(surveyId + ".xml", document, props.getProperty(SURVEY_UPLOAD_DIR), props.getProperty(SURVEY_UPLOAD_URL), props.getProperty(S3_ID), props.getProperty(SURVEY_UPLOAD_POLICY), props.getProperty(SURVEY_UPLOAD_SIG), "text/xml"); ByteArrayOutputStream os = ZipUtil.generateZip(document, surveyId + ".xml"); UploadStatusContainer uc = new UploadStatusContainer(); Boolean uploadedZip = UploadUtil.upload(os, surveyId + ".zip", props.getProperty(SURVEY_UPLOAD_DIR), props.getProperty(SURVEY_UPLOAD_URL), props.getProperty(S3_ID), props.getProperty(SURVEY_UPLOAD_POLICY), props.getProperty(SURVEY_UPLOAD_SIG), "application/zip", uc); uc.setUploadedFile(uploadedFile); uc.setUploadedZip(uploadedZip); uc.setUrl(props.getProperty(SURVEY_UPLOAD_URL) + props.getProperty(SURVEY_UPLOAD_DIR) + "/" + surveyId + ".xml"); return uc; } public String buildQuestionGroupXML(QuestionGroup item) { QuestionDao questionDao = new QuestionDao(); QuestionGroupDao questionGroupDao = new QuestionGroupDao(); QuestionGroup group = questionGroupDao.getByKey(item.getKey().getId()); TreeMap<Integer, Question> questionList = questionDao .listQuestionsByQuestionGroup(item.getKey().getId(), true); StringBuilder sb = new StringBuilder("<questionGroup><heading>") .append(StringEscapeUtils.escapeXml(group.getCode())).append( "</heading>"); int count = 0; if (questionList != null) { for (Question q : questionList.values()) { sb.append(marshallQuestion(q)); count++; } } return sb.toString() + "</questionGroup>"; } private void assembleSurvey(Long surveyId) { /************** * 1, Select survey based on surveyId 2. Retrieve all question groups * fire off queue tasks */ QuestionGroupDao qgDao = new QuestionGroupDao(); TreeMap<Integer, QuestionGroup> qgList = qgDao .listQuestionGroupsBySurvey(surveyId); if (qgList != null) { ArrayList<Long> questionGroupIdList = new ArrayList<Long>(); StringBuilder builder = new StringBuilder(); int count = 1; for (QuestionGroup item : qgList.values()) { questionGroupIdList.add(item.getKey().getId()); builder.append(item.getKey().getId()); if (count < qgList.size()) { builder.append(","); } count++; } count = 0; Long transactionId = new Random().nextLong(); sendQueueMessage( SurveyAssemblyRequest.DISPATCH_ASSEMBLE_QUESTION_GROUP, surveyId, builder.toString(), transactionId); } } /** * sends a message to the task queue for survey assembly * * @param action * @param surveyId * @param questionGroups */ private void sendQueueMessage(String action, Long surveyId, String questionGroups, Long transactionId) { Queue surveyAssemblyQueue = QueueFactory.getQueue("surveyAssembly"); TaskOptions task = url("/app_worker/surveyassembly").param("action", action).param("surveyId", surveyId.toString()); if (questionGroups != null) { task.param("questionGroupId", questionGroups); } if (transactionId != null) { task.param("transactionId", transactionId.toString()); } surveyAssemblyQueue.add(task); } private void dispatchAssembleQuestionGroup(Long surveyId, String questionGroupIds, Long transactionId) { boolean isLast = true; String currentId = questionGroupIds; String remainingIds = null; if (questionGroupIds.contains(",")) { isLast = false; currentId = questionGroupIds.substring(0, questionGroupIds.indexOf(",")); remainingIds = questionGroupIds.substring(questionGroupIds .indexOf(",") + 1); } QuestionDao questionDao = new QuestionDao(); QuestionGroupDao questionGroupDao = new QuestionGroupDao(); QuestionGroup group = questionGroupDao.getByKey(Long .parseLong(currentId)); TreeMap<Integer, Question> questionList = questionDao .listQuestionsByQuestionGroup(Long.parseLong(currentId), true); StringBuilder sb = new StringBuilder("<questionGroup><heading>") .append(group.getCode()).append("</heading>"); int count = 0; if (questionList != null) { for (Question q : questionList.values()) { sb.append(marshallQuestion(q)); count++; } } SurveyXMLFragment sxf = new SurveyXMLFragment(); sxf.setSurveyId(surveyId); sxf.setQuestionGroupId(Long.parseLong(currentId)); sxf.setFragmentOrder(group.getOrder()); sxf.setFragment(new Text(sb.append("</questionGroup>").toString())); sxf.setTransactionId(transactionId); sxf.setFragmentType(FRAGMENT_TYPE.QUESTION_GROUP); SurveyXMLFragmentDao sxmlfDao = new SurveyXMLFragmentDao(); sxmlfDao.save(sxf); if (isLast) { // Assemble the fragments sendQueueMessage(SurveyAssemblyRequest.ASSEMBLE_QUESTION_GROUP, surveyId, null, transactionId); } else { sendQueueMessage( SurveyAssemblyRequest.DISPATCH_ASSEMBLE_QUESTION_GROUP, surveyId, remainingIds, transactionId); } } private String marshallQuestion(Question q) { SurveyXMLAdapter sax = new SurveyXMLAdapter(); ObjectFactory objFactory = new ObjectFactory(); com.gallatinsystems.survey.domain.xml.Question qXML = objFactory .createQuestion(); qXML.setId(new String("" + q.getKey().getId() + "")); // ToDo fix qXML.setMandatory("false"); if (q.getText() != null) { com.gallatinsystems.survey.domain.xml.Text t = new com.gallatinsystems.survey.domain.xml.Text(); t.setContent(q.getText()); qXML.setText(t); } List<Help> helpList = new ArrayList<Help>(); // this is here for backward compatibility if (q.getTip() != null) { Help tip = new Help(); com.gallatinsystems.survey.domain.xml.Text t = new com.gallatinsystems.survey.domain.xml.Text(); t.setContent(q.getTip()); tip.setText(t); tip.setType("tip"); if (q.getTip() != null && q.getTip().trim().length() > 0 && !"null".equalsIgnoreCase(q.getTip().trim())) { helpList.add(tip); } } if (q.getQuestionHelpMediaMap() != null) { for (QuestionHelpMedia helpItem : q.getQuestionHelpMediaMap() .values()) { Help tip = new Help(); com.gallatinsystems.survey.domain.xml.Text t = new com.gallatinsystems.survey.domain.xml.Text(); t.setContent(helpItem.getText()); if (helpItem.getType() == QuestionHelpMedia.Type.TEXT) { tip.setType("tip"); } else { tip.setType(helpItem.getType().toString().toLowerCase()); } if (helpItem.getTranslationMap() != null) { List<AltText> translationList = new ArrayList<AltText>(); for (Translation trans : helpItem.getTranslationMap() .values()) { AltText aText = new AltText(); aText.setContent(trans.getText()); aText.setLanguage(trans.getLanguageCode()); aText.setType("translation"); translationList.add(aText); } if (translationList.size() > 0) { tip.setAltText(translationList); } } helpList.add(tip); } } if (helpList.size() > 0) { qXML.setHelp(helpList); } if (q.getValidationRule() != null) { ValidationRule validationRule = objFactory.createValidationRule(); // TODO set validation rule xml // validationRule.setAllowDecimal(value) } qXML.setAltText(formAltText(q.getTranslationMap())); if (q.getType().equals(Question.Type.FREE_TEXT)) { qXML.setType(FREE_QUESTION_TYPE); } else if (q.getType().equals(Question.Type.GEO)) { qXML.setType(GEO_QUESTION_TYPE); } else if (q.getType().equals(Question.Type.NUMBER)) { qXML.setType(FREE_QUESTION_TYPE); ValidationRule vrule = new ValidationRule(); vrule.setValidationType("numeric"); vrule.setSigned("false"); qXML.setValidationRule(vrule); } else if (q.getType().equals(Question.Type.OPTION)) { qXML.setType(OPTION_QUESTION_TYPE); } else if (q.getType().equals(Question.Type.PHOTO)) { qXML.setType(PHOTO_QUESTION_TYPE); } else if (q.getType().equals(Question.Type.VIDEO)) { qXML.setType(VIDEO_QUESTION_TYPE); } else if (q.getType().equals(Question.Type.SCAN)) { qXML.setType(SCAN_QUESTION_TYPE); } else if (q.getType().equals(Question.Type.NAME)) { qXML.setType(FREE_QUESTION_TYPE); ValidationRule vrule = new ValidationRule(); vrule.setValidationType("name"); qXML.setValidationRule(vrule); } else if (q.getType().equals(Question.Type.STRENGTH)) { qXML.setType(STRENGTH_QUESTION_TYPE); } else if (q.getType().equals(Question.Type.DATE)) { qXML.setType(DATE_QUESTION_TYPE); } if (q.getOrder() != null) { qXML.setOrder(q.getOrder().toString()); } if (q.getMandatoryFlag() != null) { qXML.setMandatory(q.getMandatoryFlag().toString()); } Dependency dependency = objFactory.createDependency(); if (q.getDependentQuestionId() != null) { dependency.setQuestion(q.getDependentQuestionId().toString()); dependency.setAnswerValue(q.getDependentQuestionAnswer()); qXML.setDependency(dependency); } if (q.getQuestionOptionMap() != null && q.getQuestionOptionMap().size() > 0) { Options options = objFactory.createOptions(); if (q.getAllowOtherFlag() != null) { options.setAllowOther(q.getAllowOtherFlag().toString()); } if (q.getAllowMultipleFlag() != null) { options.setAllowMultiple(q.getAllowMultipleFlag().toString()); } if (options.getAllowMultiple() == null || "false".equals(options.getAllowMultiple())) { options.setRenderType(PropertyUtil .getProperty(OPTION_RENDER_MODE_PROP)); } ArrayList<Option> optionList = new ArrayList<Option>(); for (QuestionOption qo : q.getQuestionOptionMap().values()) { Option option = objFactory.createOption(); com.gallatinsystems.survey.domain.xml.Text t = new com.gallatinsystems.survey.domain.xml.Text(); t.setContent(qo.getText()); option.addContent(t); option.setValue(qo.getCode() != null ? qo.getCode() : qo .getText()); List<AltText> altTextList = formAltText(qo.getTranslationMap()); if (altTextList != null) { for (AltText alt : altTextList) { option.addContent(alt); } } optionList.add(option); } options.setOption(optionList); qXML.setOptions(options); } if (q.getScoringRules() != null) { Scoring scoring = new Scoring(); for (ScoringRule rule : q.getScoringRules()) { Score score = new Score(); if (scoring.getType() == null) { scoring.setType(rule.getType().toLowerCase()); } score.setRangeHigh(rule.getRangeMax()); score.setRangeLow(rule.getRangeMin()); score.setValue(rule.getValue()); scoring.addScore(score); } if (scoring.getScore() != null && scoring.getScore().size() > 0) { qXML.setScoring(scoring); } } String questionDocument = null; try { questionDocument = sax.marshal(qXML); } catch (JAXBException e) { log.log(Level.SEVERE, "Could not marshal question: " + qXML, e); } questionDocument = questionDocument .replace( "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>", ""); return questionDocument; } private List<AltText> formAltText(Map<String, Translation> translationMap) { List<AltText> altTextList = new ArrayList<AltText>(); if (translationMap != null) { for (Translation lang : translationMap.values()) { AltText alt = new AltText(); alt.setContent(lang.getText()); alt.setType("translation"); alt.setLanguage(lang.getLanguageCode()); altTextList.add(alt); } } return altTextList; } private void assembleQuestionGroups(Long surveyId, Long transactionId) { SurveyXMLFragmentDao sxmlfDao = new SurveyXMLFragmentDao(); List<SurveyXMLFragment> sxmlfList = sxmlfDao.listSurveyFragments( surveyId, SurveyXMLFragment.FRAGMENT_TYPE.QUESTION_GROUP, transactionId); StringBuilder sbQG = new StringBuilder(); for (SurveyXMLFragment item : sxmlfList) { sbQG.append(item.getFragment().getValue()); } StringBuilder completeSurvey = new StringBuilder(); String surveyHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><survey>"; String surveyFooter = "</survey>"; completeSurvey.append(surveyHeader); completeSurvey.append(sbQG.toString()); sbQG = null; completeSurvey.append(surveyFooter); SurveyContainerDao scDao = new SurveyContainerDao(); SurveyContainer sc = scDao.findBySurveyId(surveyId); if (sc == null) { sc = new SurveyContainer(); } sc.setSurveyDocument(new Text(completeSurvey.toString())); sc.setSurveyId(surveyId); scDao.save(sc); sendQueueMessage(SurveyAssemblyRequest.DISTRIBUTE_SURVEY, surveyId, null, transactionId); } }
changed logger to warn level ( and from java.util.logger to log4j)
GAE/src/org/waterforpeople/mapping/app/web/SurveyAssemblyServlet.java
changed logger to warn level ( and from java.util.logger to log4j)
<ide><path>AE/src/org/waterforpeople/mapping/app/web/SurveyAssemblyServlet.java <ide> import java.util.Properties; <ide> import java.util.Random; <ide> import java.util.TreeMap; <del>import java.util.logging.Level; <del>import java.util.logging.Logger; <ide> <ide> import javax.servlet.http.HttpServletRequest; <ide> import javax.servlet.http.HttpServletResponse; <ide> import javax.xml.bind.JAXBException; <ide> <ide> import org.apache.commons.lang.StringEscapeUtils; <add>import org.apache.log4j.Logger; <ide> import org.waterforpeople.mapping.app.web.dto.SurveyAssemblyRequest; <ide> import org.waterforpeople.mapping.dao.SurveyContainerDao; <ide> <ide> * 1, Select survey based on surveyId 2. Retrieve all question groups <ide> * fire off queue tasks <ide> */ <del> log.info("Starting assembly of "+surveyId); <add> log.warn("Starting assembly of "+surveyId); <ide> // Swap with proper UUID <ide> SurveyDAO surveyDao = new SurveyDAO(); <ide> Survey s = surveyDao.getById(surveyId); <ide> StringBuilder surveyXML = new StringBuilder(); <ide> surveyXML.append(surveyHeader); <ide> for (QuestionGroup item : qgList.values()) { <del> log.info("Assembling group "+item.getKey().getId()+" for survey "+surveyId); <add> log.warn("Assembling group "+item.getKey().getId()+" for survey "+surveyId); <ide> surveyXML.append(buildQuestionGroupXML(item)); <ide> } <ide> <ide> surveyXML.append(surveyFooter); <del> log.info("Uploading "+surveyId); <add> log.warn("Uploading "+surveyId); <ide> UploadStatusContainer uc = uploadSurveyXML(surveyId, <ide> surveyXML.toString()); <ide> Message message = new Message(); <ide> // + url; <ide> if (uc.getUploadedFile() && uc.getUploadedZip()) { <ide> // increment the version so devices know to pick up the changes <del> log.info("Finishing assembly of "+surveyId); <add> log.warn("Finishing assembly of "+surveyId); <ide> surveyDao.incrementVersion(surveyId); <ide> String messageText = "Published. Please check: " + uc.getUrl(); <ide> message.setShortMessage(messageText); <ide> MessageDao messageDao = new MessageDao(); <ide> messageDao.save(message); <ide> } <del> log.info("Completed onepass aseembly method for "+surveyId); <add> log.warn("Completed onepass aseembly method for "+surveyId); <ide> } <ide> } <ide> <ide> try { <ide> questionDocument = sax.marshal(qXML); <ide> } catch (JAXBException e) { <del> log.log(Level.SEVERE, "Could not marshal question: " + qXML, e); <add> log.warn("Could not marshal question: " + qXML, e); <ide> } <ide> <ide> questionDocument = questionDocument
JavaScript
apache-2.0
bf9e633c57a2e8cda3c317292b951cb6b1468305
0
cloudera/hue,kawamon/hue,cloudera/hue,kawamon/hue,cloudera/hue,cloudera/hue,cloudera/hue,kawamon/hue,cloudera/hue,kawamon/hue,kawamon/hue,cloudera/hue,cloudera/hue,cloudera/hue,kawamon/hue,cloudera/hue,cloudera/hue,cloudera/hue,kawamon/hue,kawamon/hue,cloudera/hue,cloudera/hue,kawamon/hue,cloudera/hue,kawamon/hue,kawamon/hue,kawamon/hue,cloudera/hue,cloudera/hue,cloudera/hue,kawamon/hue,kawamon/hue,kawamon/hue,kawamon/hue,kawamon/hue,kawamon/hue
// Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. 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. const fs = require('fs'); const exec = require('child_process').exec; const LICENSE = '// Licensed to Cloudera, Inc. under one\n' + '// or more contributor license agreements. See the NOTICE file\n' + '// distributed with this work for additional information\n' + '// regarding copyright ownership. Cloudera, Inc. licenses this file\n' + '// to you under the Apache License, Version 2.0 (the\n' + '// "License"); you may not use this file except in compliance\n' + '// with the License. You may obtain a copy of the License at\n' + '//\n' + '// http://www.apache.org/licenses/LICENSE-2.0\n' + '//\n' + '// Unless required by applicable law or agreed to in writing, software\n' + '// distributed under the License is distributed on an "AS IS" BASIS,\n' + '// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n' + '// See the License for the specific language governing permissions and\n' + '// limitations under the License.\n'; const SQL_STATEMENTS_PARSER_JSDOC = '/**\n' + ' * @param {string} input\n' + ' *\n' + ' * @return {SqlStatementsParserResult}\n' + ' */\n'; const JISON_FOLDER = 'desktop/core/src/desktop/js/parse/jison/'; const TARGET_FOLDER = 'desktop/core/src/desktop/js/parse/'; const parserDefinitions = { globalSearchParser: { sources: ['globalSearchParser.jison'], target: 'globalSearchParser.jison', afterParse: contents => new Promise(resolve => { resolve( LICENSE + contents.replace( 'var globalSearchParser = ', "import SqlParseSupport from 'parse/sqlParseSupport';\n\nvar globalSearchParser = " ) + '\nexport default globalSearchParser;\n' ); }) }, solrFormulaParser: { sources: ['solrFormulaParser.jison'], target: 'solrFormulaParser.jison', afterParse: contents => new Promise(resolve => { resolve(LICENSE + contents + 'export default solrFormulaParser;\n'); }) }, solrQueryParser: { sources: ['solrQueryParser.jison'], target: 'solrQueryParser.jison', afterParse: contents => new Promise(resolve => { resolve(LICENSE + contents + 'export default solrQueryParser;\n'); }) }, sqlStatementsParser: { sources: ['sqlStatementsParser.jison'], target: 'sqlStatementsParser.jison', afterParse: contents => new Promise(resolve => { resolve( LICENSE + contents.replace( 'parse: function parse', SQL_STATEMENTS_PARSER_JSDOC + 'parse: function parse' ) + 'export default sqlStatementsParser;\n' ); }) } }; const readFile = path => new Promise((resolve, reject) => { fs.readFile(path, (err, buf) => { if (err) { reject(); } resolve(buf.toString()); }); }); const writeFile = (path, contents) => new Promise((resolve, reject) => { fs.writeFile(path, contents, err => { if (err) { reject(); } resolve(); }); }); const deleteFile = path => { fs.unlinkSync(path); }; const execCmd = cmd => new Promise((resolve, reject) => { exec(cmd, (err, stdout, stderr) => { if (err) { reject(stderr); } resolve(); }); }); const generateParser = parserName => new Promise((resolve, reject) => { const parserConfig = parserDefinitions[parserName]; const concatPromise = new Promise((resolve, reject) => { if (parserConfig.sources.length > 1 && parserConfig.target) { console.log('Concatenating files...'); const promises = parserConfig.sources.map(fileName => readFile(JISON_FOLDER + fileName)); Promise.all(promises) .then(contents => { writeFile(JISON_FOLDER + parserConfig.target, contents).then(() => { resolve(JISON_FOLDER + parserConfig.target); }); }) .catch(reject); } else if (parserConfig.sources.length === 1) { resolve(JISON_FOLDER + parserConfig.sources[0]); } else { reject('No jison source specified'); } }); concatPromise .then(targetPath => { let jisonCommand = 'jison ' + targetPath; if (parserConfig.lexer) { jisonCommand += ' ' + JISON_FOLDER + parserConfig.lexer; } jisonCommand += ' -m js'; console.log('Generating parser...'); execCmd(jisonCommand) .then(() => { if (parserConfig.sources.length > 1) { deleteFile(targetPath); // Remove concatenated file } console.log('Adjusting JS...'); const generatedJsFileName = parserConfig.target.replace('.jison', '.js'); readFile(generatedJsFileName) .then(contents => { parserConfig .afterParse(contents) .then(finalContents => { writeFile(TARGET_FOLDER + generatedJsFileName, finalContents) .then(() => { deleteFile(generatedJsFileName); console.log('Done!\n'); resolve(); }) .catch(reject); }) .catch(reject); }) .catch(reject); }) .catch(reject); }) .catch(reject); }); let parsersToGenerate = []; const invalid = []; let all = false; let appFound = false; const listDir = folder => new Promise(resolve => { fs.readdir(folder, (err, files) => { resolve(files); }); }); /* sqlSyntaxParser: { sources: [ 'syntax_header.jison', 'sql_main.jison', 'sql_valueExpression.jison', 'sql_alter.jison', 'sql_analyze.jison', 'sql_create.jison', 'sql_drop.jison', 'sql_grant.jison', 'sql_insert.jison', 'sql_load.jison', 'sql_set.jison', 'sql_show.jison', 'sql_update.jison', 'sql_use.jison', 'syntax_footer.jison' ], target: 'sqlSyntaxParser.jison', lexer: 'sql.jisonlex', afterParse: (contents) => new Promise(resolve => { resolve(LICENSE + contents.replace('var sqlSyntaxParser = ', 'import SqlParseSupport from \'parse/sqlParseSupport\';\n\nvar sqlSyntaxParser = ') .replace('loc: yyloc,', 'loc: lexer.yylloc, ruleId: stack.slice(stack.length - 2, stack.length).join(\'\'),') + '\nexport default sqlSyntaxParser;\n'); }) }, */ const findParser = (fileIndex, folder, sharedFiles, autocomplete) => { const prefix = autocomplete ? 'autocomplete' : 'syntax'; if (fileIndex[prefix + '_header.jison'] && fileIndex[prefix + '_footer.jison']) { const parserName = folder + (autocomplete ? 'AutocompleteParser' : 'SyntaxParser'); const parserDefinition = { sources: ['sql/' + folder + '/' + prefix + '_header.jison'].concat(sharedFiles), lexer: 'sql/' + folder + '/sql.jisonlex', target: 'sql/' + folder + '/' + parserName + '.jison', afterParse: contents => new Promise(resolve => { resolve( LICENSE + contents .replace( 'var ' + parserName + ' = ', "import SqlParseSupport from 'parse/sqlParseSupport';\n\nvar " + parserName + ' = ' ) .replace( 'loc: yyloc,', "loc: lexer.yylloc, ruleId: stack.slice(stack.length - 2, stack.length).join('')," ) + '\nexport default ' + parserName + ';\n' ); }) }; parserDefinition.sources.push('sql/' + folder + '/' + prefix + '_footer.jison'); parserDefinitions[parserName] = parserDefinition; } else { console.log( "Warn: Could not find '" + prefix + "_header.jison' or '" + prefix + "_footer.jison' in " + JISON_FOLDER + 'sql/' + folder + '/' ); } }; const identifySqlParsers = () => new Promise(resolve => { listDir(JISON_FOLDER + 'sql').then(files => { const promises = []; files.forEach(folder => { promises.push( listDir(JISON_FOLDER + 'sql/' + folder).then(jisonFiles => { const fileIndex = {}; jisonFiles.forEach(jisonFile => { fileIndex[jisonFile] = true; }); const sharedFiles = jisonFiles .filter(jisonFile => jisonFile.indexOf('sql_') !== -1) .map(jisonFile => 'sql/' + folder + '/' + jisonFile); if (fileIndex['sql.jisonlex']) { findParser(fileIndex, folder, sharedFiles, true); findParser(fileIndex, folder, sharedFiles, false); } else { console.log( "Warn: Could not find 'sql.jisonlex' in " + JISON_FOLDER + 'sql/' + folder + '/' ); } }) ); }); Promise.all(promises).then(resolve); }); }); identifySqlParsers().then(() => { process.argv.forEach(arg => { if (appFound) { if (arg === 'all') { all = true; } else if (parserDefinitions[arg]) { parsersToGenerate.push(arg); } else { invalid.push(arg); } } else if (arg.indexOf('generateParsers.js') !== -1) { appFound = true; } }); if (all) { parsersToGenerate = Object.keys(parserDefinitions); } if (invalid.length) { console.log("No parser config found for: '" + invalid.join("', '") + "'"); console.log( '\nPossible options are:\n ' + ['all'].concat(Object.keys(parserDefinitions)).join('\n ') + '\n' ); return; } const parserCount = parsersToGenerate.length; let idx = 0; const generateRecursive = () => { idx++; if (parsersToGenerate.length) { const parserName = parsersToGenerate.pop(); if (parserCount > 1) { console.log("Generating '" + parserName + "' (" + idx + '/' + parserCount + ')...'); } else { console.log("Generating '" + parserName + "'..."); } generateParser(parserName) .then(generateRecursive) .catch(error => { console.log(error); console.log('FAIL!'); }); } }; generateRecursive(); });
tools/jison/generateParsers.js
// Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. 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. const fs = require('fs'); const exec = require('child_process').exec; const LICENSE = '// Licensed to Cloudera, Inc. under one\n' + '// or more contributor license agreements. See the NOTICE file\n' + '// distributed with this work for additional information\n' + '// regarding copyright ownership. Cloudera, Inc. licenses this file\n' + '// to you under the Apache License, Version 2.0 (the\n' + '// "License"); you may not use this file except in compliance\n' + '// with the License. You may obtain a copy of the License at\n' + '//\n' + '// http://www.apache.org/licenses/LICENSE-2.0\n' + '//\n' + '// Unless required by applicable law or agreed to in writing, software\n' + '// distributed under the License is distributed on an "AS IS" BASIS,\n' + '// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n' + '// See the License for the specific language governing permissions and\n' + '// limitations under the License.\n'; const SQL_STATEMENTS_PARSER_JSDOC = '/**\n' + ' * @param {string} input\n' + ' *\n' + ' * @return {SqlStatementsParserResult}\n' + ' */\n'; const JISON_FOLDER = 'desktop/core/src/desktop/js/parse/jison/'; const TARGET_FOLDER = 'desktop/core/src/desktop/js/parse/'; const PARSERS = { globalSearchParser: { sources: ['globalSearchParser.jison'], target: 'globalSearchParser.jison', afterParse: contents => new Promise(resolve => { resolve( LICENSE + contents.replace( 'var globalSearchParser = ', "import SqlParseSupport from 'parse/sqlParseSupport';\n\nvar globalSearchParser = " ) + '\nexport default globalSearchParser;\n' ); }) }, solrFormulaParser: { sources: ['solrFormulaParser.jison'], target: 'solrFormulaParser.jison', afterParse: contents => new Promise(resolve => { resolve(LICENSE + contents + 'export default solrFormulaParser;\n'); }) }, solrQueryParser: { sources: ['solrQueryParser.jison'], target: 'solrQueryParser.jison', afterParse: contents => new Promise(resolve => { resolve(LICENSE + contents + 'export default solrQueryParser;\n'); }) }, sqlAutocompleteParser: { sources: [ 'autocomplete_header.jison', 'sql_main.jison', 'sql_valueExpression.jison', 'sql_error.jison', 'sql_alter.jison', 'sql_analyze.jison', 'sql_create.jison', 'sql_drop.jison', 'sql_grant.jison', 'sql_insert.jison', 'sql_load.jison', 'sql_set.jison', 'sql_show.jison', 'sql_update.jison', 'sql_use.jison', 'autocomplete_footer.jison' ], target: 'sqlAutocompleteParser.jison', lexer: 'sql.jisonlex', afterParse: contents => new Promise(resolve => { resolve( LICENSE + contents.replace( 'var sqlAutocompleteParser = ', "import SqlParseSupport from 'parse/sqlParseSupport';\n\nvar sqlAutocompleteParser = " ) + '\nexport default sqlAutocompleteParser;\n' ); }) }, sqlStatementsParser: { sources: ['sqlStatementsParser.jison'], target: 'sqlStatementsParser.jison', afterParse: contents => new Promise(resolve => { resolve( LICENSE + contents.replace( 'parse: function parse', SQL_STATEMENTS_PARSER_JSDOC + 'parse: function parse' ) + 'export default sqlStatementsParser;\n' ); }) }, sqlSyntaxParser: { sources: [ 'syntax_header.jison', 'sql_main.jison', 'sql_valueExpression.jison', 'sql_alter.jison', 'sql_analyze.jison', 'sql_create.jison', 'sql_drop.jison', 'sql_grant.jison', 'sql_insert.jison', 'sql_load.jison', 'sql_set.jison', 'sql_show.jison', 'sql_update.jison', 'sql_use.jison', 'syntax_footer.jison' ], target: 'sqlSyntaxParser.jison', lexer: 'sql.jisonlex', afterParse: contents => new Promise(resolve => { resolve( LICENSE + contents .replace( 'var sqlSyntaxParser = ', "import SqlParseSupport from 'parse/sqlParseSupport';\n\nvar sqlSyntaxParser = " ) .replace( 'loc: yyloc,', "loc: lexer.yylloc, ruleId: stack.slice(stack.length - 2, stack.length).join('')," ) + '\nexport default sqlSyntaxParser;\n' ); }) } }; const readFile = path => new Promise((resolve, reject) => { fs.readFile(path, (err, buf) => { if (err) { reject(); } resolve(buf.toString()); }); }); const writeFile = (path, contents) => new Promise((resolve, reject) => { fs.writeFile(path, contents, (err, data) => { if (err) { reject(); } resolve(); }); }); const deleteFile = path => { fs.unlinkSync(path); }; const execCmd = cmd => new Promise((resolve, reject) => { exec(cmd, (err, stdout, stderr) => { if (err) { reject(stderr); } resolve(); }); }); const generateParser = parserName => new Promise((resolve, reject) => { const parserConfig = PARSERS[parserName]; const concatPromise = new Promise((resolve, reject) => { if (parserConfig.sources.length > 1 && parserConfig.target) { console.log('Concatenating files...'); const promises = parserConfig.sources.map(fileName => readFile(JISON_FOLDER + fileName)); Promise.all(promises) .then(contents => { writeFile(JISON_FOLDER + parserConfig.target, contents).then(() => { resolve(JISON_FOLDER + parserConfig.target); }); }) .catch(reject); } else if (parserConfig.sources.length === 1) { resolve(JISON_FOLDER + parserConfig.sources[0]); } else { reject('No jison source specified'); } }); concatPromise .then(targetPath => { let jisonCommand = 'jison ' + targetPath; if (parserConfig.lexer) { jisonCommand += ' ' + JISON_FOLDER + parserConfig.lexer; } jisonCommand += ' -m js'; console.log('Generating parser...'); execCmd(jisonCommand) .then(() => { if (parserConfig.sources.length > 1) { deleteFile(targetPath); // Remove concatenated file } console.log('Adjusting JS...'); const generatedJsFileName = parserConfig.target.replace('.jison', '.js'); readFile(generatedJsFileName) .then(contents => { parserConfig .afterParse(contents) .then(finalContents => { writeFile(TARGET_FOLDER + generatedJsFileName, finalContents) .then(() => { deleteFile(generatedJsFileName); console.log('Done!\n'); resolve(); }) .catch(reject); }) .catch(reject); }) .catch(reject); }) .catch(reject); }) .catch(reject); }); let parsersToGenerate = []; const invalid = []; let all = false; let appFound = false; process.argv.forEach(arg => { if (appFound) { if (arg === 'all') { all = true; } else if (PARSERS[arg]) { parsersToGenerate.push(arg); } else { invalid.push(arg); } } else if (arg.indexOf('generateParsers.js') !== -1) { appFound = true; } }); if (all) { parsersToGenerate = Object.keys(PARSERS); } if (invalid.length) { console.log("No parser config found for: '" + invalid.join("', '") + "'"); console.log( '\nPossible options are:\n ' + ['all'].concat(Object.keys(PARSERS)).join('\n ') + '\n' ); return; } const parserCount = parsersToGenerate.length; let idx = 0; const generateRecursive = () => { idx++; if (parsersToGenerate.length) { const parserName = parsersToGenerate.pop(); if (parserCount > 1) { console.log("Generating '" + parserName + "' (" + idx + '/' + parserCount + ')...'); } else { console.log("Generating '" + parserName + "'..."); } generateParser(parserName) .then(generateRecursive) .catch(error => { console.log(error); console.log('FAIL!'); }); } }; generateRecursive();
HUE-8856 [autocomplete] Have parser generator identify autocomplete and syntax definitions dynamically
tools/jison/generateParsers.js
HUE-8856 [autocomplete] Have parser generator identify autocomplete and syntax definitions dynamically
<ide><path>ools/jison/generateParsers.js <ide> const JISON_FOLDER = 'desktop/core/src/desktop/js/parse/jison/'; <ide> const TARGET_FOLDER = 'desktop/core/src/desktop/js/parse/'; <ide> <del>const PARSERS = { <add>const parserDefinitions = { <ide> globalSearchParser: { <ide> sources: ['globalSearchParser.jison'], <ide> target: 'globalSearchParser.jison', <ide> afterParse: contents => <ide> new Promise(resolve => { <ide> resolve(LICENSE + contents + 'export default solrQueryParser;\n'); <del> }) <del> }, <del> sqlAutocompleteParser: { <del> sources: [ <del> 'autocomplete_header.jison', <del> 'sql_main.jison', <del> 'sql_valueExpression.jison', <del> 'sql_error.jison', <del> 'sql_alter.jison', <del> 'sql_analyze.jison', <del> 'sql_create.jison', <del> 'sql_drop.jison', <del> 'sql_grant.jison', <del> 'sql_insert.jison', <del> 'sql_load.jison', <del> 'sql_set.jison', <del> 'sql_show.jison', <del> 'sql_update.jison', <del> 'sql_use.jison', <del> 'autocomplete_footer.jison' <del> ], <del> target: 'sqlAutocompleteParser.jison', <del> lexer: 'sql.jisonlex', <del> afterParse: contents => <del> new Promise(resolve => { <del> resolve( <del> LICENSE + <del> contents.replace( <del> 'var sqlAutocompleteParser = ', <del> "import SqlParseSupport from 'parse/sqlParseSupport';\n\nvar sqlAutocompleteParser = " <del> ) + <del> '\nexport default sqlAutocompleteParser;\n' <del> ); <ide> }) <ide> }, <ide> sqlStatementsParser: { <ide> 'export default sqlStatementsParser;\n' <ide> ); <ide> }) <del> }, <del> sqlSyntaxParser: { <del> sources: [ <del> 'syntax_header.jison', <del> 'sql_main.jison', <del> 'sql_valueExpression.jison', <del> 'sql_alter.jison', <del> 'sql_analyze.jison', <del> 'sql_create.jison', <del> 'sql_drop.jison', <del> 'sql_grant.jison', <del> 'sql_insert.jison', <del> 'sql_load.jison', <del> 'sql_set.jison', <del> 'sql_show.jison', <del> 'sql_update.jison', <del> 'sql_use.jison', <del> 'syntax_footer.jison' <del> ], <del> target: 'sqlSyntaxParser.jison', <del> lexer: 'sql.jisonlex', <del> afterParse: contents => <del> new Promise(resolve => { <del> resolve( <del> LICENSE + <del> contents <del> .replace( <del> 'var sqlSyntaxParser = ', <del> "import SqlParseSupport from 'parse/sqlParseSupport';\n\nvar sqlSyntaxParser = " <del> ) <del> .replace( <del> 'loc: yyloc,', <del> "loc: lexer.yylloc, ruleId: stack.slice(stack.length - 2, stack.length).join('')," <del> ) + <del> '\nexport default sqlSyntaxParser;\n' <del> ); <del> }) <ide> } <ide> }; <ide> <ide> <ide> const writeFile = (path, contents) => <ide> new Promise((resolve, reject) => { <del> fs.writeFile(path, contents, (err, data) => { <add> fs.writeFile(path, contents, err => { <ide> if (err) { <ide> reject(); <ide> } <ide> <ide> const generateParser = parserName => <ide> new Promise((resolve, reject) => { <del> const parserConfig = PARSERS[parserName]; <add> const parserConfig = parserDefinitions[parserName]; <ide> <ide> const concatPromise = new Promise((resolve, reject) => { <ide> if (parserConfig.sources.length > 1 && parserConfig.target) { <ide> <ide> let all = false; <ide> let appFound = false; <del>process.argv.forEach(arg => { <del> if (appFound) { <del> if (arg === 'all') { <del> all = true; <del> } else if (PARSERS[arg]) { <del> parsersToGenerate.push(arg); <del> } else { <del> invalid.push(arg); <del> } <del> } else if (arg.indexOf('generateParsers.js') !== -1) { <del> appFound = true; <del> } <del>}); <del> <del>if (all) { <del> parsersToGenerate = Object.keys(PARSERS); <del>} <del> <del>if (invalid.length) { <del> console.log("No parser config found for: '" + invalid.join("', '") + "'"); <del> console.log( <del> '\nPossible options are:\n ' + ['all'].concat(Object.keys(PARSERS)).join('\n ') + '\n' <del> ); <del> return; <del>} <del> <del>const parserCount = parsersToGenerate.length; <del>let idx = 0; <del> <del>const generateRecursive = () => { <del> idx++; <del> if (parsersToGenerate.length) { <del> const parserName = parsersToGenerate.pop(); <del> if (parserCount > 1) { <del> console.log("Generating '" + parserName + "' (" + idx + '/' + parserCount + ')...'); <del> } else { <del> console.log("Generating '" + parserName + "'..."); <del> } <del> generateParser(parserName) <del> .then(generateRecursive) <del> .catch(error => { <del> console.log(error); <del> console.log('FAIL!'); <del> }); <add> <add>const listDir = folder => <add> new Promise(resolve => { <add> fs.readdir(folder, (err, files) => { <add> resolve(files); <add> }); <add> }); <add> <add>/* <add>sqlSyntaxParser: { <add> sources: [ <add> 'syntax_header.jison', 'sql_main.jison', 'sql_valueExpression.jison', 'sql_alter.jison', 'sql_analyze.jison', <add> 'sql_create.jison', 'sql_drop.jison', 'sql_grant.jison', 'sql_insert.jison', 'sql_load.jison', 'sql_set.jison', <add> 'sql_show.jison', 'sql_update.jison', 'sql_use.jison', 'syntax_footer.jison' <add> ], <add> target: 'sqlSyntaxParser.jison', <add> lexer: 'sql.jisonlex', <add> afterParse: (contents) => new Promise(resolve => { <add> resolve(LICENSE + <add> contents.replace('var sqlSyntaxParser = ', 'import SqlParseSupport from \'parse/sqlParseSupport\';\n\nvar sqlSyntaxParser = ') <add> .replace('loc: yyloc,', 'loc: lexer.yylloc, ruleId: stack.slice(stack.length - 2, stack.length).join(\'\'),') + <add> '\nexport default sqlSyntaxParser;\n'); <add> }) <add> }, <add> */ <add> <add>const findParser = (fileIndex, folder, sharedFiles, autocomplete) => { <add> const prefix = autocomplete ? 'autocomplete' : 'syntax'; <add> if (fileIndex[prefix + '_header.jison'] && fileIndex[prefix + '_footer.jison']) { <add> const parserName = folder + (autocomplete ? 'AutocompleteParser' : 'SyntaxParser'); <add> const parserDefinition = { <add> sources: ['sql/' + folder + '/' + prefix + '_header.jison'].concat(sharedFiles), <add> lexer: 'sql/' + folder + '/sql.jisonlex', <add> target: 'sql/' + folder + '/' + parserName + '.jison', <add> afterParse: contents => <add> new Promise(resolve => { <add> resolve( <add> LICENSE + <add> contents <add> .replace( <add> 'var ' + parserName + ' = ', <add> "import SqlParseSupport from 'parse/sqlParseSupport';\n\nvar " + <add> parserName + <add> ' = ' <add> ) <add> .replace( <add> 'loc: yyloc,', <add> "loc: lexer.yylloc, ruleId: stack.slice(stack.length - 2, stack.length).join('')," <add> ) + <add> '\nexport default ' + <add> parserName + <add> ';\n' <add> ); <add> }) <add> }; <add> <add> parserDefinition.sources.push('sql/' + folder + '/' + prefix + '_footer.jison'); <add> parserDefinitions[parserName] = parserDefinition; <add> } else { <add> console.log( <add> "Warn: Could not find '" + <add> prefix + <add> "_header.jison' or '" + <add> prefix + <add> "_footer.jison' in " + <add> JISON_FOLDER + <add> 'sql/' + <add> folder + <add> '/' <add> ); <ide> } <ide> }; <ide> <del>generateRecursive(); <add>const identifySqlParsers = () => <add> new Promise(resolve => { <add> listDir(JISON_FOLDER + 'sql').then(files => { <add> const promises = []; <add> files.forEach(folder => { <add> promises.push( <add> listDir(JISON_FOLDER + 'sql/' + folder).then(jisonFiles => { <add> const fileIndex = {}; <add> jisonFiles.forEach(jisonFile => { <add> fileIndex[jisonFile] = true; <add> }); <add> <add> const sharedFiles = jisonFiles <add> .filter(jisonFile => jisonFile.indexOf('sql_') !== -1) <add> .map(jisonFile => 'sql/' + folder + '/' + jisonFile); <add> <add> if (fileIndex['sql.jisonlex']) { <add> findParser(fileIndex, folder, sharedFiles, true); <add> findParser(fileIndex, folder, sharedFiles, false); <add> } else { <add> console.log( <add> "Warn: Could not find 'sql.jisonlex' in " + JISON_FOLDER + 'sql/' + folder + '/' <add> ); <add> } <add> }) <add> ); <add> }); <add> Promise.all(promises).then(resolve); <add> }); <add> }); <add> <add>identifySqlParsers().then(() => { <add> process.argv.forEach(arg => { <add> if (appFound) { <add> if (arg === 'all') { <add> all = true; <add> } else if (parserDefinitions[arg]) { <add> parsersToGenerate.push(arg); <add> } else { <add> invalid.push(arg); <add> } <add> } else if (arg.indexOf('generateParsers.js') !== -1) { <add> appFound = true; <add> } <add> }); <add> <add> if (all) { <add> parsersToGenerate = Object.keys(parserDefinitions); <add> } <add> <add> if (invalid.length) { <add> console.log("No parser config found for: '" + invalid.join("', '") + "'"); <add> console.log( <add> '\nPossible options are:\n ' + <add> ['all'].concat(Object.keys(parserDefinitions)).join('\n ') + <add> '\n' <add> ); <add> return; <add> } <add> <add> const parserCount = parsersToGenerate.length; <add> let idx = 0; <add> <add> const generateRecursive = () => { <add> idx++; <add> if (parsersToGenerate.length) { <add> const parserName = parsersToGenerate.pop(); <add> if (parserCount > 1) { <add> console.log("Generating '" + parserName + "' (" + idx + '/' + parserCount + ')...'); <add> } else { <add> console.log("Generating '" + parserName + "'..."); <add> } <add> generateParser(parserName) <add> .then(generateRecursive) <add> .catch(error => { <add> console.log(error); <add> console.log('FAIL!'); <add> }); <add> } <add> }; <add> <add> generateRecursive(); <add>});
Java
mit
a5c455dc86abedbf8c428eff17ed41826a0ef21d
0
sumit784/java-cookie,js-cookie/java-cookie,sumit784/java-cookie
package org.jscookie.test.integration.encoding; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.jscookie.Cookies; import com.fasterxml.jackson.databind.ObjectMapper; @WebServlet( "/encoding" ) public class EncodingServlet extends HttpServlet { private static final long serialVersionUID = 1; @Override public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { String name = getUTF8Param( "name", request ); System.out.println( "--------------------" ); System.out.println( "Testing: " + name ); Cookies cookies = Cookies.initFromServlet( request, response ); String value = cookies.get( name ); if ( value == null ) { throw new NullPointerException( "Cookie not found with name: " + name ); } System.out.println( "Value: " + value ); System.out.println( "--------------------" ); cookies.set( name, value ); response.setContentType( "application/json" ); new ObjectMapper() .writeValue( response.getOutputStream(), new Result( name, value ) ); } /** * Retrieves the parameter using UTF-8 charset since the server default is ISO-8859-1 */ private String getUTF8Param( String name, HttpServletRequest request ) throws UnsupportedEncodingException { String query = request.getQueryString(); for ( String pair : query.split( "&" ) ) { if ( name.equals( pair.split( "=" )[ 0 ] ) ) { return URLDecoder.decode( pair.split( "=" )[ 1 ], StandardCharsets.UTF_8.name() ); } } return null; } } class Result { private String name; private String value; Result( String name, String value ) { this.name = name; this.value = value; } public String getName() { return name; } public String getValue() { return value; } }
src/test/java/org/jscookie/test/integration/encoding/EncodingServlet.java
package org.jscookie.test.integration.encoding; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.jscookie.Cookies; import com.fasterxml.jackson.databind.ObjectMapper; @WebServlet( "/encoding" ) public class EncodingServlet extends HttpServlet { private static final long serialVersionUID = 1; @Override public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { String name = request.getParameter( "name" ); System.out.println( "--------------------" ); System.out.println( "Testing: " + name ); Cookies cookies = Cookies.initFromServlet( request, response ); String value = cookies.get( name ); if ( value == null ) { throw new NullPointerException( "Cookie not found with name: " + name ); } System.out.println( "Value: " + value ); System.out.println( "--------------------" ); cookies.set( name, value ); response.setContentType( "application/json" ); new ObjectMapper() .writeValue( response.getOutputStream(), new Result( name, value ) ); } } class Result { private String name; private String value; Result( String name, String value ) { this.name = name; this.value = value; } public String getName() { return name; } public String getValue() { return value; } }
Fix the retrieval of UTF-8 characters from the server With this all encoding tests pass for js-cookie, ;D
src/test/java/org/jscookie/test/integration/encoding/EncodingServlet.java
Fix the retrieval of UTF-8 characters from the server
<ide><path>rc/test/java/org/jscookie/test/integration/encoding/EncodingServlet.java <ide> package org.jscookie.test.integration.encoding; <ide> <ide> import java.io.IOException; <add>import java.io.UnsupportedEncodingException; <add>import java.net.URLDecoder; <add>import java.nio.charset.StandardCharsets; <ide> <ide> import javax.servlet.ServletException; <ide> import javax.servlet.annotation.WebServlet; <ide> @Override <ide> public void doGet( HttpServletRequest request, HttpServletResponse response ) <ide> throws ServletException, IOException { <del> String name = request.getParameter( "name" ); <add> String name = getUTF8Param( "name", request ); <ide> <ide> System.out.println( "--------------------" ); <ide> System.out.println( "Testing: " + name ); <ide> new ObjectMapper() <ide> .writeValue( response.getOutputStream(), new Result( name, value ) ); <ide> } <add> <add> /** <add> * Retrieves the parameter using UTF-8 charset since the server default is ISO-8859-1 <add> */ <add> private String getUTF8Param( String name, HttpServletRequest request ) throws UnsupportedEncodingException { <add> String query = request.getQueryString(); <add> for ( String pair : query.split( "&" ) ) { <add> if ( name.equals( pair.split( "=" )[ 0 ] ) ) { <add> return URLDecoder.decode( pair.split( "=" )[ 1 ], StandardCharsets.UTF_8.name() ); <add> } <add> } <add> return null; <add> } <ide> } <ide> <ide> class Result {
Java
apache-2.0
5d2d969d520477f0a0e71bbc527de2f8f69879b2
0
apache/jena,apache/jena,apache/jena,apache/jena,apache/jena,apache/jena,apache/jena,apache/jena
/* * 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.jena.vocabulary; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.rdf.model.Property ; import org.apache.jena.rdf.model.Resource ; public class ACL { /** Basic Access Control ontology. */ private static final Model m = ModelFactory.createDefaultModel(); public static final String NS = "http://www.w3.org/ns/auth/acl#"; public static final Resource APPEND = m.createResource(NS+"Append"); public static final Resource WRITE = m.createResource(NS+"Write"); public static final Resource CONTROL = m.createResource(NS+"Control"); public static final Resource ACCESS = m.createResource(NS+"Access"); public static final Resource AUTHORIZATION = m.createResource(NS+"Authorization"); public static final Resource AUTHENTICATEDAGENT = m.createResource(NS+"AuthenticatedAgent"); public static final Resource ORIGIN = m.createResource(NS+"Origin"); public static final Resource READ = m.createResource(NS+"Read"); public static final Property accessControl = m.createProperty(NS+"accessControl"); public static final Property accessTo = m.createProperty(NS+"accessTo"); public static final Property delegates = m.createProperty(NS+"delegates"); public static final Property mode = m.createProperty(NS+"mode"); public static final Property agentClass = m.createProperty(NS+"agentClass"); public static final Property origin = m.createProperty(NS+"origin"); public static final Property _default = m.createProperty(NS+"_default"); public static final Property agent = m.createProperty(NS+"agent"); public static final Property agentGroup = m.createProperty(NS+"agentGroup"); public static final Property accessToClass = m.createProperty(NS+"accessToClass"); public static final Property defaultForNew = m.createProperty(NS+"defaultForNew"); public static final Property owner = m.createProperty(NS+"owner"); }
jena-core/src/main/java/org/apache/jena/vocabulary/ACL.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.jena.vocabulary; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.rdf.model.Property ; import org.apache.jena.rdf.model.Resource ; public class ACL { /** Basic Access Control ontology. */ private static final Model m = ModelFactory.createDefaultModel(); public static final String NS = "http://www.w3.org/ns/auth/acl#"; public static Resource APPEND = m.createResource(NS+"Append"); public static Resource WRITE = m.createResource(NS+"Write"); public static Resource CONTROL = m.createResource(NS+"Control"); public static Resource ACCESS = m.createResource(NS+"Access"); public static Resource AUTHORIZATION = m.createResource(NS+"Authorization"); public static Resource AUTHENTICATEDAGENT = m.createResource(NS+"AuthenticatedAgent"); public static Resource ORIGIN = m.createResource(NS+"Origin"); public static Resource READ = m.createResource(NS+"Read"); public static final Property accessControl = m.createProperty(NS+"accessControl"); public static final Property accessTo = m.createProperty(NS+"accessTo"); public static final Property delegates = m.createProperty(NS+"delegates"); public static final Property mode = m.createProperty(NS+"mode"); public static final Property agentClass = m.createProperty(NS+"agentClass"); public static final Property origin = m.createProperty(NS+"origin"); public static final Property _default = m.createProperty(NS+"_default"); public static final Property agent = m.createProperty(NS+"agent"); public static final Property agentGroup = m.createProperty(NS+"agentGroup"); public static final Property accessToClass = m.createProperty(NS+"accessToClass"); public static final Property defaultForNew = m.createProperty(NS+"defaultForNew"); public static final Property owner = m.createProperty(NS+"owner"); }
add final to Resources.
jena-core/src/main/java/org/apache/jena/vocabulary/ACL.java
add final to Resources.
<ide><path>ena-core/src/main/java/org/apache/jena/vocabulary/ACL.java <ide> */ private static final Model m = ModelFactory.createDefaultModel(); <ide> public static final String NS = "http://www.w3.org/ns/auth/acl#"; <ide> <del> public static Resource APPEND = m.createResource(NS+"Append"); <del> public static Resource WRITE = m.createResource(NS+"Write"); <del> public static Resource CONTROL = m.createResource(NS+"Control"); <del> public static Resource ACCESS = m.createResource(NS+"Access"); <del> public static Resource AUTHORIZATION = m.createResource(NS+"Authorization"); <del> public static Resource AUTHENTICATEDAGENT = m.createResource(NS+"AuthenticatedAgent"); <del> public static Resource ORIGIN = m.createResource(NS+"Origin"); <del> public static Resource READ = m.createResource(NS+"Read"); <add> public static final Resource APPEND = m.createResource(NS+"Append"); <add> public static final Resource WRITE = m.createResource(NS+"Write"); <add> public static final Resource CONTROL = m.createResource(NS+"Control"); <add> public static final Resource ACCESS = m.createResource(NS+"Access"); <add> public static final Resource AUTHORIZATION = m.createResource(NS+"Authorization"); <add> public static final Resource AUTHENTICATEDAGENT = m.createResource(NS+"AuthenticatedAgent"); <add> public static final Resource ORIGIN = m.createResource(NS+"Origin"); <add> public static final Resource READ = m.createResource(NS+"Read"); <ide> public static final Property accessControl = m.createProperty(NS+"accessControl"); <ide> public static final Property accessTo = m.createProperty(NS+"accessTo"); <ide> public static final Property delegates = m.createProperty(NS+"delegates");
Java
apache-2.0
30f9aa3452036923f9368e88f27a63f40819ebdf
0
geisterfurz007/JavaBot,Unihedro/JavaBot,Vogel612/JavaBot
package com.gmail.inverseconduit.bot; import java.io.IOException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.gmail.inverseconduit.AppContext; import com.gmail.inverseconduit.BotConfig; import com.gmail.inverseconduit.SESite; import com.gmail.inverseconduit.chat.ChatInterface; import com.gmail.inverseconduit.chat.StackExchangeChat; import com.gmail.inverseconduit.chat.commands.ChatCommands; import com.gmail.inverseconduit.commands.CommandHandle; import com.gmail.inverseconduit.datatype.SeChatDescriptor; import com.gmail.inverseconduit.javadoc.JavaDocAccessor; import com.gmail.inverseconduit.scripts.ScriptRunner; import com.gmail.inverseconduit.scripts.ScriptRunnerCommands; /** * Class to contain the program, to be started from main. This class is * responsible for glueing all the components together. * * @author vogel612<<a href="[email protected]">[email protected]</a>> */ @SuppressWarnings("deprecation") public class Program { private static final Logger LOGGER = Logger.getLogger(Program.class.getName()); private static final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); private static final BotConfig config = AppContext.INSTANCE.get(BotConfig.class); private final DefaultBot bot; private final ChatInterface chatInterface; private final ScriptRunner scriptRunner; private final JavaDocAccessor javaDocAccessor; private static final Pattern javadocPattern = Pattern.compile("^" + Pattern.quote(config.getTrigger()) + "javadoc:(.*)", Pattern.DOTALL); /** * @throws IOException * if there's a problem loading the Javadocs */ public Program() throws IOException { LOGGER.finest("Instantiating Program"); chatInterface = new StackExchangeChat(); bot = new DefaultBot(); chatInterface.subscribe(bot); javaDocAccessor = new JavaDocAccessor(chatInterface, config.getJavadocsDir()); scriptRunner = new ScriptRunner(chatInterface); LOGGER.info("Basic component setup complete"); } /** * This is where the beef happens. Glue all the stuff together here */ public void startup() { LOGGER.info("Beginning startup process"); bindDefaultCommands(); login(); for (Integer room : config.getRooms()) { chatInterface.joinChat(new SeChatDescriptor.DescriptorBuilder(SESite.STACK_OVERFLOW).setRoom(() -> room).build()); } scheduleQueryingThread(); bot.start(); LOGGER.info("Startup completed."); } private void scheduleQueryingThread() { executor.scheduleAtFixedRate(() -> { try { chatInterface.queryMessages(); } catch(RuntimeException | Error e) { Logger.getAnonymousLogger().log(Level.SEVERE, "Throwable occurred in querying thread: " + e.getMessage(), e); throw e; } catch(Exception e) { Logger.getAnonymousLogger().log(Level.WARNING, "Exception occured in querying thread: " + e.getMessage(), e); } }, 5, 3, TimeUnit.SECONDS); Logger.getAnonymousLogger().info("querying thread started"); } private void login() { boolean loggedIn = chatInterface.login(SESite.STACK_OVERFLOW, config); if ( !loggedIn) { Logger.getAnonymousLogger().severe("Login failed!"); System.exit(2); } } private void bindDefaultCommands() { bindHelpCommand(); bindShutdownCommand(); bindEvalCommand(); bindLoadCommand(); bindJavaDocCommand(); bindTestCommand(); bindSummonCommand(); bindUnsummonCommand(); } private void bindUnsummonCommand() { CommandHandle unsummon = ChatCommands.unsummonCommand(chatInterface); bot.subscribe(unsummon); } private void bindSummonCommand() { CommandHandle summon = ChatCommands.summonCommand(chatInterface); bot.subscribe(summon); } private void bindEvalCommand() { CommandHandle eval = ScriptRunnerCommands.evalCommand(scriptRunner); bot.subscribe(eval); } private void bindLoadCommand() { CommandHandle load = ScriptRunnerCommands.loadCommand(scriptRunner); bot.subscribe(load); } private void bindHelpCommand() { CommandHandle help = new CommandHandle.Builder( "help", s -> { return s.trim().startsWith(config.getTrigger() + "help"); }, message -> { chatInterface.sendMessage(SeChatDescriptor.buildSeChatDescriptorFrom(message), String.format("@%s I am JavaBot, maintained by Uni, Vogel, and a few others. You can find me on http://github.com/Vincentyification/JavaBot", message.getUsername())); }).build(); bot.subscribe(help); } private void bindJavaDocCommand() { CommandHandle javaDoc = new CommandHandle.Builder("javadoc", javadocPattern.asPredicate(), message -> { Matcher matcher = javadocPattern.matcher(message.getMessage()); matcher.find(); javaDocAccessor.javadoc(message, matcher.group(1).trim()); }).build(); bot.subscribe(javaDoc); } private void bindShutdownCommand() { CommandHandle shutdown = new CommandHandle.Builder("shutdown", s -> { return s.trim().startsWith(config.getTrigger() + "shutdown"); }, message -> { //FIXME: Require permissions for this chatInterface.broadcast("*~going down*"); executor.shutdownNow(); System.exit(0); }).build(); bot.subscribe(shutdown); } private void bindTestCommand() { CommandHandle test = new CommandHandle.Builder("test", s -> s.equals("test"), message -> { chatInterface.sendMessage(SeChatDescriptor.buildSeChatDescriptorFrom(message), "*~response*"); }).build(); bot.subscribe(test); } }
src/main/java/com/gmail/inverseconduit/bot/Program.java
package com.gmail.inverseconduit.bot; import java.io.IOException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.gmail.inverseconduit.AppContext; import com.gmail.inverseconduit.BotConfig; import com.gmail.inverseconduit.SESite; import com.gmail.inverseconduit.chat.ChatInterface; import com.gmail.inverseconduit.chat.StackExchangeChat; import com.gmail.inverseconduit.chat.commands.ChatCommands; import com.gmail.inverseconduit.commands.CommandHandle; import com.gmail.inverseconduit.datatype.SeChatDescriptor; import com.gmail.inverseconduit.javadoc.JavaDocAccessor; import com.gmail.inverseconduit.scripts.ScriptRunner; import com.gmail.inverseconduit.scripts.ScriptRunnerCommands; /** * Class to contain the program, to be started from main. This class is * responsible for glueing all the components together. * * @author vogel612<<a href="[email protected]">[email protected]</a>> */ @SuppressWarnings("deprecation") public class Program { private static final Logger LOGGER = Logger.getLogger(Program.class.getName()); private static final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); private static final BotConfig config = AppContext.INSTANCE.get(BotConfig.class); private final DefaultBot bot; private final ChatInterface chatInterface; private final ScriptRunner scriptRunner; private final JavaDocAccessor javaDocAccessor; private static final Pattern javadocPattern = Pattern.compile("^" + Pattern.quote(config.getTrigger()) + "javadoc:(.*)", Pattern.DOTALL); /** * @throws IOException * if there's a problem loading the Javadocs */ public Program() throws IOException { LOGGER.finest("Instantiating Program"); chatInterface = new StackExchangeChat(); bot = new DefaultBot(); chatInterface.subscribe(bot); javaDocAccessor = new JavaDocAccessor(chatInterface, config.getJavadocsDir()); scriptRunner = new ScriptRunner(chatInterface); LOGGER.info("Basic component setup complete"); } /** * This is where the beef happens. Glue all the stuff together here */ public void startup() { LOGGER.info("Beginning startup process"); bindDefaultCommands(); login(); for (Integer room : config.getRooms()) { chatInterface.joinChat(new SeChatDescriptor.DescriptorBuilder(SESite.STACK_OVERFLOW).setRoom(() -> room).build()); } scheduleQueryingThread(); bot.start(); LOGGER.info("Startup completed."); } private void scheduleQueryingThread() { executor.scheduleAtFixedRate(() -> { try { chatInterface.queryMessages(); } catch(Throwable e) { Logger.getAnonymousLogger().severe("Throwable occurred in querying thread: " + e.getMessage()); e.printStackTrace(); } }, 5, 3, TimeUnit.SECONDS); Logger.getAnonymousLogger().info("querying thread started"); } private void login() { boolean loggedIn = chatInterface.login(SESite.STACK_OVERFLOW, config); if ( !loggedIn) { Logger.getAnonymousLogger().severe("Login failed!"); System.exit(2); } } private void bindDefaultCommands() { bindHelpCommand(); bindShutdownCommand(); bindEvalCommand(); bindLoadCommand(); bindJavaDocCommand(); bindTestCommand(); bindSummonCommand(); bindUnsummonCommand(); } private void bindUnsummonCommand() { CommandHandle unsummon = ChatCommands.unsummonCommand(chatInterface); bot.subscribe(unsummon); } private void bindSummonCommand() { CommandHandle summon = ChatCommands.summonCommand(chatInterface); bot.subscribe(summon); } private void bindEvalCommand() { CommandHandle eval = ScriptRunnerCommands.evalCommand(scriptRunner); bot.subscribe(eval); } private void bindLoadCommand() { CommandHandle load = ScriptRunnerCommands.loadCommand(scriptRunner); bot.subscribe(load); } private void bindHelpCommand() { CommandHandle help = new CommandHandle.Builder( "help", s -> { return s.trim().startsWith(config.getTrigger() + "help"); }, message -> { chatInterface.sendMessage(SeChatDescriptor.buildSeChatDescriptorFrom(message), String.format("@%s I am JavaBot, maintained by Uni, Vogel, and a few others. You can find me on http://github.com/Vincentyification/JavaBot", message.getUsername())); }).build(); bot.subscribe(help); } private void bindJavaDocCommand() { CommandHandle javaDoc = new CommandHandle.Builder("javadoc", javadocPattern.asPredicate(), message -> { Matcher matcher = javadocPattern.matcher(message.getMessage()); matcher.find(); javaDocAccessor.javadoc(message, matcher.group(1).trim()); }).build(); bot.subscribe(javaDoc); } private void bindShutdownCommand() { CommandHandle shutdown = new CommandHandle.Builder("shutdown", s -> { return s.trim().startsWith(config.getTrigger() + "shutdown"); }, message -> { //FIXME: Require permissions for this chatInterface.broadcast("*~going down*"); executor.shutdownNow(); System.exit(0); }).build(); bot.subscribe(shutdown); } private void bindTestCommand() { CommandHandle test = new CommandHandle.Builder("test", s -> s.equals("test"), message -> { chatInterface.sendMessage(SeChatDescriptor.buildSeChatDescriptorFrom(message), "*~response*"); }).build(); bot.subscribe(test); } }
Corrected the throwable catching to a more sane approach concerning errors and RuntimeExceptions
src/main/java/com/gmail/inverseconduit/bot/Program.java
Corrected the throwable catching to a more sane approach concerning errors and RuntimeExceptions
<ide><path>rc/main/java/com/gmail/inverseconduit/bot/Program.java <ide> import java.util.concurrent.Executors; <ide> import java.util.concurrent.ScheduledExecutorService; <ide> import java.util.concurrent.TimeUnit; <add>import java.util.logging.Level; <ide> import java.util.logging.Logger; <ide> import java.util.regex.Matcher; <ide> import java.util.regex.Pattern; <ide> executor.scheduleAtFixedRate(() -> { <ide> try { <ide> chatInterface.queryMessages(); <del> } catch(Throwable e) { <del> Logger.getAnonymousLogger().severe("Throwable occurred in querying thread: " + e.getMessage()); <del> e.printStackTrace(); <add> } catch(RuntimeException | Error e) { <add> Logger.getAnonymousLogger().log(Level.SEVERE, "Throwable occurred in querying thread: " + e.getMessage(), e); <add> throw e; <add> } catch(Exception e) { <add> Logger.getAnonymousLogger().log(Level.WARNING, "Exception occured in querying thread: " + e.getMessage(), e); <ide> } <ide> }, 5, 3, TimeUnit.SECONDS); <ide> Logger.getAnonymousLogger().info("querying thread started");
Java
bsd-3-clause
d875d2a0f19b9ec3f078df7dbd8c30260437965c
0
vivo-project/VIVO,vivo-project/VIVO,vivo-project/VIVO,vivo-project/VIVO
/* $This file is distributed under the terms of the license in /doc/license.txt$ */ package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.hp.hpl.jena.rdf.model.Literal; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.RDFS; import com.hp.hpl.jena.vocabulary.XSD; import edu.cornell.mannlib.vitro.webapp.beans.Individual; import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty; import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatement; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder; import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationUtils; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.FieldVTwo; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.AddAssociatedConceptsPreprocessor; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation; import edu.cornell.mannlib.vitro.webapp.utils.ConceptSearchService.ConceptSearchServiceUtils; /** * Generates the edit configuration for importing concepts from external * search services, e.g. UMLS etc. * * The N3 for this is set with the default settinf of * */ public class AddAssociatedConceptGenerator extends VivoBaseGenerator implements EditConfigurationGenerator { private Log log = LogFactory.getLog(AddAssociatedConceptGenerator.class); private String template = "addAssociatedConcept.ftl"; private static String SKOSConceptType = "http://www.w3.org/2004/02/skos/core#Concept"; @Override public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq, HttpSession session) { EditConfigurationVTwo editConfiguration = new EditConfigurationVTwo(); initBasics(editConfiguration, vreq); initPropertyParameters(vreq, session, editConfiguration); initObjectPropForm(editConfiguration, vreq); editConfiguration.setTemplate(template); setVarNames(editConfiguration); // Assumes this is a simple case of subject predicate var editConfiguration.setN3Required(this.generateN3Required(vreq)); // n3 optional editConfiguration.setN3Optional(this.generateN3Optional()); // Todo: what do new resources depend on here? // In original form, these variables start off empty editConfiguration.setNewResources(generateNewResources(vreq)); // In scope this.setUrisAndLiteralsInScope(editConfiguration, vreq); // on Form this.setUrisAndLiteralsOnForm(editConfiguration, vreq); editConfiguration.setFilesOnForm(new ArrayList<String>()); // Sparql queries this.setSparqlQueries(editConfiguration, vreq); // set fields setFields(editConfiguration, vreq, EditConfigurationUtils .getPredicateUri(vreq)); setTemplate(editConfiguration, vreq); // No validators required here // Add preprocessors addPreprocessors(editConfiguration, vreq.getWebappDaoFactory()); // Adding additional data, specifically edit mode addFormSpecificData(editConfiguration, vreq); // One override for basic functionality, changing url pattern // and entity // Adding term should return to this same page, not the subject // Return takes the page back to the individual form editConfiguration.setUrlPatternToReturnTo(EditConfigurationUtils .getFormUrlWithoutContext(vreq)); editConfiguration.addValidator(new AntiXssValidation()); // prepare prepare(vreq, editConfiguration); return editConfiguration; } //In this case, the generator is not equipped to handle any deletion //Editing in the usual sense does not exist for this form //So we will disable editing @Override void initObjectPropForm(EditConfigurationVTwo editConfiguration,VitroRequest vreq) { editConfiguration.setObject( null ); } //Ensuring that editing property logic does not get executed on processing //since form's deletions are handled separately @Override void prepare(VitroRequest vreq, EditConfigurationVTwo editConfig) { Model model = vreq.getJenaOntModel(); //Set subject and predicate uri if( editConfig.getSubjectUri() == null) editConfig.setSubjectUri( EditConfigurationUtils.getSubjectUri(vreq)); if( editConfig.getPredicateUri() == null ) editConfig.setPredicateUri( EditConfigurationUtils.getPredicateUri(vreq)); //Always set creation editConfig.prepareForNonUpdate(model); } private void setVarNames(EditConfigurationVTwo editConfiguration) { editConfiguration.setVarNameForSubject("subject"); editConfiguration.setVarNameForPredicate("predicate"); //We are not including concept node here since //we never actually "edit" using this form //the n3 required and optional will still be evaluated based on the form editConfiguration.setVarNameForObject("object"); } protected void setTemplate(EditConfigurationVTwo editConfiguration, VitroRequest vreq) { editConfiguration.setTemplate(template); } /* * N3 Required and Optional Generators as well as supporting methods */ private String getPrefixesString() { //TODO: Include dynamic way of including this return "@prefix core: <http://vivoweb.org/ontology/core#> ."; } //The only string always required is that linking the subject to the concept node //Since the concept node from an external vocabulary may already be in the system //The label and is defined by may already be defined and don't require re-saving private List<String> generateN3Required(VitroRequest vreq) { List<String> n3Required = list( getPrefixesString() + "\n" + "?subject ?predicate ?conceptNode .\n" + "?conceptNode <" + RDF.type.getURI() + "> <http://www.w3.org/2002/07/owl#Thing> ." ); List<String> inversePredicate = getInversePredicate(vreq); //Adding inverse predicate if it exists if(inversePredicate.size() > 0) { n3Required.add("?conceptNode <" + inversePredicate.get(0) + "> ?subject ."); } return n3Required; } //Don't think there's any n3 optional here private List<String> generateN3Optional() { return list("?conceptNode <" + RDFS.label.getURI() + "> ?conceptLabel .\n" + "?conceptNode <" + RDFS.isDefinedBy.getURI() + "> ?conceptSource ." ); } /* * Get new resources */ private Map<String, String> generateNewResources(VitroRequest vreq) { HashMap<String, String> newResources = new HashMap<String, String>(); //There are no new resources here, the concept node uri doesn't //get created but already exists, and vocab uri should already exist as well return newResources; } /* * Set URIS and Literals In Scope and on form and supporting methods */ private void setUrisAndLiteralsInScope(EditConfigurationVTwo editConfiguration, VitroRequest vreq) { HashMap<String, List<String>> urisInScope = new HashMap<String, List<String>>(); //note that at this point the subject, predicate, and object var parameters have already been processed //these two were always set when instantiating an edit configuration object from json, //although the json itself did not specify subject/predicate as part of uris in scope urisInScope.put(editConfiguration.getVarNameForSubject(), Arrays.asList(new String[]{editConfiguration.getSubjectUri()})); urisInScope.put(editConfiguration.getVarNameForPredicate(), Arrays.asList(new String[]{editConfiguration.getPredicateUri()})); //Setting inverse role predicate urisInScope.put("inverseRolePredicate", getInversePredicate(vreq)); editConfiguration.setUrisInScope(urisInScope); //Uris in scope include subject, predicate, and object var //literals in scope empty initially, usually populated by code in prepare for update //with existing values for variables editConfiguration.setLiteralsInScope(new HashMap<String, List<Literal>>()); } private List<String> getInversePredicate(VitroRequest vreq) { List<String> inversePredicateArray = new ArrayList<String>(); ObjectProperty op = EditConfigurationUtils.getObjectProperty(vreq); if(op != null && op.getURIInverse() != null) { inversePredicateArray.add(op.getURIInverse()); } return inversePredicateArray; } //n3 should look as follows //?subject ?predicate ?objectVar private void setUrisAndLiteralsOnForm(EditConfigurationVTwo editConfiguration, VitroRequest vreq) { List<String> urisOnForm = new ArrayList<String>(); List<String> literalsOnForm = new ArrayList<String>(); //The URI of the node that defines the concept urisOnForm.add("conceptNode"); urisOnForm.add("conceptSource"); editConfiguration.setUrisOnform(urisOnForm); //Also need to add the label of the concept literalsOnForm.add("conceptLabel"); editConfiguration.setLiteralsOnForm(literalsOnForm); } /** * Set SPARQL Queries and supporting methods */ private void setSparqlQueries(EditConfigurationVTwo editConfiguration, VitroRequest vreq) { //Sparql queries defining retrieval of literals etc. editConfiguration.setSparqlForAdditionalLiteralsInScope(new HashMap<String, String>()); editConfiguration.setSparqlForAdditionalUrisInScope(new HashMap<String, String>()); editConfiguration.setSparqlForExistingLiterals(new HashMap<String, String>()); editConfiguration.setSparqlForExistingUris(new HashMap<String, String>()); } /** * * Set Fields and supporting methods */ private void setFields(EditConfigurationVTwo editConfiguration, VitroRequest vreq, String predicateUri) { setConceptNodeField(editConfiguration, vreq); setConceptLabelField(editConfiguration, vreq); setVocabURIField(editConfiguration, vreq); } //this field will be hidden and include the concept node URI private void setConceptNodeField(EditConfigurationVTwo editConfiguration, VitroRequest vreq) { editConfiguration.addField(new FieldVTwo(). setName("conceptNode"). setValidators(list("nonempty")). setOptionsType("UNDEFINED")); } private void setVocabURIField(EditConfigurationVTwo editConfiguration, VitroRequest vreq) { editConfiguration.addField(new FieldVTwo(). setName("conceptSource")); } private void setConceptLabelField(EditConfigurationVTwo editConfiguration, VitroRequest vreq) { editConfiguration.addField(new FieldVTwo(). setName("conceptLabel"). setRangeDatatypeUri(XSD.xstring.toString()) ); } //Add preprocessor private void addPreprocessors(EditConfigurationVTwo editConfiguration, WebappDaoFactory wadf) { //An Edit submission preprocessor for enabling addition of multiple terms for a single search editConfiguration.addEditSubmissionPreprocessor( new AddAssociatedConceptsPreprocessor(editConfiguration)); } //Form specific data public void addFormSpecificData(EditConfigurationVTwo editConfiguration, VitroRequest vreq) { HashMap<String, Object> formSpecificData = new HashMap<String, Object>(); //These are the concepts that already exist currently formSpecificData.put("existingConcepts", getExistingConcepts(vreq)); //Return url for adding user defined concept formSpecificData.put("userDefinedConceptUrl", getUserDefinedConceptUrl(vreq)); //Add URIs and labels for different services formSpecificData.put("searchServices", ConceptSearchServiceUtils.getVocabSources()); List<String> inversePredicate = getInversePredicate(vreq); if(inversePredicate.size() > 0) { formSpecificData.put("inversePredicate", inversePredicate.get(0)); } else { formSpecificData.put("inversePredicate", ""); } editConfiguration.setFormSpecificData(formSpecificData); } // private Object getUserDefinedConceptUrl(VitroRequest vreq) { String subjectUri = EditConfigurationUtils.getSubjectUri(vreq); String predicateUri = EditConfigurationUtils.getPredicateUri(vreq); String generatorName = "edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.AddUserDefinedConceptGenerator"; String editUrl = EditConfigurationUtils.getEditUrl(vreq); return editUrl + "?subjectUri=" + UrlBuilder.urlEncode(subjectUri) + "&predicateUri=" + UrlBuilder.urlEncode(predicateUri) + "&editForm=" + UrlBuilder.urlEncode(generatorName); } private List<AssociatedConceptInfo> getExistingConcepts(VitroRequest vreq) { Individual individual = EditConfigurationUtils.getSubjectIndividual(vreq); List<Individual> concepts = individual.getRelatedIndividuals( EditConfigurationUtils.getPredicateUri(vreq)); List<AssociatedConceptInfo> associatedConcepts = getAssociatedConceptInfo(concepts, vreq); sortConcepts(associatedConcepts); return associatedConcepts; } private void sortConcepts(List<AssociatedConceptInfo> concepts) { Collections.sort(concepts, new AssociatedConceptInfoComparator()); log.debug("Concepts should be sorted now" + concepts.toString()); } private List<AssociatedConceptInfo> getAssociatedConceptInfo( List<Individual> concepts, VitroRequest vreq) { List<AssociatedConceptInfo> info = new ArrayList<AssociatedConceptInfo>(); for ( Individual conceptIndividual : concepts ) { boolean isSKOSConcept = false; String conceptUri = conceptIndividual.getURI(); String conceptLabel = conceptIndividual.getName(); //Check if SKOS Concept type List<ObjectPropertyStatement> osl = conceptIndividual.getObjectPropertyStatements(RDF.type.getURI()); for(ObjectPropertyStatement os: osl) { if(os.getObjectURI().equals(SKOSConceptType)) { isSKOSConcept = true; break; } } if(isSKOSConcept) { info.add(new AssociatedConceptInfo(conceptLabel, conceptUri, null, null, SKOSConceptType)); } else { //Get the vocab source and vocab label List<ObjectPropertyStatement> vocabList = conceptIndividual.getObjectPropertyStatements(RDFS.isDefinedBy.getURI()); String vocabSource = null; String vocabLabel = null; if(vocabList != null && vocabList.size() > 0) { vocabSource = vocabList.get(0).getObjectURI(); Individual sourceIndividual = EditConfigurationUtils.getIndividual(vreq, vocabSource); //Assuming name will get label vocabLabel = sourceIndividual.getName(); } info.add(new AssociatedConceptInfo(conceptLabel, conceptUri, vocabSource, vocabLabel, null)); } } return info; } public class AssociatedConceptInfo { private String conceptLabel; private String conceptURI; private String vocabURI; private String vocabLabel; private String type; //In case of SKOS concept, will have skos concept type public AssociatedConceptInfo(String inputLabel, String inputURI, String inputVocabURI, String inputVocabLabel, String inputType) { this.conceptLabel = inputLabel; this.conceptURI = inputURI; this.vocabURI = inputVocabURI; this.vocabLabel = inputVocabLabel; this.type = inputType; } //Getters public String getConceptLabel() { return conceptLabel; } public String getConceptURI() { return conceptURI; } public String getVocabURI() { return vocabURI; } public String getVocabLabel(){ return vocabLabel; } public String getType(){ return type; } } public class AssociatedConceptInfoComparator implements Comparator<AssociatedConceptInfo>{ public int compare(AssociatedConceptInfo concept1, AssociatedConceptInfo concept2) { String concept1Label = concept1.getConceptLabel().toLowerCase(); String concept2Label = concept2.getConceptLabel().toLowerCase(); return concept1Label.compareTo(concept2Label); } } }
src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddAssociatedConceptGenerator.java
/* Copyright (c) 2012, Cornell University 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 Cornell University nor the names of its 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 HOLDER 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 edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.hp.hpl.jena.rdf.model.Literal; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.RDFS; import com.hp.hpl.jena.vocabulary.XSD; import edu.cornell.mannlib.vitro.webapp.beans.Individual; import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty; import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatement; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder; import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationUtils; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.FieldVTwo; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.AddAssociatedConceptsPreprocessor; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation; import edu.cornell.mannlib.vitro.webapp.utils.ConceptSearchService.ConceptSearchServiceUtils; /** * Generates the edit configuration for importing concepts from external * search services, e.g. UMLS etc. * * The N3 for this is set with the default settinf of * */ public class AddAssociatedConceptGenerator extends VivoBaseGenerator implements EditConfigurationGenerator { private Log log = LogFactory.getLog(AddAssociatedConceptGenerator.class); private String template = "addAssociatedConcept.ftl"; private static String SKOSConceptType = "http://www.w3.org/2004/02/skos/core#Concept"; @Override public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq, HttpSession session) { EditConfigurationVTwo editConfiguration = new EditConfigurationVTwo(); initBasics(editConfiguration, vreq); initPropertyParameters(vreq, session, editConfiguration); initObjectPropForm(editConfiguration, vreq); editConfiguration.setTemplate(template); setVarNames(editConfiguration); // Assumes this is a simple case of subject predicate var editConfiguration.setN3Required(this.generateN3Required(vreq)); // n3 optional editConfiguration.setN3Optional(this.generateN3Optional()); // Todo: what do new resources depend on here? // In original form, these variables start off empty editConfiguration.setNewResources(generateNewResources(vreq)); // In scope this.setUrisAndLiteralsInScope(editConfiguration, vreq); // on Form this.setUrisAndLiteralsOnForm(editConfiguration, vreq); editConfiguration.setFilesOnForm(new ArrayList<String>()); // Sparql queries this.setSparqlQueries(editConfiguration, vreq); // set fields setFields(editConfiguration, vreq, EditConfigurationUtils .getPredicateUri(vreq)); setTemplate(editConfiguration, vreq); // No validators required here // Add preprocessors addPreprocessors(editConfiguration, vreq.getWebappDaoFactory()); // Adding additional data, specifically edit mode addFormSpecificData(editConfiguration, vreq); // One override for basic functionality, changing url pattern // and entity // Adding term should return to this same page, not the subject // Return takes the page back to the individual form editConfiguration.setUrlPatternToReturnTo(EditConfigurationUtils .getFormUrlWithoutContext(vreq)); editConfiguration.addValidator(new AntiXssValidation()); // prepare prepare(vreq, editConfiguration); return editConfiguration; } //In this case, the generator is not equipped to handle any deletion //Editing in the usual sense does not exist for this form //So we will disable editing @Override void initObjectPropForm(EditConfigurationVTwo editConfiguration,VitroRequest vreq) { editConfiguration.setObject( null ); } //Ensuring that editing property logic does not get executed on processing //since form's deletions are handled separately @Override void prepare(VitroRequest vreq, EditConfigurationVTwo editConfig) { Model model = vreq.getJenaOntModel(); //Set subject and predicate uri if( editConfig.getSubjectUri() == null) editConfig.setSubjectUri( EditConfigurationUtils.getSubjectUri(vreq)); if( editConfig.getPredicateUri() == null ) editConfig.setPredicateUri( EditConfigurationUtils.getPredicateUri(vreq)); //Always set creation editConfig.prepareForNonUpdate(model); } private void setVarNames(EditConfigurationVTwo editConfiguration) { editConfiguration.setVarNameForSubject("subject"); editConfiguration.setVarNameForPredicate("predicate"); //We are not including concept node here since //we never actually "edit" using this form //the n3 required and optional will still be evaluated based on the form editConfiguration.setVarNameForObject("object"); } protected void setTemplate(EditConfigurationVTwo editConfiguration, VitroRequest vreq) { editConfiguration.setTemplate(template); } /* * N3 Required and Optional Generators as well as supporting methods */ private String getPrefixesString() { //TODO: Include dynamic way of including this return "@prefix core: <http://vivoweb.org/ontology/core#> ."; } //The only string always required is that linking the subject to the concept node //Since the concept node from an external vocabulary may already be in the system //The label and is defined by may already be defined and don't require re-saving private List<String> generateN3Required(VitroRequest vreq) { List<String> n3Required = list( getPrefixesString() + "\n" + "?subject ?predicate ?conceptNode .\n" + "?conceptNode <" + RDF.type.getURI() + "> <http://www.w3.org/2002/07/owl#Thing> ." ); List<String> inversePredicate = getInversePredicate(vreq); //Adding inverse predicate if it exists if(inversePredicate.size() > 0) { n3Required.add("?conceptNode <" + inversePredicate.get(0) + "> ?subject ."); } return n3Required; } //Don't think there's any n3 optional here private List<String> generateN3Optional() { return list("?conceptNode <" + RDFS.label.getURI() + "> ?conceptLabel .\n" + "?conceptNode <" + RDFS.isDefinedBy.getURI() + "> ?conceptSource ." ); } /* * Get new resources */ private Map<String, String> generateNewResources(VitroRequest vreq) { HashMap<String, String> newResources = new HashMap<String, String>(); //There are no new resources here, the concept node uri doesn't //get created but already exists, and vocab uri should already exist as well return newResources; } /* * Set URIS and Literals In Scope and on form and supporting methods */ private void setUrisAndLiteralsInScope(EditConfigurationVTwo editConfiguration, VitroRequest vreq) { HashMap<String, List<String>> urisInScope = new HashMap<String, List<String>>(); //note that at this point the subject, predicate, and object var parameters have already been processed //these two were always set when instantiating an edit configuration object from json, //although the json itself did not specify subject/predicate as part of uris in scope urisInScope.put(editConfiguration.getVarNameForSubject(), Arrays.asList(new String[]{editConfiguration.getSubjectUri()})); urisInScope.put(editConfiguration.getVarNameForPredicate(), Arrays.asList(new String[]{editConfiguration.getPredicateUri()})); //Setting inverse role predicate urisInScope.put("inverseRolePredicate", getInversePredicate(vreq)); editConfiguration.setUrisInScope(urisInScope); //Uris in scope include subject, predicate, and object var //literals in scope empty initially, usually populated by code in prepare for update //with existing values for variables editConfiguration.setLiteralsInScope(new HashMap<String, List<Literal>>()); } private List<String> getInversePredicate(VitroRequest vreq) { List<String> inversePredicateArray = new ArrayList<String>(); ObjectProperty op = EditConfigurationUtils.getObjectProperty(vreq); if(op != null && op.getURIInverse() != null) { inversePredicateArray.add(op.getURIInverse()); } return inversePredicateArray; } //n3 should look as follows //?subject ?predicate ?objectVar private void setUrisAndLiteralsOnForm(EditConfigurationVTwo editConfiguration, VitroRequest vreq) { List<String> urisOnForm = new ArrayList<String>(); List<String> literalsOnForm = new ArrayList<String>(); //The URI of the node that defines the concept urisOnForm.add("conceptNode"); urisOnForm.add("conceptSource"); editConfiguration.setUrisOnform(urisOnForm); //Also need to add the label of the concept literalsOnForm.add("conceptLabel"); editConfiguration.setLiteralsOnForm(literalsOnForm); } /** * Set SPARQL Queries and supporting methods */ private void setSparqlQueries(EditConfigurationVTwo editConfiguration, VitroRequest vreq) { //Sparql queries defining retrieval of literals etc. editConfiguration.setSparqlForAdditionalLiteralsInScope(new HashMap<String, String>()); editConfiguration.setSparqlForAdditionalUrisInScope(new HashMap<String, String>()); editConfiguration.setSparqlForExistingLiterals(new HashMap<String, String>()); editConfiguration.setSparqlForExistingUris(new HashMap<String, String>()); } /** * * Set Fields and supporting methods */ private void setFields(EditConfigurationVTwo editConfiguration, VitroRequest vreq, String predicateUri) { setConceptNodeField(editConfiguration, vreq); setConceptLabelField(editConfiguration, vreq); setVocabURIField(editConfiguration, vreq); } //this field will be hidden and include the concept node URI private void setConceptNodeField(EditConfigurationVTwo editConfiguration, VitroRequest vreq) { editConfiguration.addField(new FieldVTwo(). setName("conceptNode"). setValidators(list("nonempty")). setOptionsType("UNDEFINED")); } private void setVocabURIField(EditConfigurationVTwo editConfiguration, VitroRequest vreq) { editConfiguration.addField(new FieldVTwo(). setName("conceptSource")); } private void setConceptLabelField(EditConfigurationVTwo editConfiguration, VitroRequest vreq) { editConfiguration.addField(new FieldVTwo(). setName("conceptLabel"). setRangeDatatypeUri(XSD.xstring.toString()) ); } //Add preprocessor private void addPreprocessors(EditConfigurationVTwo editConfiguration, WebappDaoFactory wadf) { //An Edit submission preprocessor for enabling addition of multiple terms for a single search editConfiguration.addEditSubmissionPreprocessor( new AddAssociatedConceptsPreprocessor(editConfiguration)); } //Form specific data public void addFormSpecificData(EditConfigurationVTwo editConfiguration, VitroRequest vreq) { HashMap<String, Object> formSpecificData = new HashMap<String, Object>(); //These are the concepts that already exist currently formSpecificData.put("existingConcepts", getExistingConcepts(vreq)); //Return url for adding user defined concept formSpecificData.put("userDefinedConceptUrl", getUserDefinedConceptUrl(vreq)); //Add URIs and labels for different services formSpecificData.put("searchServices", ConceptSearchServiceUtils.getVocabSources()); List<String> inversePredicate = getInversePredicate(vreq); if(inversePredicate.size() > 0) { formSpecificData.put("inversePredicate", inversePredicate.get(0)); } else { formSpecificData.put("inversePredicate", ""); } editConfiguration.setFormSpecificData(formSpecificData); } // private Object getUserDefinedConceptUrl(VitroRequest vreq) { String subjectUri = EditConfigurationUtils.getSubjectUri(vreq); String predicateUri = EditConfigurationUtils.getPredicateUri(vreq); String generatorName = "edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.AddUserDefinedConceptGenerator"; String editUrl = EditConfigurationUtils.getEditUrl(vreq); return editUrl + "?subjectUri=" + UrlBuilder.urlEncode(subjectUri) + "&predicateUri=" + UrlBuilder.urlEncode(predicateUri) + "&editForm=" + UrlBuilder.urlEncode(generatorName); } private List<AssociatedConceptInfo> getExistingConcepts(VitroRequest vreq) { Individual individual = EditConfigurationUtils.getSubjectIndividual(vreq); List<Individual> concepts = individual.getRelatedIndividuals( EditConfigurationUtils.getPredicateUri(vreq)); List<AssociatedConceptInfo> associatedConcepts = getAssociatedConceptInfo(concepts, vreq); sortConcepts(associatedConcepts); return associatedConcepts; } private void sortConcepts(List<AssociatedConceptInfo> concepts) { Collections.sort(concepts, new AssociatedConceptInfoComparator()); log.debug("Concepts should be sorted now" + concepts.toString()); } private List<AssociatedConceptInfo> getAssociatedConceptInfo( List<Individual> concepts, VitroRequest vreq) { List<AssociatedConceptInfo> info = new ArrayList<AssociatedConceptInfo>(); for ( Individual conceptIndividual : concepts ) { boolean isSKOSConcept = false; String conceptUri = conceptIndividual.getURI(); String conceptLabel = conceptIndividual.getName(); //Check if SKOS Concept type List<ObjectPropertyStatement> osl = conceptIndividual.getObjectPropertyStatements(RDF.type.getURI()); for(ObjectPropertyStatement os: osl) { if(os.getObjectURI().equals(SKOSConceptType)) { isSKOSConcept = true; break; } } if(isSKOSConcept) { info.add(new AssociatedConceptInfo(conceptLabel, conceptUri, null, null, SKOSConceptType)); } else { //Get the vocab source and vocab label List<ObjectPropertyStatement> vocabList = conceptIndividual.getObjectPropertyStatements(RDFS.isDefinedBy.getURI()); String vocabSource = null; String vocabLabel = null; if(vocabList != null && vocabList.size() > 0) { vocabSource = vocabList.get(0).getObjectURI(); Individual sourceIndividual = EditConfigurationUtils.getIndividual(vreq, vocabSource); //Assuming name will get label vocabLabel = sourceIndividual.getName(); } info.add(new AssociatedConceptInfo(conceptLabel, conceptUri, vocabSource, vocabLabel, null)); } } return info; } public class AssociatedConceptInfo { private String conceptLabel; private String conceptURI; private String vocabURI; private String vocabLabel; private String type; //In case of SKOS concept, will have skos concept type public AssociatedConceptInfo(String inputLabel, String inputURI, String inputVocabURI, String inputVocabLabel, String inputType) { this.conceptLabel = inputLabel; this.conceptURI = inputURI; this.vocabURI = inputVocabURI; this.vocabLabel = inputVocabLabel; this.type = inputType; } //Getters public String getConceptLabel() { return conceptLabel; } public String getConceptURI() { return conceptURI; } public String getVocabURI() { return vocabURI; } public String getVocabLabel(){ return vocabLabel; } public String getType(){ return type; } } public class AssociatedConceptInfoComparator implements Comparator<AssociatedConceptInfo>{ public int compare(AssociatedConceptInfo concept1, AssociatedConceptInfo concept2) { String concept1Label = concept1.getConceptLabel().toLowerCase(); String concept2Label = concept2.getConceptLabel().toLowerCase(); return concept1Label.compareTo(concept2Label); } } }
updating generator for inclusion of external/user-defined concepts to prevent errors when clicking on edit link for concept from profile page - ensuring license line is correct
src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddAssociatedConceptGenerator.java
updating generator for inclusion of external/user-defined concepts to prevent errors when clicking on edit link for concept from profile page - ensuring license line is correct
<ide><path>rc/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddAssociatedConceptGenerator.java <del>/* <del>Copyright (c) 2012, Cornell University <del>All rights reserved. <del> <del>Redistribution and use in source and binary forms, with or without <del>modification, are permitted provided that the following conditions are met: <del> <del> * Redistributions of source code must retain the above copyright notice, <del> this list of conditions and the following disclaimer. <del> * Redistributions in binary form must reproduce the above copyright notice, <del> this list of conditions and the following disclaimer in the documentation <del> and/or other materials provided with the distribution. <del> * Neither the name of Cornell University nor the names of its contributors <del> may be used to endorse or promote products derived from this software <del> without specific prior written permission. <del> <del>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND <del>ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED <del>WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE <del>DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE <del>FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL <del>DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR <del>SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER <del>CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, <del>OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE <del>OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. <del>*/ <add>/* $This file is distributed under the terms of the license in /doc/license.txt$ */ <add> <ide> <ide> package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators; <ide>
Java
epl-1.0
0c7e07c2c5619459ea01991c36a6cf4b2f2df8cb
0
codenvy/codenvy,R-Brain/codenvy,R-Brain/codenvy,codenvy/codenvy,R-Brain/codenvy,codenvy/codenvy,codenvy/codenvy,R-Brain/codenvy,codenvy/codenvy,R-Brain/codenvy,codenvy/codenvy,R-Brain/codenvy
/* * CODENVY CONFIDENTIAL * __________________ * * [2012] - [2014] Codenvy, S.A. * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Codenvy S.A. and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Codenvy S.A. * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Codenvy S.A.. */ package com.codenvy.subscription.service; import com.codenvy.api.account.server.SubscriptionService; import com.codenvy.api.account.server.dao.Account; import com.codenvy.api.account.server.dao.AccountDao; import com.codenvy.api.account.server.dao.Subscription; import com.codenvy.api.core.ApiException; import com.codenvy.api.core.ConflictException; import com.codenvy.api.core.NotFoundException; import com.codenvy.api.core.ServerException; import com.codenvy.api.workspace.server.dao.Workspace; import com.codenvy.api.workspace.server.dao.WorkspaceDao; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import java.util.List; import java.util.Map; import static com.codenvy.commons.lang.Size.parseSizeToMegabytes; /** * Service provide functionality of Saas subscription. * * @author Sergii Kabashniuk * @author Sergii Leschenko * @author Eugene Voevodin * @author Alexander Garagatyi */ @Singleton public class SaasSubscriptionService extends SubscriptionService { private static final Logger LOG = LoggerFactory.getLogger(SaasSubscriptionService.class); private static final String SAAS_RUNNER_LIFETIME = "saas.runner.lifetime"; private static final String SAAS_BUILDER_EXECUTION_TIME = "saas.builder.execution_time"; private final String saasRunnerLifetime; private final String saasBuilderExecutionTime; private final WorkspaceDao workspaceDao; private final AccountDao accountDao; @Inject public SaasSubscriptionService(WorkspaceDao workspaceDao, AccountDao accountDao, @Named(SAAS_RUNNER_LIFETIME) String saasRunnerLifetime, @Named(SAAS_BUILDER_EXECUTION_TIME) String saasBuilderExecutionTime) { super("Saas", "Saas"); this.saasRunnerLifetime = saasRunnerLifetime; this.saasBuilderExecutionTime = saasBuilderExecutionTime; this.workspaceDao = workspaceDao; this.accountDao = accountDao; } /** * @param subscription * new subscription * @throws com.codenvy.api.core.ConflictException * if subscription state is not valid * @throws com.codenvy.api.core.ServerException * if internal error occurs */ @Override public void beforeCreateSubscription(Subscription subscription) throws ConflictException, ServerException { if (subscription.getProperties() == null) { throw new ConflictException("Subscription properties required"); } if (subscription.getProperties().get("Package") == null) { throw new ConflictException("Subscription property 'Package' required"); } if (subscription.getProperties().get("RAM") == null) { throw new ConflictException("Subscription property 'RAM' required"); } try { final List<Subscription> subscriptions = accountDao.getSubscriptions(subscription.getAccountId(), getServiceId()); if (!subscriptions.isEmpty() && !"sas-community".equals(subscriptions.get(0).getPlanId())) { throw new ConflictException(SUBSCRIPTION_LIMIT_EXHAUSTED_MESSAGE); } } catch (ServerException | NotFoundException e) { LOG.error(e.getLocalizedMessage(), e); throw new ServerException(e.getLocalizedMessage()); } if (workspaceDao.getByAccount(subscription.getAccountId()).isEmpty()) { throw new ConflictException("Given account doesn't have any workspaces."); } } @Override public void afterCreateSubscription(Subscription subscription) throws ApiException { setResources(subscription); } @Override public void onRemoveSubscription(Subscription subscription) throws ServerException, NotFoundException, ConflictException { unsetResources(subscription); } @Override public void onCheckSubscription(Subscription subscription) throws ServerException, NotFoundException, ConflictException { setResources(subscription); } @Override public void onUpdateSubscription(Subscription oldSubscription, Subscription newSubscription) throws ServerException, NotFoundException, ConflictException { setResources(newSubscription); } private void setResources(Subscription subscription) throws NotFoundException, ConflictException, ServerException { final Map<String, String> properties = subscription.getProperties(); if (properties == null) { throw new ConflictException("Subscription properties required"); } String tariffPackage = ensureExistsAndGet("Package", subscription).toLowerCase(); if ("team".equals(tariffPackage) || "enterprise".equals(tariffPackage)) { try { final Account account = accountDao.getById(subscription.getAccountId()); account.getAttributes().put("codenvy:multi-ws", "true"); accountDao.update(account); } catch (NotFoundException e) { throw new ConflictException(e.getLocalizedMessage()); } } List<Workspace> workspaces = workspaceDao.getByAccount(subscription.getAccountId()); if (!workspaces.isEmpty()) { boolean ramIsSet = false; for (Workspace workspace : workspaces) { final Map<String, String> wsAttributes = workspace.getAttributes(); switch (tariffPackage) { case "developer": case "team": //1 hour wsAttributes.put("codenvy:runner_lifetime", saasRunnerLifetime); wsAttributes.put("codenvy:runner_infra", "paid"); break; case "project": case "enterprise": //unlimited wsAttributes.put("codenvy:runner_lifetime", "-1"); wsAttributes.put("codenvy:runner_infra", "always_on"); break; default: throw new NotFoundException(String.format("Package %s not found", tariffPackage)); } wsAttributes.put("codenvy:builder_execution_time", saasBuilderExecutionTime); if (ramIsSet) { wsAttributes.put("codenvy:runner_ram", "0"); } else { try { wsAttributes .put("codenvy:runner_ram", String.valueOf(parseSizeToMegabytes(ensureExistsAndGet("RAM", subscription)))); } catch (IllegalArgumentException exception) { throw new ConflictException("Subscription with such plan can't be added"); } ramIsSet = true; } workspaceDao.update(workspace); } } else { throw new ConflictException("Given account doesn't have any workspaces."); } } private String ensureExistsAndGet(String propertyName, Subscription src) throws ConflictException { final String target = src.getProperties().get(propertyName); if (target == null) { throw new ConflictException(String.format("Subscription property %s required", propertyName)); } return target; } private void unsetResources(Subscription subscription) throws NotFoundException, ServerException, ConflictException { String tariffPackage = subscription.getProperties().get("Package"); tariffPackage = null == tariffPackage ? null : tariffPackage.toLowerCase(); if ("team".equals(tariffPackage) || "enterprise".equals(tariffPackage)) { try { final Account account = accountDao.getById(subscription.getAccountId()); account.getAttributes().remove("codenvy:multi-ws"); accountDao.update(account); } catch (ApiException e) { LOG.error(e.getLocalizedMessage(), e); } } boolean defaultRamUsed = false; for (Workspace workspace : workspaceDao.getByAccount(subscription.getAccountId())) { try { final Map<String, String> wsAttributes = workspace.getAttributes(); if (defaultRamUsed) { wsAttributes.put("codenvy:runner_ram", "0"); } else { wsAttributes.remove("codenvy:runner_ram"); defaultRamUsed = true; } wsAttributes.remove("codenvy:runner_lifetime"); wsAttributes.remove("codenvy:builder_execution_time"); wsAttributes.remove("codenvy:runner_infra"); workspaceDao.update(workspace); } catch (ApiException e) { LOG.error(e.getLocalizedMessage(), e); } } } }
codenvy-hosted-subscription/src/main/java/com/codenvy/subscription/service/SaasSubscriptionService.java
/* * CODENVY CONFIDENTIAL * __________________ * * [2012] - [2014] Codenvy, S.A. * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Codenvy S.A. and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Codenvy S.A. * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Codenvy S.A.. */ package com.codenvy.subscription.service; import com.codenvy.api.account.server.SubscriptionService; import com.codenvy.api.account.server.dao.Account; import com.codenvy.api.account.server.dao.AccountDao; import com.codenvy.api.account.server.dao.Subscription; import com.codenvy.api.core.ApiException; import com.codenvy.api.core.ConflictException; import com.codenvy.api.core.NotFoundException; import com.codenvy.api.core.ServerException; import com.codenvy.api.workspace.server.dao.Workspace; import com.codenvy.api.workspace.server.dao.WorkspaceDao; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import java.util.List; import java.util.Map; import static com.codenvy.commons.lang.MemoryUtils.convert; /** * Service provide functionality of Saas subscription. * * @author Sergii Kabashniuk * @author Sergii Leschenko * @author Eugene Voevodin * @author Alexander Garagatyi */ @Singleton public class SaasSubscriptionService extends SubscriptionService { private static final Logger LOG = LoggerFactory.getLogger(SaasSubscriptionService.class); private static final String SAAS_RUNNER_LIFETIME = "saas.runner.lifetime"; private static final String SAAS_BUILDER_EXECUTION_TIME = "saas.builder.execution_time"; private final String saasRunnerLifetime; private final String saasBuilderExecutionTime; private final WorkspaceDao workspaceDao; private final AccountDao accountDao; @Inject public SaasSubscriptionService(WorkspaceDao workspaceDao, AccountDao accountDao, @Named(SAAS_RUNNER_LIFETIME) String saasRunnerLifetime, @Named(SAAS_BUILDER_EXECUTION_TIME) String saasBuilderExecutionTime) { super("Saas", "Saas"); this.saasRunnerLifetime = saasRunnerLifetime; this.saasBuilderExecutionTime = saasBuilderExecutionTime; this.workspaceDao = workspaceDao; this.accountDao = accountDao; } /** * @param subscription * new subscription * @throws com.codenvy.api.core.ConflictException * if subscription state is not valid * @throws com.codenvy.api.core.ServerException * if internal error occurs */ @Override public void beforeCreateSubscription(Subscription subscription) throws ConflictException, ServerException { if (subscription.getProperties() == null) { throw new ConflictException("Subscription properties required"); } if (subscription.getProperties().get("Package") == null) { throw new ConflictException("Subscription property 'Package' required"); } if (subscription.getProperties().get("RAM") == null) { throw new ConflictException("Subscription property 'RAM' required"); } try { final List<Subscription> subscriptions = accountDao.getSubscriptions(subscription.getAccountId(), getServiceId()); if (!subscriptions.isEmpty() && !"sas-community".equals(subscriptions.get(0).getPlanId())) { throw new ConflictException(SUBSCRIPTION_LIMIT_EXHAUSTED_MESSAGE); } } catch (ServerException | NotFoundException e) { LOG.error(e.getLocalizedMessage(), e); throw new ServerException(e.getLocalizedMessage()); } if (workspaceDao.getByAccount(subscription.getAccountId()).isEmpty()) { throw new ConflictException("Given account doesn't have any workspaces."); } } @Override public void afterCreateSubscription(Subscription subscription) throws ApiException { setResources(subscription); } @Override public void onRemoveSubscription(Subscription subscription) throws ServerException, NotFoundException, ConflictException { unsetResources(subscription); } @Override public void onCheckSubscription(Subscription subscription) throws ServerException, NotFoundException, ConflictException { setResources(subscription); } @Override public void onUpdateSubscription(Subscription oldSubscription, Subscription newSubscription) throws ServerException, NotFoundException, ConflictException { setResources(newSubscription); } private void setResources(Subscription subscription) throws NotFoundException, ConflictException, ServerException { final Map<String, String> properties = subscription.getProperties(); if (properties == null) { throw new ConflictException("Subscription properties required"); } String tariffPackage = ensureExistsAndGet("Package", subscription).toLowerCase(); if ("team".equals(tariffPackage) || "enterprise".equals(tariffPackage)) { try { final Account account = accountDao.getById(subscription.getAccountId()); account.getAttributes().put("codenvy:multi-ws", "true"); accountDao.update(account); } catch (NotFoundException e) { throw new ConflictException(e.getLocalizedMessage()); } } List<Workspace> workspaces = workspaceDao.getByAccount(subscription.getAccountId()); if (!workspaces.isEmpty()) { boolean ramIsSet = false; for (Workspace workspace : workspaces) { final Map<String, String> wsAttributes = workspace.getAttributes(); switch (tariffPackage) { case "developer": case "team": //1 hour wsAttributes.put("codenvy:runner_lifetime", saasRunnerLifetime); wsAttributes.put("codenvy:runner_infra", "paid"); break; case "project": case "enterprise": //unlimited wsAttributes.put("codenvy:runner_lifetime", "-1"); wsAttributes.put("codenvy:runner_infra", "always_on"); break; default: throw new NotFoundException(String.format("Package %s not found", tariffPackage)); } wsAttributes.put("codenvy:builder_execution_time", saasBuilderExecutionTime); if (ramIsSet) { wsAttributes.put("codenvy:runner_ram", "0"); } else { try { wsAttributes.put("codenvy:runner_ram", String.valueOf(convert(ensureExistsAndGet("RAM", subscription)))); } catch (IllegalArgumentException exception) { throw new ConflictException("Subscription with such plan can't be added"); } ramIsSet = true; } workspaceDao.update(workspace); } } else { throw new ConflictException("Given account doesn't have any workspaces."); } } private String ensureExistsAndGet(String propertyName, Subscription src) throws ConflictException { final String target = src.getProperties().get(propertyName); if (target == null) { throw new ConflictException(String.format("Subscription property %s required", propertyName)); } return target; } private void unsetResources(Subscription subscription) throws NotFoundException, ServerException, ConflictException { String tariffPackage = subscription.getProperties().get("Package"); tariffPackage = null == tariffPackage ? null : tariffPackage.toLowerCase(); if ("team".equals(tariffPackage) || "enterprise".equals(tariffPackage)) { try { final Account account = accountDao.getById(subscription.getAccountId()); account.getAttributes().remove("codenvy:multi-ws"); accountDao.update(account); } catch (ApiException e) { LOG.error(e.getLocalizedMessage(), e); } } boolean defaultRamUsed = false; for (Workspace workspace : workspaceDao.getByAccount(subscription.getAccountId())) { try { final Map<String, String> wsAttributes = workspace.getAttributes(); if (defaultRamUsed) { wsAttributes.put("codenvy:runner_ram", "0"); } else { wsAttributes.remove("codenvy:runner_ram"); defaultRamUsed = true; } wsAttributes.remove("codenvy:runner_lifetime"); wsAttributes.remove("codenvy:builder_execution_time"); wsAttributes.remove("codenvy:runner_infra"); workspaceDao.update(workspace); } catch (ApiException e) { LOG.error(e.getLocalizedMessage(), e); } } } }
Removed usage of MemoryUtils
codenvy-hosted-subscription/src/main/java/com/codenvy/subscription/service/SaasSubscriptionService.java
Removed usage of MemoryUtils
<ide><path>odenvy-hosted-subscription/src/main/java/com/codenvy/subscription/service/SaasSubscriptionService.java <ide> import java.util.List; <ide> import java.util.Map; <ide> <del>import static com.codenvy.commons.lang.MemoryUtils.convert; <add>import static com.codenvy.commons.lang.Size.parseSizeToMegabytes; <ide> <ide> /** <ide> * Service provide functionality of Saas subscription. <ide> wsAttributes.put("codenvy:runner_ram", "0"); <ide> } else { <ide> try { <del> wsAttributes.put("codenvy:runner_ram", String.valueOf(convert(ensureExistsAndGet("RAM", subscription)))); <add> wsAttributes <add> .put("codenvy:runner_ram", String.valueOf(parseSizeToMegabytes(ensureExistsAndGet("RAM", subscription)))); <ide> } catch (IllegalArgumentException exception) { <ide> throw new ConflictException("Subscription with such plan can't be added"); <ide> }
Java
apache-2.0
421e360df48a9bb216b10d1bfeab1b88c441fce4
0
lime-company/lime-security-powerauth-webauth,lime-company/powerauth-webflow,lime-company/powerauth-webflow,lime-company/lime-security-powerauth-webauth,lime-company/lime-security-powerauth-webauth,lime-company/powerauth-webflow
/* * Copyright 2019 Wultra s.r.o. * * 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 io.getlime.security.powerauth.app.tppengine.service; import com.google.common.base.Joiner; import io.getlime.security.powerauth.app.tppengine.converter.TppAppConverter; import io.getlime.security.powerauth.app.tppengine.errorhandling.exception.TppAppNotFoundException; import io.getlime.security.powerauth.app.tppengine.errorhandling.exception.TppNotFoundException; import io.getlime.security.powerauth.app.tppengine.model.request.CreateTppAppRequest; import io.getlime.security.powerauth.app.tppengine.model.response.TppAppDetailResponse; import io.getlime.security.powerauth.app.tppengine.repository.OAuthAccessTokenRepository; import io.getlime.security.powerauth.app.tppengine.repository.OAuthClientDetailsRepository; import io.getlime.security.powerauth.app.tppengine.repository.TppAppDetailRepository; import io.getlime.security.powerauth.app.tppengine.repository.TppRepository; import io.getlime.security.powerauth.app.tppengine.repository.model.entity.OAuthClientDetailsEntity; import io.getlime.security.powerauth.app.tppengine.repository.model.entity.TppAppDetailEntity; import io.getlime.security.powerauth.app.tppengine.repository.model.entity.TppEntity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.util.*; /** * Service from handling information about TPP and TPP apps. * * @author Petr Dvorak, [email protected] */ @Service public class TppService { private static final Long OAUTH_ACCESS_TOKEN_VALIDITY = 5 * 60L; private final TppRepository tppRepository; private final TppAppDetailRepository appDetailRepository; private final OAuthClientDetailsRepository clientDetailsRepository; private final OAuthAccessTokenRepository accessTokenRepository; @Autowired public TppService(TppRepository tppRepository, TppAppDetailRepository appDetailRepository, OAuthClientDetailsRepository clientDetailsRepository, OAuthAccessTokenRepository accessTokenRepository) { this.tppRepository = tppRepository; this.appDetailRepository = appDetailRepository; this.clientDetailsRepository = clientDetailsRepository; this.accessTokenRepository = accessTokenRepository; } /** * Fetch application details by provided client ID (OAuth 2.0 identification). * * @param clientId Client ID. * @return Application details for app with given client ID, or null * if no app for given client ID exists. * @throws TppAppNotFoundException In case TPP app is not found. */ public TppAppDetailResponse fetchAppDetailByClientId(String clientId) throws TppAppNotFoundException { final Optional<TppAppDetailEntity> tppAppEntityOptional = appDetailRepository.findByClientId(clientId); if (tppAppEntityOptional.isPresent()) { final TppAppDetailEntity tppAppDetailEntity = tppAppEntityOptional.get(); final Optional<OAuthClientDetailsEntity> clientDetailsRepositoryById = clientDetailsRepository.findById(clientId); if (clientDetailsRepositoryById.isPresent()) { return TppAppConverter.fromTppAppEntity(tppAppDetailEntity, clientDetailsRepositoryById.get()); } else { return TppAppConverter.fromTppAppEntity(tppAppDetailEntity); } } else { throw new TppAppNotFoundException(clientId); } } /** * Fetch application details by provided client ID (OAuth 2.0 identification) and TPP license information. * * @param clientId Client ID. * @param tppLicense TPP license info. * @return Application details for app with given client ID, or null * if no app for given client ID exists. * @throws TppNotFoundException In case TPP is not found. * @throws TppAppNotFoundException In case TPP app is not found. */ public TppAppDetailResponse fetchAppDetailByClientId(String clientId, String tppLicense) throws TppNotFoundException, TppAppNotFoundException { // Create a TPP entity, if it does not exist TppEntity tppEntity = getTppEntity(tppLicense); final Optional<TppAppDetailEntity> tppAppEntityOptional = appDetailRepository.findByClientId(clientId); if (tppAppEntityOptional.isPresent()) { final TppAppDetailEntity tppAppDetailEntity = tppAppEntityOptional.get(); if (Objects.equals(tppAppDetailEntity.getPrimaryKey().getTppId(), tppEntity.getTppId())) { final Optional<OAuthClientDetailsEntity> clientDetailsRepositoryById = clientDetailsRepository.findById(clientId); if (clientDetailsRepositoryById.isPresent()) { return TppAppConverter.fromTppAppEntity(tppAppDetailEntity, clientDetailsRepositoryById.get()); } else { return TppAppConverter.fromTppAppEntity(tppAppDetailEntity); } } else { throw new TppAppNotFoundException(clientId); } } else { throw new TppAppNotFoundException(clientId); } } /** * Fetch applications for given TPP provider based on license information. * * @param tppLicense TPP license information. * @return Application list for given third party. * @throws TppNotFoundException In case TPP is not found. */ public List<TppAppDetailResponse> fetchAppListByTppLicense(String tppLicense) throws TppNotFoundException { final Optional<TppEntity> tppAppEntityOptional = tppRepository.findFirstByTppLicense(tppLicense); if (tppAppEntityOptional.isPresent()) { final TppEntity tppEntity = tppAppEntityOptional.get(); final Iterable<TppAppDetailEntity> appDetailEntityIterable = appDetailRepository.findByTppId(tppEntity.getTppId()); List<TppAppDetailResponse> response = new ArrayList<>(); for (TppAppDetailEntity app: appDetailEntityIterable) { response.add(TppAppConverter.fromTppAppEntity(app)); // no need to list all OAuth 2.0 details here } return response; } else { throw new TppNotFoundException("tpp.notFound", tppLicense); } } /** * Create a new application with provided information. * @param request Request with information about a newly created app. * @return Information about a newly created app, including the OAuth 2.0 credentials (including "client secret"). */ @Transactional public TppAppDetailResponse createApp(CreateTppAppRequest request) { // Create a TPP entity, if it does not exist final Optional<TppEntity> tppEntityOptional = tppRepository.findFirstByTppLicense(request.getTppLicense()); TppEntity tppEntity; if (tppEntityOptional.isPresent()) { // This TPP already exists tppEntity = tppEntityOptional.get(); } else { // TPP does not exist yet, must be created tppEntity = new TppEntity(); tppEntity.setTppLicense(request.getTppLicense()); tppEntity.setTppName(request.getTppName()); tppEntity.setTppAddress(request.getTppAddress()); tppEntity.setTppWebsite(request.getTppWebsite()); tppEntity = tppRepository.save(tppEntity); } // Generate app OAuth 2.0 credentials final String clientId = UUID.randomUUID().toString(); final String clientSecret = UUID.randomUUID().toString(); BCryptPasswordEncoder bcrypt = new BCryptPasswordEncoder(); final String encodedClientSecret = bcrypt.encode(clientSecret); // Create a new TPP app record in database TppAppDetailEntity tppAppDetailEntity = new TppAppDetailEntity(); tppAppDetailEntity.setAppName(request.getAppName()); tppAppDetailEntity.setAppInfo(request.getAppDescription()); tppAppDetailEntity.setTpp(tppEntity); TppAppDetailEntity.TppAppDetailKey tppAppDetailKey = new TppAppDetailEntity.TppAppDetailKey(); tppAppDetailKey.setTppId(tppEntity.getTppId()); tppAppDetailKey.setAppClientId(clientId); tppAppDetailEntity.setTpp(tppEntity); tppAppDetailEntity.setPrimaryKey(tppAppDetailKey); // Sanitize redirect URIs by Base64 decoding them final String redirectUris = sanitizeRedirectUris(request.getRedirectUris()); // Sort scopes and make sure a scope is unique in the collection final String scopes = sanitizeScopes(request.getScopes()); // Store the new OAuth 2.0 credentials in database OAuthClientDetailsEntity oAuthClientDetailsEntity = new OAuthClientDetailsEntity(); oAuthClientDetailsEntity.setClientId(clientId); oAuthClientDetailsEntity.setClientSecret(encodedClientSecret); oAuthClientDetailsEntity.setAuthorizedGrantTypes("authorization_code"); oAuthClientDetailsEntity.setWebServerRedirectUri(redirectUris); oAuthClientDetailsEntity.setScope(scopes); oAuthClientDetailsEntity.setAccessTokenValidity(OAUTH_ACCESS_TOKEN_VALIDITY); oAuthClientDetailsEntity.setAdditionalInformation("{}"); oAuthClientDetailsEntity.setAutoapprove("true"); clientDetailsRepository.save(oAuthClientDetailsEntity); tppAppDetailEntity = appDetailRepository.save(tppAppDetailEntity); return TppAppConverter.fromTppAppEntity(tppAppDetailEntity, oAuthClientDetailsEntity, clientSecret); } /** * Update application details for an app with provided client ID. * @param clientId Client ID of TPP app to be updated. * @param request Request with information about updated app. * @return Information about the updated app. * @throws TppNotFoundException In case TPP is not found. * @throws TppAppNotFoundException In case TPP app is not found. */ @Transactional public TppAppDetailResponse updateApp(String clientId, CreateTppAppRequest request) throws TppNotFoundException, TppAppNotFoundException { // Get TPP entity TppEntity tppEntity = getTppEntity(request.getTppLicense()); // Find application by client ID final Optional<TppAppDetailEntity> appDetailEntityOptional = appDetailRepository.findByClientId(clientId); if (appDetailEntityOptional.isPresent()) { TppAppDetailEntity tppAppDetailEntity = appDetailEntityOptional.get(); // Check if the client ID belongs to the TPP provider if (!Objects.equals(tppAppDetailEntity.getPrimaryKey().getTppId(), tppEntity.getTppId())) { throw new TppAppNotFoundException(clientId); } tppAppDetailEntity.setAppName(request.getAppName()); tppAppDetailEntity.setAppInfo(request.getAppDescription()); // Sanitize redirect URIs by Base64 decoding them final String redirectUris = sanitizeRedirectUris(request.getRedirectUris()); // Sort scopes and make sure a scope is unique in the collection final String scopes = sanitizeScopes(request.getScopes()); // Store the new OAuth 2.0 credentials in database Optional<OAuthClientDetailsEntity> oAuthClientDetailsEntityOptional = clientDetailsRepository.findById(clientId); if (oAuthClientDetailsEntityOptional.isPresent()) { final OAuthClientDetailsEntity oAuthClientDetailsEntity = oAuthClientDetailsEntityOptional.get(); oAuthClientDetailsEntity.setWebServerRedirectUri(redirectUris); if (!scopes.equals(oAuthClientDetailsEntity.getScope())) { oAuthClientDetailsEntity.setScope(scopes); accessTokenRepository.deleteAllByClientId(clientId); // changing application scopes will immediately revoke access tokens } clientDetailsRepository.save(oAuthClientDetailsEntity); tppAppDetailEntity = appDetailRepository.save(tppAppDetailEntity); return TppAppConverter.fromTppAppEntity(tppAppDetailEntity, oAuthClientDetailsEntity); } else { throw new TppAppNotFoundException(clientId); } } else { throw new TppAppNotFoundException(clientId); } } /** * Renew OAuth 2.0 secret for an app with given client ID and belonging to TPP with specific license. * @param clientId Client ID for which to refresh Client Secret. * @param tppLicense License information of the party that owns the app with given Client ID. * @return Information about application, including new client secret. * @throws TppNotFoundException In case TPP was not found. * @throws TppAppNotFoundException In case TPP app was not found. */ public TppAppDetailResponse renewAppSecret(String clientId, String tppLicense) throws TppNotFoundException, TppAppNotFoundException { // Create a TPP entity, if it does not exist TppEntity tppEntity = getTppEntity(tppLicense); final Optional<TppAppDetailEntity> appDetailEntityOptional = appDetailRepository.findByClientId(clientId); if (appDetailEntityOptional.isPresent()) { TppAppDetailEntity tppAppDetailEntity = appDetailEntityOptional.get(); // Check if the client ID belongs to the TPP provider if (!Objects.equals(tppAppDetailEntity.getPrimaryKey().getTppId(), tppEntity.getTppId())) { throw new TppAppNotFoundException(clientId); } // Generate app OAuth 2.0 credentials final String clientSecret = UUID.randomUUID().toString(); BCryptPasswordEncoder bcrypt = new BCryptPasswordEncoder(); final String encodedClientSecret = bcrypt.encode(clientSecret); // Store the new OAuth 2.0 credentials in database Optional<OAuthClientDetailsEntity> oAuthClientDetailsEntityOptional = clientDetailsRepository.findById(clientId); if (oAuthClientDetailsEntityOptional.isPresent()) { final OAuthClientDetailsEntity oAuthClientDetailsEntity = oAuthClientDetailsEntityOptional.get(); oAuthClientDetailsEntity.setClientSecret(encodedClientSecret); clientDetailsRepository.save(oAuthClientDetailsEntity); return TppAppConverter.fromTppAppEntity(tppAppDetailEntity, oAuthClientDetailsEntity, clientSecret); } else { throw new TppAppNotFoundException(clientId); } } else { throw new TppAppNotFoundException(clientId); } } /** * Delete an app based on provided client ID, with crosscheck to client license. * @param clientId Client ID of an app to be deleted. * @param tppLicense License info of a TPP party that owns the app. * @throws TppNotFoundException In case TPP was not found. * @throws TppAppNotFoundException In case TPP app was not found. */ @Transactional public void deleteApp(String clientId, String tppLicense) throws TppNotFoundException, TppAppNotFoundException { // Create a TPP entity, if it does not exist TppEntity tppEntity = getTppEntity(tppLicense); final Optional<TppAppDetailEntity> appDetailEntityOptional = appDetailRepository.findByClientId(clientId); if (appDetailEntityOptional.isPresent()) { TppAppDetailEntity tppAppDetailEntity = appDetailEntityOptional.get(); // Check if the client ID belongs to the TPP provider if (!Objects.equals(tppAppDetailEntity.getPrimaryKey().getTppId(), tppEntity.getTppId())) { throw new TppAppNotFoundException(clientId); } // Store the new OAuth 2.0 credentials in database Optional<OAuthClientDetailsEntity> oAuthClientDetailsEntityOptional = clientDetailsRepository.findById(clientId); if (oAuthClientDetailsEntityOptional.isPresent()) { final OAuthClientDetailsEntity oAuthClientDetailsEntity = oAuthClientDetailsEntityOptional.get(); appDetailRepository.delete(tppAppDetailEntity); clientDetailsRepository.delete(oAuthClientDetailsEntity); accessTokenRepository.deleteAllByClientId(clientId); } else { throw new TppAppNotFoundException(clientId); } } else { throw new TppAppNotFoundException(clientId); } } /** * Find TPP entity based on TPP license. * @param tppLicense TPP license info. * @return TPP entity, in case the TPP entity is found. * @throws TppNotFoundException In case that TPP entity is not found. */ private TppEntity getTppEntity(String tppLicense) throws TppNotFoundException { final Optional<TppEntity> tppEntityOptional = tppRepository.findFirstByTppLicense(tppLicense); TppEntity tppEntity; if (tppEntityOptional.isPresent()) { // This TPP already exists tppEntity = tppEntityOptional.get(); } else { // TPP does not exist - this is an incorrect state throw new TppNotFoundException("tpp.notFound", tppLicense); } return tppEntity; } /** * Create a comma-separated string with unique values from an array, sorted. * @param source Original array. * @return A comma-separated string with unique values from an array, sorted. */ private String sortAndUniqueCommaSeparated(String[] source) { TreeSet<String> set = new TreeSet<>(); Collections.addAll(set, source); String[] result = set.toArray(new String[0]); return Joiner.on(",").join(result); } /** * Create a comma-separated string with unique sorted redirect URIs. * @param redirectUris Original redirect URIs. * @return A comma separated string with unique sorted redirect URIs, or null if original array is null. */ private String sanitizeRedirectUris(String[] redirectUris) { if (redirectUris != null) { String[] sanitizedUris = new String[redirectUris.length]; for (int i = 0; i < redirectUris.length; i++) { // comma is not allowed, we cannot encode the data in DB due to Spring OAuth support sanitizedUris[i] = redirectUris[i].replace(",", "%2C"); } // Make sure that redirect URIs are unique return sortAndUniqueCommaSeparated(sanitizedUris); } return null; } /** * Create a comma-separated string with unique sorted scopes. * @param scopes Original scopes. * @return A comma-separated string with unique sorted scopes, or null if original array is null. */ private String sanitizeScopes(String[] scopes) { return sortAndUniqueCommaSeparated(scopes); } }
powerauth-tpp-engine/src/main/java/io/getlime/security/powerauth/app/tppengine/service/TppService.java
/* * Copyright 2019 Wultra s.r.o. * * 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 io.getlime.security.powerauth.app.tppengine.service; import com.google.common.base.Joiner; import io.getlime.security.powerauth.app.tppengine.converter.TppAppConverter; import io.getlime.security.powerauth.app.tppengine.errorhandling.exception.TppAppNotFoundException; import io.getlime.security.powerauth.app.tppengine.errorhandling.exception.TppNotFoundException; import io.getlime.security.powerauth.app.tppengine.model.request.CreateTppAppRequest; import io.getlime.security.powerauth.app.tppengine.model.response.TppAppDetailResponse; import io.getlime.security.powerauth.app.tppengine.repository.OAuthAccessTokenRepository; import io.getlime.security.powerauth.app.tppengine.repository.OAuthClientDetailsRepository; import io.getlime.security.powerauth.app.tppengine.repository.TppAppDetailRepository; import io.getlime.security.powerauth.app.tppengine.repository.TppRepository; import io.getlime.security.powerauth.app.tppengine.repository.model.entity.OAuthClientDetailsEntity; import io.getlime.security.powerauth.app.tppengine.repository.model.entity.TppAppDetailEntity; import io.getlime.security.powerauth.app.tppengine.repository.model.entity.TppEntity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.util.*; /** * Service from handling information about TPP and TPP apps. * * @author Petr Dvorak, [email protected] */ @Service public class TppService { private static final Long OAUTH_ACCESS_TOKEN_VALIDITY = 5 * 60L; private final TppRepository tppRepository; private final TppAppDetailRepository appDetailRepository; private final OAuthClientDetailsRepository clientDetailsRepository; private final OAuthAccessTokenRepository accessTokenRepository; @Autowired public TppService(TppRepository tppRepository, TppAppDetailRepository appDetailRepository, OAuthClientDetailsRepository clientDetailsRepository, OAuthAccessTokenRepository accessTokenRepository) { this.tppRepository = tppRepository; this.appDetailRepository = appDetailRepository; this.clientDetailsRepository = clientDetailsRepository; this.accessTokenRepository = accessTokenRepository; } /** * Fetch application details by provided client ID (OAuth 2.0 identification). * * @param clientId Client ID. * @return Application details for app with given client ID, or null * if no app for given client ID exists. * @throws TppAppNotFoundException In case TPP app is not found. */ public TppAppDetailResponse fetchAppDetailByClientId(String clientId) throws TppAppNotFoundException { final Optional<TppAppDetailEntity> tppAppEntityOptional = appDetailRepository.findByClientId(clientId); if (tppAppEntityOptional.isPresent()) { final TppAppDetailEntity tppAppDetailEntity = tppAppEntityOptional.get(); final Optional<OAuthClientDetailsEntity> clientDetailsRepositoryById = clientDetailsRepository.findById(clientId); if (clientDetailsRepositoryById.isPresent()) { return TppAppConverter.fromTppAppEntity(tppAppDetailEntity, clientDetailsRepositoryById.get()); } else { return TppAppConverter.fromTppAppEntity(tppAppDetailEntity); } } else { throw new TppAppNotFoundException(clientId); } } /** * Fetch application details by provided client ID (OAuth 2.0 identification) and TPP license information. * * @param clientId Client ID. * @param tppLicense TPP license info. * @return Application details for app with given client ID, or null * if no app for given client ID exists. * @throws TppNotFoundException In case TPP is not found. * @throws TppAppNotFoundException In case TPP app is not found. */ public TppAppDetailResponse fetchAppDetailByClientId(String clientId, String tppLicense) throws TppNotFoundException, TppAppNotFoundException { // Create a TPP entity, if it does not exist TppEntity tppEntity = getTppEntity(tppLicense); final Optional<TppAppDetailEntity> tppAppEntityOptional = appDetailRepository.findByClientId(clientId); if (tppAppEntityOptional.isPresent()) { final TppAppDetailEntity tppAppDetailEntity = tppAppEntityOptional.get(); if (Objects.equals(tppAppDetailEntity.getPrimaryKey().getTppId(), tppEntity.getTppId())) { final Optional<OAuthClientDetailsEntity> clientDetailsRepositoryById = clientDetailsRepository.findById(clientId); if (clientDetailsRepositoryById.isPresent()) { return TppAppConverter.fromTppAppEntity(tppAppDetailEntity, clientDetailsRepositoryById.get()); } else { return TppAppConverter.fromTppAppEntity(tppAppDetailEntity); } } else { throw new TppAppNotFoundException(clientId); } } else { throw new TppAppNotFoundException(clientId); } } /** * Fetch applications for given TPP provider based on license information. * * @param tppLicense TPP license information. * @return Application list for given third party. * @throws TppNotFoundException In case TPP is not found. */ public List<TppAppDetailResponse> fetchAppListByTppLicense(String tppLicense) throws TppNotFoundException { final Optional<TppEntity> tppAppEntityOptional = tppRepository.findFirstByTppLicense(tppLicense); if (tppAppEntityOptional.isPresent()) { final TppEntity tppEntity = tppAppEntityOptional.get(); final Iterable<TppAppDetailEntity> appDetailEntityIterable = appDetailRepository.findByTppId(tppEntity.getTppId()); List<TppAppDetailResponse> response = new ArrayList<>(); for (TppAppDetailEntity app: appDetailEntityIterable) { response.add(TppAppConverter.fromTppAppEntity(app)); // no need to list all OAuth 2.0 details here } return response; } else { throw new TppNotFoundException("tpp.notFound", tppLicense); } } /** * Create a new application with provided information. * @param request Request with information about a newly created app. * @return Information about a newly created app, including the OAuth 2.0 credentials (including "client secret"). */ @Transactional public TppAppDetailResponse createApp(CreateTppAppRequest request) { // Create a TPP entity, if it does not exist final Optional<TppEntity> tppEntityOptional = tppRepository.findFirstByTppLicense(request.getTppLicense()); TppEntity tppEntity; if (tppEntityOptional.isPresent()) { // This TPP already exists tppEntity = tppEntityOptional.get(); } else { // TPP does not exist yet, must be created tppEntity = new TppEntity(); tppEntity.setTppLicense(request.getTppLicense()); tppEntity.setTppName(request.getTppName()); tppEntity.setTppAddress(request.getTppAddress()); tppEntity.setTppWebsite(request.getTppWebsite()); tppEntity = tppRepository.save(tppEntity); } // Generate app OAuth 2.0 credentials final String clientId = UUID.randomUUID().toString(); final String clientSecret = UUID.randomUUID().toString(); BCryptPasswordEncoder bcrypt = new BCryptPasswordEncoder(); final String encodedClientSecret = bcrypt.encode(clientSecret); // Create a new TPP app record in database TppAppDetailEntity tppAppDetailEntity = new TppAppDetailEntity(); tppAppDetailEntity.setAppName(request.getAppName()); tppAppDetailEntity.setAppInfo(request.getAppDescription()); tppAppDetailEntity.setTpp(tppEntity); TppAppDetailEntity.TppAppDetailKey tppAppDetailKey = new TppAppDetailEntity.TppAppDetailKey(); tppAppDetailKey.setTppId(tppEntity.getTppId()); tppAppDetailKey.setAppClientId(clientId); tppAppDetailEntity.setTpp(tppEntity); tppAppDetailEntity.setPrimaryKey(tppAppDetailKey); // Sanitize redirect URIs by Base64 decoding them final String[] redirectUris = request.getRedirectUris(); final String sanitizedRedirectUris; if (redirectUris != null) { for (int i = 0; i < redirectUris.length; i++) { // comma is not allowed, we cannot encode the data in DB due to Spring OAuth support redirectUris[i] = redirectUris[i].replace(",", "%2C"); } sanitizedRedirectUris = Joiner.on(",").join(redirectUris); } else { sanitizedRedirectUris = null; // should not happen due to validation in controller } String[] scopesArray = request.getScopes(); Arrays.sort(scopesArray); final String scopes = Joiner.on(",").join(scopesArray); // Store the new OAuth 2.0 credentials in database OAuthClientDetailsEntity oAuthClientDetailsEntity = new OAuthClientDetailsEntity(); oAuthClientDetailsEntity.setClientId(clientId); oAuthClientDetailsEntity.setClientSecret(encodedClientSecret); oAuthClientDetailsEntity.setAuthorizedGrantTypes("authorization_code"); oAuthClientDetailsEntity.setWebServerRedirectUri(sanitizedRedirectUris); oAuthClientDetailsEntity.setScope(scopes); oAuthClientDetailsEntity.setAccessTokenValidity(OAUTH_ACCESS_TOKEN_VALIDITY); oAuthClientDetailsEntity.setAdditionalInformation("{}"); oAuthClientDetailsEntity.setAutoapprove("true"); clientDetailsRepository.save(oAuthClientDetailsEntity); tppAppDetailEntity = appDetailRepository.save(tppAppDetailEntity); return TppAppConverter.fromTppAppEntity(tppAppDetailEntity, oAuthClientDetailsEntity, clientSecret); } /** * Update application details for an app with provided client ID. * @param clientId Client ID of TPP app to be updated. * @param request Request with information about updated app. * @return Information about the updated app. * @throws TppNotFoundException In case TPP is not found. * @throws TppAppNotFoundException In case TPP app is not found. */ @Transactional public TppAppDetailResponse updateApp(String clientId, CreateTppAppRequest request) throws TppNotFoundException, TppAppNotFoundException { // Get TPP entity TppEntity tppEntity = getTppEntity(request.getTppLicense()); // Find application by client ID final Optional<TppAppDetailEntity> appDetailEntityOptional = appDetailRepository.findByClientId(clientId); if (appDetailEntityOptional.isPresent()) { TppAppDetailEntity tppAppDetailEntity = appDetailEntityOptional.get(); // Check if the client ID belongs to the TPP provider if (!Objects.equals(tppAppDetailEntity.getPrimaryKey().getTppId(), tppEntity.getTppId())) { throw new TppAppNotFoundException(clientId); } tppAppDetailEntity.setAppName(request.getAppName()); tppAppDetailEntity.setAppInfo(request.getAppDescription()); // Sanitize redirect URIs by Base64 decoding them final String[] redirectUris = request.getRedirectUris(); final String sanitizedRedirectUris; if (redirectUris != null) { for (int i = 0; i < redirectUris.length; i++) { // comma is not allowed, we cannot encode the data in DB due to Spring OAuth support redirectUris[i] = redirectUris[i].replace(",", "%2C"); } sanitizedRedirectUris = Joiner.on(",").join(redirectUris); } else { sanitizedRedirectUris = null; // should not happen due to validation in controller } String[] scopesArray = request.getScopes(); Arrays.sort(scopesArray); final String scopes = Joiner.on(",").join(scopesArray); // Store the new OAuth 2.0 credentials in database Optional<OAuthClientDetailsEntity> oAuthClientDetailsEntityOptional = clientDetailsRepository.findById(clientId); if (oAuthClientDetailsEntityOptional.isPresent()) { final OAuthClientDetailsEntity oAuthClientDetailsEntity = oAuthClientDetailsEntityOptional.get(); oAuthClientDetailsEntity.setWebServerRedirectUri(sanitizedRedirectUris); if (!scopes.equals(oAuthClientDetailsEntity.getScope())) { oAuthClientDetailsEntity.setScope(scopes); accessTokenRepository.deleteAllByClientId(clientId); // changing application scopes will immediately revoke access tokens } clientDetailsRepository.save(oAuthClientDetailsEntity); tppAppDetailEntity = appDetailRepository.save(tppAppDetailEntity); return TppAppConverter.fromTppAppEntity(tppAppDetailEntity, oAuthClientDetailsEntity); } else { throw new TppAppNotFoundException(clientId); } } else { throw new TppAppNotFoundException(clientId); } } /** * Delete an app based on provided client ID, with crosscheck to client license. * @param clientId Client ID of an app to be deleted. * @param tppLicense License info of a TPP party that owns the app. * @throws TppNotFoundException In case TPP was not found. * @throws TppAppNotFoundException In case TPP app was not found. */ @Transactional public void deleteApp(String clientId, String tppLicense) throws TppNotFoundException, TppAppNotFoundException { // Create a TPP entity, if it does not exist TppEntity tppEntity = getTppEntity(tppLicense); final Optional<TppAppDetailEntity> appDetailEntityOptional = appDetailRepository.findByClientId(clientId); if (appDetailEntityOptional.isPresent()) { TppAppDetailEntity tppAppDetailEntity = appDetailEntityOptional.get(); // Check if the client ID belongs to the TPP provider if (!Objects.equals(tppAppDetailEntity.getPrimaryKey().getTppId(), tppEntity.getTppId())) { throw new TppAppNotFoundException(clientId); } // Store the new OAuth 2.0 credentials in database Optional<OAuthClientDetailsEntity> oAuthClientDetailsEntityOptional = clientDetailsRepository.findById(clientId); if (oAuthClientDetailsEntityOptional.isPresent()) { final OAuthClientDetailsEntity oAuthClientDetailsEntity = oAuthClientDetailsEntityOptional.get(); appDetailRepository.delete(tppAppDetailEntity); clientDetailsRepository.delete(oAuthClientDetailsEntity); accessTokenRepository.deleteAllByClientId(clientId); } else { throw new TppAppNotFoundException(clientId); } } else { throw new TppAppNotFoundException(clientId); } } /** * Find TPP entity based on TPP license. * @param tppLicense TPP license info. * @return TPP entity, in case the TPP entity is found. * @throws TppNotFoundException In case that TPP entity is not found. */ private TppEntity getTppEntity(String tppLicense) throws TppNotFoundException { final Optional<TppEntity> tppEntityOptional = tppRepository.findFirstByTppLicense(tppLicense); TppEntity tppEntity; if (tppEntityOptional.isPresent()) { // This TPP already exists tppEntity = tppEntityOptional.get(); } else { // TPP does not exist - this is an incorrect state throw new TppNotFoundException("tpp.notFound", tppLicense); } return tppEntity; } /** * Renew OAuth 2.0 secret for an app with given client ID and belonging to TPP with specific license. * @param clientId Client ID for which to refresh Client Secret. * @param tppLicense License information of the party that owns the app with given Client ID. * @return Information about application, including new client secret. * @throws TppNotFoundException In case TPP was not found. * @throws TppAppNotFoundException In case TPP app was not found. */ public TppAppDetailResponse renewAppSecret(String clientId, String tppLicense) throws TppNotFoundException, TppAppNotFoundException { // Create a TPP entity, if it does not exist TppEntity tppEntity = getTppEntity(tppLicense); final Optional<TppAppDetailEntity> appDetailEntityOptional = appDetailRepository.findByClientId(clientId); if (appDetailEntityOptional.isPresent()) { TppAppDetailEntity tppAppDetailEntity = appDetailEntityOptional.get(); // Check if the client ID belongs to the TPP provider if (!Objects.equals(tppAppDetailEntity.getPrimaryKey().getTppId(), tppEntity.getTppId())) { throw new TppAppNotFoundException(clientId); } // Generate app OAuth 2.0 credentials final String clientSecret = UUID.randomUUID().toString(); BCryptPasswordEncoder bcrypt = new BCryptPasswordEncoder(); final String encodedClientSecret = bcrypt.encode(clientSecret); // Store the new OAuth 2.0 credentials in database Optional<OAuthClientDetailsEntity> oAuthClientDetailsEntityOptional = clientDetailsRepository.findById(clientId); if (oAuthClientDetailsEntityOptional.isPresent()) { final OAuthClientDetailsEntity oAuthClientDetailsEntity = oAuthClientDetailsEntityOptional.get(); oAuthClientDetailsEntity.setClientSecret(encodedClientSecret); clientDetailsRepository.save(oAuthClientDetailsEntity); return TppAppConverter.fromTppAppEntity(tppAppDetailEntity, oAuthClientDetailsEntity, clientSecret); } else { throw new TppAppNotFoundException(clientId); } } else { throw new TppAppNotFoundException(clientId); } } }
Isolate sanitization code, normalize storage
powerauth-tpp-engine/src/main/java/io/getlime/security/powerauth/app/tppengine/service/TppService.java
Isolate sanitization code, normalize storage
<ide><path>owerauth-tpp-engine/src/main/java/io/getlime/security/powerauth/app/tppengine/service/TppService.java <ide> tppAppDetailEntity.setPrimaryKey(tppAppDetailKey); <ide> <ide> // Sanitize redirect URIs by Base64 decoding them <del> final String[] redirectUris = request.getRedirectUris(); <del> final String sanitizedRedirectUris; <del> if (redirectUris != null) { <del> for (int i = 0; i < redirectUris.length; i++) { <del> // comma is not allowed, we cannot encode the data in DB due to Spring OAuth support <del> redirectUris[i] = redirectUris[i].replace(",", "%2C"); <del> } <del> sanitizedRedirectUris = Joiner.on(",").join(redirectUris); <del> } else { <del> sanitizedRedirectUris = null; // should not happen due to validation in controller <del> } <del> <del> String[] scopesArray = request.getScopes(); <del> Arrays.sort(scopesArray); <del> final String scopes = Joiner.on(",").join(scopesArray); <add> final String redirectUris = sanitizeRedirectUris(request.getRedirectUris()); <add> <add> // Sort scopes and make sure a scope is unique in the collection <add> final String scopes = sanitizeScopes(request.getScopes()); <ide> <ide> // Store the new OAuth 2.0 credentials in database <ide> OAuthClientDetailsEntity oAuthClientDetailsEntity = new OAuthClientDetailsEntity(); <ide> oAuthClientDetailsEntity.setClientId(clientId); <ide> oAuthClientDetailsEntity.setClientSecret(encodedClientSecret); <ide> oAuthClientDetailsEntity.setAuthorizedGrantTypes("authorization_code"); <del> oAuthClientDetailsEntity.setWebServerRedirectUri(sanitizedRedirectUris); <add> oAuthClientDetailsEntity.setWebServerRedirectUri(redirectUris); <ide> oAuthClientDetailsEntity.setScope(scopes); <ide> oAuthClientDetailsEntity.setAccessTokenValidity(OAUTH_ACCESS_TOKEN_VALIDITY); <ide> oAuthClientDetailsEntity.setAdditionalInformation("{}"); <ide> tppAppDetailEntity.setAppInfo(request.getAppDescription()); <ide> <ide> // Sanitize redirect URIs by Base64 decoding them <del> final String[] redirectUris = request.getRedirectUris(); <del> final String sanitizedRedirectUris; <del> if (redirectUris != null) { <del> for (int i = 0; i < redirectUris.length; i++) { <del> // comma is not allowed, we cannot encode the data in DB due to Spring OAuth support <del> redirectUris[i] = redirectUris[i].replace(",", "%2C"); <del> } <del> sanitizedRedirectUris = Joiner.on(",").join(redirectUris); <del> } else { <del> sanitizedRedirectUris = null; // should not happen due to validation in controller <del> } <del> <del> String[] scopesArray = request.getScopes(); <del> Arrays.sort(scopesArray); <del> final String scopes = Joiner.on(",").join(scopesArray); <add> final String redirectUris = sanitizeRedirectUris(request.getRedirectUris()); <add> <add> // Sort scopes and make sure a scope is unique in the collection <add> final String scopes = sanitizeScopes(request.getScopes()); <ide> <ide> // Store the new OAuth 2.0 credentials in database <ide> Optional<OAuthClientDetailsEntity> oAuthClientDetailsEntityOptional = clientDetailsRepository.findById(clientId); <ide> if (oAuthClientDetailsEntityOptional.isPresent()) { <ide> final OAuthClientDetailsEntity oAuthClientDetailsEntity = oAuthClientDetailsEntityOptional.get(); <del> oAuthClientDetailsEntity.setWebServerRedirectUri(sanitizedRedirectUris); <add> oAuthClientDetailsEntity.setWebServerRedirectUri(redirectUris); <ide> if (!scopes.equals(oAuthClientDetailsEntity.getScope())) { <ide> oAuthClientDetailsEntity.setScope(scopes); <ide> accessTokenRepository.deleteAllByClientId(clientId); // changing application scopes will immediately revoke access tokens <ide> } <ide> <ide> /** <add> * Renew OAuth 2.0 secret for an app with given client ID and belonging to TPP with specific license. <add> * @param clientId Client ID for which to refresh Client Secret. <add> * @param tppLicense License information of the party that owns the app with given Client ID. <add> * @return Information about application, including new client secret. <add> * @throws TppNotFoundException In case TPP was not found. <add> * @throws TppAppNotFoundException In case TPP app was not found. <add> */ <add> public TppAppDetailResponse renewAppSecret(String clientId, String tppLicense) throws TppNotFoundException, TppAppNotFoundException { <add> // Create a TPP entity, if it does not exist <add> TppEntity tppEntity = getTppEntity(tppLicense); <add> <add> final Optional<TppAppDetailEntity> appDetailEntityOptional = appDetailRepository.findByClientId(clientId); <add> if (appDetailEntityOptional.isPresent()) { <add> TppAppDetailEntity tppAppDetailEntity = appDetailEntityOptional.get(); <add> // Check if the client ID belongs to the TPP provider <add> if (!Objects.equals(tppAppDetailEntity.getPrimaryKey().getTppId(), tppEntity.getTppId())) { <add> throw new TppAppNotFoundException(clientId); <add> } <add> <add> // Generate app OAuth 2.0 credentials <add> final String clientSecret = UUID.randomUUID().toString(); <add> BCryptPasswordEncoder bcrypt = new BCryptPasswordEncoder(); <add> final String encodedClientSecret = bcrypt.encode(clientSecret); <add> <add> // Store the new OAuth 2.0 credentials in database <add> Optional<OAuthClientDetailsEntity> oAuthClientDetailsEntityOptional = clientDetailsRepository.findById(clientId); <add> if (oAuthClientDetailsEntityOptional.isPresent()) { <add> final OAuthClientDetailsEntity oAuthClientDetailsEntity = oAuthClientDetailsEntityOptional.get(); <add> oAuthClientDetailsEntity.setClientSecret(encodedClientSecret); <add> clientDetailsRepository.save(oAuthClientDetailsEntity); <add> return TppAppConverter.fromTppAppEntity(tppAppDetailEntity, oAuthClientDetailsEntity, clientSecret); <add> } else { <add> throw new TppAppNotFoundException(clientId); <add> } <add> <add> } else { <add> throw new TppAppNotFoundException(clientId); <add> } <add> <add> } <add> <add> /** <ide> * Delete an app based on provided client ID, with crosscheck to client license. <ide> * @param clientId Client ID of an app to be deleted. <ide> * @param tppLicense License info of a TPP party that owns the app. <ide> } <ide> <ide> /** <del> * Renew OAuth 2.0 secret for an app with given client ID and belonging to TPP with specific license. <del> * @param clientId Client ID for which to refresh Client Secret. <del> * @param tppLicense License information of the party that owns the app with given Client ID. <del> * @return Information about application, including new client secret. <del> * @throws TppNotFoundException In case TPP was not found. <del> * @throws TppAppNotFoundException In case TPP app was not found. <del> */ <del> public TppAppDetailResponse renewAppSecret(String clientId, String tppLicense) throws TppNotFoundException, TppAppNotFoundException { <del> // Create a TPP entity, if it does not exist <del> TppEntity tppEntity = getTppEntity(tppLicense); <del> <del> final Optional<TppAppDetailEntity> appDetailEntityOptional = appDetailRepository.findByClientId(clientId); <del> if (appDetailEntityOptional.isPresent()) { <del> TppAppDetailEntity tppAppDetailEntity = appDetailEntityOptional.get(); <del> // Check if the client ID belongs to the TPP provider <del> if (!Objects.equals(tppAppDetailEntity.getPrimaryKey().getTppId(), tppEntity.getTppId())) { <del> throw new TppAppNotFoundException(clientId); <del> } <del> <del> // Generate app OAuth 2.0 credentials <del> final String clientSecret = UUID.randomUUID().toString(); <del> BCryptPasswordEncoder bcrypt = new BCryptPasswordEncoder(); <del> final String encodedClientSecret = bcrypt.encode(clientSecret); <del> <del> // Store the new OAuth 2.0 credentials in database <del> Optional<OAuthClientDetailsEntity> oAuthClientDetailsEntityOptional = clientDetailsRepository.findById(clientId); <del> if (oAuthClientDetailsEntityOptional.isPresent()) { <del> final OAuthClientDetailsEntity oAuthClientDetailsEntity = oAuthClientDetailsEntityOptional.get(); <del> oAuthClientDetailsEntity.setClientSecret(encodedClientSecret); <del> clientDetailsRepository.save(oAuthClientDetailsEntity); <del> return TppAppConverter.fromTppAppEntity(tppAppDetailEntity, oAuthClientDetailsEntity, clientSecret); <del> } else { <del> throw new TppAppNotFoundException(clientId); <del> } <del> <del> } else { <del> throw new TppAppNotFoundException(clientId); <del> } <del> <del> } <add> * Create a comma-separated string with unique values from an array, sorted. <add> * @param source Original array. <add> * @return A comma-separated string with unique values from an array, sorted. <add> */ <add> private String sortAndUniqueCommaSeparated(String[] source) { <add> TreeSet<String> set = new TreeSet<>(); <add> Collections.addAll(set, source); <add> String[] result = set.toArray(new String[0]); <add> return Joiner.on(",").join(result); <add> } <add> <add> /** <add> * Create a comma-separated string with unique sorted redirect URIs. <add> * @param redirectUris Original redirect URIs. <add> * @return A comma separated string with unique sorted redirect URIs, or null if original array is null. <add> */ <add> private String sanitizeRedirectUris(String[] redirectUris) { <add> if (redirectUris != null) { <add> String[] sanitizedUris = new String[redirectUris.length]; <add> for (int i = 0; i < redirectUris.length; i++) { <add> // comma is not allowed, we cannot encode the data in DB due to Spring OAuth support <add> sanitizedUris[i] = redirectUris[i].replace(",", "%2C"); <add> } <add> // Make sure that redirect URIs are unique <add> return sortAndUniqueCommaSeparated(sanitizedUris); <add> } <add> return null; <add> } <add> <add> /** <add> * Create a comma-separated string with unique sorted scopes. <add> * @param scopes Original scopes. <add> * @return A comma-separated string with unique sorted scopes, or null if original array is null. <add> */ <add> private String sanitizeScopes(String[] scopes) { <add> return sortAndUniqueCommaSeparated(scopes); <add> } <add> <ide> }
Java
apache-2.0
ad5364f4fd8fdfa69e05fad071ea6bb21d583799
0
signed/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,semonte/intellij-community,kool79/intellij-community,holmes/intellij-community,kool79/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,supersven/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,signed/intellij-community,Distrotech/intellij-community,caot/intellij-community,da1z/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,clumsy/intellij-community,caot/intellij-community,vladmm/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,fnouama/intellij-community,ryano144/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,signed/intellij-community,samthor/intellij-community,semonte/intellij-community,amith01994/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,semonte/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,signed/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,caot/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,petteyg/intellij-community,kool79/intellij-community,petteyg/intellij-community,FHannes/intellij-community,FHannes/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,supersven/intellij-community,clumsy/intellij-community,caot/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,vladmm/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,diorcety/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,supersven/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,allotria/intellij-community,kdwink/intellij-community,fnouama/intellij-community,da1z/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,gnuhub/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,ernestp/consulo,apixandru/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,consulo/consulo,fitermay/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,dslomov/intellij-community,robovm/robovm-studio,holmes/intellij-community,kool79/intellij-community,holmes/intellij-community,fitermay/intellij-community,izonder/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,slisson/intellij-community,ibinti/intellij-community,semonte/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,jagguli/intellij-community,supersven/intellij-community,signed/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,kool79/intellij-community,samthor/intellij-community,supersven/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,muntasirsyed/intellij-community,consulo/consulo,consulo/consulo,consulo/consulo,dslomov/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,retomerz/intellij-community,holmes/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,robovm/robovm-studio,retomerz/intellij-community,akosyakov/intellij-community,slisson/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,ernestp/consulo,dslomov/intellij-community,apixandru/intellij-community,blademainer/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,apixandru/intellij-community,adedayo/intellij-community,slisson/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,supersven/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,signed/intellij-community,amith01994/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,allotria/intellij-community,suncycheng/intellij-community,consulo/consulo,ftomassetti/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,semonte/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,semonte/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,caot/intellij-community,adedayo/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,caot/intellij-community,izonder/intellij-community,supersven/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,ernestp/consulo,fnouama/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,robovm/robovm-studio,FHannes/intellij-community,FHannes/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,ernestp/consulo,da1z/intellij-community,vvv1559/intellij-community,caot/intellij-community,gnuhub/intellij-community,slisson/intellij-community,holmes/intellij-community,tmpgit/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,izonder/intellij-community,consulo/consulo,ivan-fedorov/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,caot/intellij-community,slisson/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,allotria/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,hurricup/intellij-community,wreckJ/intellij-community,slisson/intellij-community,fitermay/intellij-community,slisson/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,allotria/intellij-community,blademainer/intellij-community,vladmm/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,kdwink/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,ernestp/consulo,fnouama/intellij-community,jagguli/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,signed/intellij-community,xfournet/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,amith01994/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,apixandru/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,robovm/robovm-studio,amith01994/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,fnouama/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,signed/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,samthor/intellij-community,nicolargo/intellij-community,supersven/intellij-community,vladmm/intellij-community,izonder/intellij-community,suncycheng/intellij-community,da1z/intellij-community,diorcety/intellij-community,allotria/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,allotria/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,kool79/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,kdwink/intellij-community,ryano144/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,diorcety/intellij-community,ryano144/intellij-community,clumsy/intellij-community,da1z/intellij-community,retomerz/intellij-community,signed/intellij-community,hurricup/intellij-community,xfournet/intellij-community,izonder/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,kool79/intellij-community,kdwink/intellij-community,izonder/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,retomerz/intellij-community,xfournet/intellij-community,ryano144/intellij-community,xfournet/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,caot/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,holmes/intellij-community,apixandru/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,samthor/intellij-community,semonte/intellij-community,semonte/intellij-community,adedayo/intellij-community,ryano144/intellij-community,kdwink/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,signed/intellij-community,retomerz/intellij-community,fnouama/intellij-community,asedunov/intellij-community,ibinti/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,apixandru/intellij-community,kool79/intellij-community,holmes/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,ernestp/consulo,da1z/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,samthor/intellij-community,blademainer/intellij-community,clumsy/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,izonder/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,supersven/intellij-community,kool79/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,fitermay/intellij-community,jagguli/intellij-community,holmes/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,petteyg/intellij-community,clumsy/intellij-community,ibinti/intellij-community,supersven/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,fnouama/intellij-community,petteyg/intellij-community,FHannes/intellij-community,semonte/intellij-community,blademainer/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,petteyg/intellij-community
/* * Copyright 2000-2009 JetBrains s.r.o. * * 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.intellij.compiler.impl; import com.intellij.ProjectTopics; import com.intellij.compiler.CompileServerManager; import com.intellij.compiler.CompilerConfiguration; import com.intellij.compiler.CompilerIOUtil; import com.intellij.compiler.CompilerWorkspaceConfiguration; import com.intellij.compiler.make.MakeUtil; import com.intellij.compiler.server.BuildManager; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.compiler.*; import com.intellij.openapi.compiler.ex.CompileContextEx; import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.project.ProjectManagerAdapter; import com.intellij.openapi.roots.*; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.*; import com.intellij.openapi.vfs.newvfs.FileAttribute; import com.intellij.openapi.vfs.newvfs.ManagingFS; import com.intellij.openapi.vfs.newvfs.NewVirtualFile; import com.intellij.openapi.vfs.newvfs.persistent.FSRecords; import com.intellij.openapi.vfs.newvfs.persistent.PersistentFS; import com.intellij.util.Alarm; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.SLRUCache; import com.intellij.util.indexing.FileBasedIndex; import com.intellij.util.indexing.IndexInfrastructure; import com.intellij.util.io.*; import com.intellij.util.io.DataOutputStream; import com.intellij.util.messages.MessageBusConnection; import gnu.trove.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.*; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; /** * @author Eugene Zhuravlev * Date: Jun 3, 2008 * * A source file is scheduled for recompilation if * 1. its timestamp has changed * 2. one of its corresponding output files was deleted * 3. output root of containing module has changed * * An output file is scheduled for deletion if: * 1. corresponding source file has been scheduled for recompilation (see above) * 2. corresponding source file has been deleted */ public class TranslatingCompilerFilesMonitor implements ApplicationComponent { private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.impl.TranslatingCompilerFilesMonitor"); public static boolean ourDebugMode = false; private static final FileAttribute ourSourceFileAttribute = new FileAttribute("_make_source_file_info_", 3); private static final FileAttribute ourOutputFileAttribute = new FileAttribute("_make_output_file_info_", 3); private static final Key<Map<String, VirtualFile>> SOURCE_FILES_CACHE = Key.create("_source_url_to_vfile_cache_"); private final Object myDataLock = new Object(); private final TIntHashSet mySuspendedProjects = new TIntHashSet(); // projectId for allprojects that should not be monitored private final TIntObjectHashMap<TIntHashSet> mySourcesToRecompile = new TIntObjectHashMap<TIntHashSet>(); // ProjectId->set of source file paths private PersistentHashMap<Integer, TIntObjectHashMap<Pair<Integer, Integer>>> myOutputRootsStorage; // ProjectId->map[moduleId->Pair(outputDirId, testOutputDirId)] // Map: projectId -> Map{output path -> [sourceUrl; classname]} private final SLRUCache<Integer, Outputs> myOutputsToDelete = new SLRUCache<Integer, Outputs>(3, 3) { @Override public Outputs getIfCached(Integer key) { final Outputs value = super.getIfCached(key); if (value != null) { value.allocate(); } return value; } @NotNull @Override public Outputs get(Integer key) { final Outputs value = super.get(key); value.allocate(); return value; } @NotNull @Override public Outputs createValue(Integer key) { try { final String dirName = FSRecords.getNames().valueOf(key); final File storeFile; if (StringUtil.isEmpty(dirName)) { storeFile = null; } else { final File compilerCacheDir = CompilerPaths.getCacheStoreDirectory(dirName); storeFile = compilerCacheDir.exists()? new File(compilerCacheDir, "paths_to_delete.dat") : null; } return new Outputs(storeFile, loadPathsToDelete(storeFile)); } catch (IOException e) { LOG.info(e); return new Outputs(null, new HashMap<String, SourceUrlClassNamePair>()); } } @Override protected void onDropFromCache(Integer key, Outputs value) { value.release(); } }; private final SLRUCache<Project, File> myGeneratedDataPaths = new SLRUCache<Project, File>(8, 8) { @NotNull public File createValue(final Project project) { Disposer.register(project, new Disposable() { public void dispose() { myGeneratedDataPaths.remove(project); } }); return CompilerPaths.getGeneratedDataDirectory(project); } }; private final SLRUCache<Integer, TIntObjectHashMap<Pair<Integer, Integer>>> myProjectOutputRoots = new SLRUCache<Integer, TIntObjectHashMap<Pair<Integer, Integer>>>(2, 2) { protected void onDropFromCache(Integer key, TIntObjectHashMap<Pair<Integer, Integer>> value) { try { myOutputRootsStorage.put(key, value); } catch (IOException e) { LOG.info(e); } } @NotNull public TIntObjectHashMap<Pair<Integer, Integer>> createValue(Integer key) { TIntObjectHashMap<Pair<Integer, Integer>> map = null; try { ensureOutputStorageInitialized(); map = myOutputRootsStorage.get(key); } catch (IOException e) { LOG.info(e); } return map != null? map : new TIntObjectHashMap<Pair<Integer, Integer>>(); } }; private final ProjectManager myProjectManager; private final TIntIntHashMap myInitInProgress = new TIntIntHashMap(); // projectId for successfully initialized projects private final Object myAsyncScanLock = new Object(); public TranslatingCompilerFilesMonitor(VirtualFileManager vfsManager, ProjectManager projectManager, Application application) { myProjectManager = projectManager; projectManager.addProjectManagerListener(new MyProjectManagerListener()); vfsManager.addVirtualFileListener(new MyVfsListener(), application); } public static TranslatingCompilerFilesMonitor getInstance() { return ApplicationManager.getApplication().getComponent(TranslatingCompilerFilesMonitor.class); } public void suspendProject(Project project) { final int projectId = getProjectId(project); synchronized (myDataLock) { if (!mySuspendedProjects.add(projectId)) { return; } FileUtil.createIfDoesntExist(CompilerPaths.getRebuildMarkerFile(project)); // cleanup internal structures to free memory mySourcesToRecompile.remove(projectId); myOutputsToDelete.remove(projectId); myGeneratedDataPaths.remove(project); } synchronized (myProjectOutputRoots) { myProjectOutputRoots.remove(projectId); } try { myOutputRootsStorage.remove(projectId); } catch (IOException e) { LOG.info(e); } } public void watchProject(Project project) { synchronized (myDataLock) { mySuspendedProjects.remove(getProjectId(project)); } } public boolean isSuspended(Project project) { return isSuspended(getProjectId(project)); } public boolean isSuspended(int projectId) { synchronized (myDataLock) { return mySuspendedProjects.contains(projectId); } } @Nullable public static VirtualFile getSourceFileByOutput(VirtualFile outputFile) { final OutputFileInfo outputFileInfo = loadOutputInfo(outputFile); if (outputFileInfo != null) { final String path = outputFileInfo.getSourceFilePath(); if (path != null) { return LocalFileSystem.getInstance().findFileByPath(path); } } return null; } public void collectFiles(CompileContext context, final TranslatingCompiler compiler, Iterator<VirtualFile> scopeSrcIterator, boolean forceCompile, final boolean isRebuild, Collection<VirtualFile> toCompile, Collection<Trinity<File, String, Boolean>> toDelete) { final Project project = context.getProject(); final int projectId = getProjectId(project); final CompilerConfiguration configuration = CompilerConfiguration.getInstance(project); final boolean _forceCompile = forceCompile || isRebuild; final Set<VirtualFile> selectedForRecompilation = new HashSet<VirtualFile>(); synchronized (myDataLock) { final TIntHashSet pathsToRecompile = mySourcesToRecompile.get(projectId); if (_forceCompile || pathsToRecompile != null && !pathsToRecompile.isEmpty()) { if (ourDebugMode) { System.out.println("Analysing potentially recompilable files for " + compiler.getDescription()); } while (scopeSrcIterator.hasNext()) { final VirtualFile file = scopeSrcIterator.next(); if (!file.isValid()) { if (LOG.isDebugEnabled() || ourDebugMode) { LOG.debug("Skipping invalid file " + file.getPresentableUrl()); if (ourDebugMode) { System.out.println("\t SKIPPED(INVALID) " + file.getPresentableUrl()); } } continue; } final int fileId = getFileId(file); if (_forceCompile) { if (compiler.isCompilableFile(file, context) && !configuration.isExcludedFromCompilation(file)) { toCompile.add(file); if (ourDebugMode) { System.out.println("\t INCLUDED " + file.getPresentableUrl()); } selectedForRecompilation.add(file); if (pathsToRecompile == null || !pathsToRecompile.contains(fileId)) { loadInfoAndAddSourceForRecompilation(projectId, file); } } else { if (ourDebugMode) { System.out.println("\t NOT COMPILABLE OR EXCLUDED " + file.getPresentableUrl()); } } } else if (pathsToRecompile.contains(fileId)) { if (compiler.isCompilableFile(file, context) && !configuration.isExcludedFromCompilation(file)) { toCompile.add(file); if (ourDebugMode) { System.out.println("\t INCLUDED " + file.getPresentableUrl()); } selectedForRecompilation.add(file); } else { if (ourDebugMode) { System.out.println("\t NOT COMPILABLE OR EXCLUDED " + file.getPresentableUrl()); } } } else { if (ourDebugMode) { System.out.println("\t NOT INCLUDED " + file.getPresentableUrl()); } } } } // it is important that files to delete are collected after the files to compile (see what happens if forceCompile == true) if (!isRebuild) { final Outputs outputs = myOutputsToDelete.get(projectId); try { final VirtualFileManager vfm = VirtualFileManager.getInstance(); final LocalFileSystem lfs = LocalFileSystem.getInstance(); final List<String> zombieEntries = new ArrayList<String>(); final Map<String, VirtualFile> srcFileCache = getFileCache(context); for (Map.Entry<String, SourceUrlClassNamePair> entry : outputs.getEntries()) { final String outputPath = entry.getKey(); final SourceUrlClassNamePair classNamePair = entry.getValue(); final String sourceUrl = classNamePair.getSourceUrl(); final VirtualFile srcFile; if (srcFileCache.containsKey(sourceUrl)) { srcFile = srcFileCache.get(sourceUrl); } else { srcFile = vfm.findFileByUrl(sourceUrl); srcFileCache.put(sourceUrl, srcFile); } final boolean sourcePresent = srcFile != null; if (sourcePresent) { if (!compiler.isCompilableFile(srcFile, context)) { continue; // do not collect files that were compiled by another compiler } if (!selectedForRecompilation.contains(srcFile)) { if (!isMarkedForRecompilation(projectId, getFileId(srcFile))) { if (LOG.isDebugEnabled() || ourDebugMode) { final String message = "Found zombie entry (output is marked, but source is present and up-to-date): " + outputPath; LOG.debug(message); if (ourDebugMode) { System.out.println(message); } } zombieEntries.add(outputPath); } continue; } } if (lfs.findFileByPath(outputPath) != null) { //noinspection UnnecessaryBoxing final File file = new File(outputPath); toDelete.add(new Trinity<File, String, Boolean>(file, classNamePair.getClassName(), Boolean.valueOf(sourcePresent))); if (LOG.isDebugEnabled() || ourDebugMode) { final String message = "Found file to delete: " + file; LOG.debug(message); if (ourDebugMode) { System.out.println(message); } } } else { if (LOG.isDebugEnabled() || ourDebugMode) { final String message = "Found zombie entry marked for deletion: " + outputPath; LOG.debug(message); if (ourDebugMode) { System.out.println(message); } } // must be gagbage entry, should cleanup zombieEntries.add(outputPath); } } for (String path : zombieEntries) { unmarkOutputPathForDeletion(projectId, path); } } finally { outputs.release(); } } } } private static Map<String, VirtualFile> getFileCache(CompileContext context) { Map<String, VirtualFile> cache = context.getUserData(SOURCE_FILES_CACHE); if (cache == null) { context.putUserData(SOURCE_FILES_CACHE, cache = new HashMap<String, VirtualFile>()); } return cache; } private static int getFileId(final VirtualFile file) { return FileBasedIndex.getFileId(file); } private static VirtualFile findFileById(int id) { return IndexInfrastructure.findFileById((PersistentFS)ManagingFS.getInstance(), id); } public void update(final CompileContext context, @Nullable final String outputRoot, final Collection<TranslatingCompiler.OutputItem> successfullyCompiled, final VirtualFile[] filesToRecompile) throws IOException { final Project project = context.getProject(); final int projectId = getProjectId(project); if (!successfullyCompiled.isEmpty()) { final LocalFileSystem lfs = LocalFileSystem.getInstance(); final IOException[] exceptions = {null}; // need read action here to ensure that no modifications were made to VFS while updating file attributes ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { try { final Map<VirtualFile, SourceFileInfo> compiledSources = new HashMap<VirtualFile, SourceFileInfo>(); final Set<VirtualFile> forceRecompile = new HashSet<VirtualFile>(); for (TranslatingCompiler.OutputItem item : successfullyCompiled) { final VirtualFile sourceFile = item.getSourceFile(); final boolean isSourceValid = sourceFile.isValid(); SourceFileInfo srcInfo = compiledSources.get(sourceFile); if (isSourceValid && srcInfo == null) { srcInfo = loadSourceInfo(sourceFile); if (srcInfo != null) { srcInfo.clearPaths(projectId); } else { srcInfo = new SourceFileInfo(); } compiledSources.put(sourceFile, srcInfo); } final String outputPath = item.getOutputPath(); if (outputPath != null) { // can be null for packageinfo final VirtualFile outputFile = lfs.findFileByPath(outputPath); //assert outputFile != null : "Virtual file was not found for \"" + outputPath + "\""; if (outputFile != null) { if (!sourceFile.equals(outputFile)) { final String className = outputRoot == null? null : MakeUtil.relativeClassPathToQName(outputPath.substring(outputRoot.length()), '/'); if (isSourceValid) { srcInfo.addOutputPath(projectId, outputPath); saveOutputInfo(outputFile, new OutputFileInfo(sourceFile.getPath(), className)); } else { markOutputPathForDeletion(projectId, outputPath, className, sourceFile.getUrl()); } } } else { // output file was not found LOG.warn("TranslatingCompilerFilesMonitor.update(): Virtual file was not found for \"" + outputPath + "\""); if (isSourceValid) { forceRecompile.add(sourceFile); } } } } final long compilationStartStamp = ((CompileContextEx)context).getStartCompilationStamp(); for (Map.Entry<VirtualFile, SourceFileInfo> entry : compiledSources.entrySet()) { final SourceFileInfo info = entry.getValue(); final VirtualFile file = entry.getKey(); final long fileStamp = file.getTimeStamp(); info.updateTimestamp(projectId, fileStamp); saveSourceInfo(file, info); if (LOG.isDebugEnabled() || ourDebugMode) { final String message = "Unschedule recompilation (successfully compiled) " + file.getPresentableUrl(); LOG.debug(message); if (ourDebugMode) { System.out.println(message); } } removeSourceForRecompilation(projectId, Math.abs(getFileId(file))); if (fileStamp > compilationStartStamp && !((CompileContextEx)context).isGenerated(file) || forceRecompile.contains(file)) { // changes were made during compilation, need to re-schedule compilation // it is important to invoke removeSourceForRecompilation() before this call to make sure // the corresponding output paths will be scheduled for deletion addSourceForRecompilation(projectId, file, info); } } } catch (IOException e) { exceptions[0] = e; } } }); if (exceptions[0] != null) { throw exceptions[0]; } } if (filesToRecompile.length > 0) { ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { for (VirtualFile file : filesToRecompile) { if (file.isValid()) { loadInfoAndAddSourceForRecompilation(projectId, file); } } } }); } } public void updateOutputRootsLayout(Project project) { final TIntObjectHashMap<Pair<Integer, Integer>> map = buildOutputRootsLayout(new ProjectRef(project)); final int projectId = getProjectId(project); synchronized (myProjectOutputRoots) { myProjectOutputRoots.put(projectId, map); } } @NotNull public String getComponentName() { return "TranslatingCompilerFilesMonitor"; } public void initComponent() { ensureOutputStorageInitialized(); } private static File getOutputRootsFile() { return new File(CompilerPaths.getCompilerSystemDirectory(), "output_roots.dat"); } private static void deleteStorageFiles(File tableFile) { final File[] files = tableFile.getParentFile().listFiles(); if (files != null) { final String name = tableFile.getName(); for (File file : files) { if (file.getName().startsWith(name)) { FileUtil.delete(file); } } } } private static Map<String, SourceUrlClassNamePair> loadPathsToDelete(@Nullable final File file) { final Map<String, SourceUrlClassNamePair> map = new HashMap<String, SourceUrlClassNamePair>(); try { if (file != null && file.length() > 0) { final DataInputStream is = new DataInputStream(new BufferedInputStream(new FileInputStream(file))); try { final int size = is.readInt(); for (int i = 0; i < size; i++) { final String _outputPath = CompilerIOUtil.readString(is); final String srcUrl = CompilerIOUtil.readString(is); final String className = CompilerIOUtil.readString(is); map.put(FileUtil.toSystemIndependentName(_outputPath), new SourceUrlClassNamePair(srcUrl, className)); } } finally { is.close(); } } } catch (FileNotFoundException ignored) { } catch (IOException e) { LOG.info(e); } return map; } private void ensureOutputStorageInitialized() { if (myOutputRootsStorage != null) { return; } final File rootsFile = getOutputRootsFile(); try { initOutputRootsFile(rootsFile); } catch (IOException e) { LOG.info(e); deleteStorageFiles(rootsFile); try { initOutputRootsFile(rootsFile); } catch (IOException e1) { LOG.error(e1); } } } private TIntObjectHashMap<Pair<Integer, Integer>> buildOutputRootsLayout(ProjectRef projRef) { final TIntObjectHashMap<Pair<Integer, Integer>> map = new TIntObjectHashMap<Pair<Integer, Integer>>(); for (Module module : ModuleManager.getInstance(projRef.get()).getModules()) { final CompilerModuleExtension manager = CompilerModuleExtension.getInstance(module); if (manager != null) { final VirtualFile output = manager.getCompilerOutputPath(); final int first = output != null? Math.abs(getFileId(output)) : -1; final VirtualFile testsOutput = manager.getCompilerOutputPathForTests(); final int second = testsOutput != null? Math.abs(getFileId(testsOutput)) : -1; map.put(getModuleId(module), new Pair<Integer, Integer>(first, second)); } } return map; } private void initOutputRootsFile(File rootsFile) throws IOException { myOutputRootsStorage = new PersistentHashMap<Integer, TIntObjectHashMap<Pair<Integer, Integer>>>(rootsFile, EnumeratorIntegerDescriptor.INSTANCE, new DataExternalizer<TIntObjectHashMap<Pair<Integer, Integer>>>() { public void save(DataOutput out, TIntObjectHashMap<Pair<Integer, Integer>> value) throws IOException { for (final TIntObjectIterator<Pair<Integer, Integer>> it = value.iterator(); it.hasNext();) { it.advance(); DataInputOutputUtil.writeINT(out, it.key()); final Pair<Integer, Integer> pair = it.value(); DataInputOutputUtil.writeINT(out, pair.first); DataInputOutputUtil.writeINT(out, pair.second); } } public TIntObjectHashMap<Pair<Integer, Integer>> read(DataInput in) throws IOException { final DataInputStream _in = (DataInputStream)in; final TIntObjectHashMap<Pair<Integer, Integer>> map = new TIntObjectHashMap<Pair<Integer, Integer>>(); while (_in.available() > 0) { final int key = DataInputOutputUtil.readINT(_in); final int first = DataInputOutputUtil.readINT(_in); final int second = DataInputOutputUtil.readINT(_in); map.put(key, new Pair<Integer, Integer>(first, second)); } return map; } }); } public void disposeComponent() { try { synchronized (myProjectOutputRoots) { myProjectOutputRoots.clear(); } } finally { synchronized (myDataLock) { myOutputsToDelete.clear(); } } try { myOutputRootsStorage.close(); } catch (IOException e) { LOG.info(e); deleteStorageFiles(getOutputRootsFile()); } } private static void savePathsToDelete(final File file, final Map<String, SourceUrlClassNamePair> outputs) { try { FileUtil.createParentDirs(file); final DataOutputStream os = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file))); try { if (outputs != null) { os.writeInt(outputs.size()); for (Map.Entry<String, SourceUrlClassNamePair> entry : outputs.entrySet()) { CompilerIOUtil.writeString(entry.getKey(), os); final SourceUrlClassNamePair pair = entry.getValue(); CompilerIOUtil.writeString(pair.getSourceUrl(), os); CompilerIOUtil.writeString(pair.getClassName(), os); } } else { os.writeInt(0); } } finally { os.close(); } } catch (IOException e) { LOG.error(e); } } @Nullable private static SourceFileInfo loadSourceInfo(final VirtualFile file) { try { final DataInputStream is = ourSourceFileAttribute.readAttribute(file); if (is != null) { try { return new SourceFileInfo(is); } finally { is.close(); } } } catch (RuntimeException e) { final Throwable cause = e.getCause(); if (cause instanceof IOException) { LOG.info(e); // ignore IOExceptions } else { throw e; } } catch (IOException ignored) { LOG.info(ignored); } return null; } public static void removeSourceInfo(VirtualFile file) { saveSourceInfo(file, new SourceFileInfo()); } private static void saveSourceInfo(VirtualFile file, SourceFileInfo descriptor) { final java.io.DataOutputStream out = ourSourceFileAttribute.writeAttribute(file); try { try { descriptor.save(out); } finally { out.close(); } } catch (IOException ignored) { LOG.info(ignored); } } @Nullable private static OutputFileInfo loadOutputInfo(final VirtualFile file) { try { final DataInputStream is = ourOutputFileAttribute.readAttribute(file); if (is != null) { try { return new OutputFileInfo(is); } finally { is.close(); } } } catch (RuntimeException e) { final Throwable cause = e.getCause(); if (cause instanceof IOException) { LOG.info(e); // ignore IO exceptions } else { throw e; } } catch (IOException ignored) { LOG.info(ignored); } return null; } private static void saveOutputInfo(VirtualFile file, OutputFileInfo descriptor) { final java.io.DataOutputStream out = ourOutputFileAttribute.writeAttribute(file); try { try { descriptor.save(out); } finally { out.close(); } } catch (IOException ignored) { LOG.info(ignored); } } private int getProjectId(Project project) { try { return FSRecords.getNames().enumerate(CompilerPaths.getCompilerSystemDirectoryName(project)); } catch (IOException e) { LOG.info(e); } return -1; } private int getModuleId(Module module) { try { return FSRecords.getNames().enumerate(module.getName().toLowerCase(Locale.US)); } catch (IOException e) { LOG.info(e); } return -1; } private static class OutputFileInfo { private final int mySourcePath; private final int myClassName; OutputFileInfo(final String sourcePath, @Nullable String className) throws IOException { final PersistentStringEnumerator symtable = FSRecords.getNames(); mySourcePath = symtable.enumerate(sourcePath); myClassName = className != null? symtable.enumerate(className) : -1; } OutputFileInfo(final DataInput in) throws IOException { mySourcePath = in.readInt(); myClassName = in.readInt(); } String getSourceFilePath() { try { return FSRecords.getNames().valueOf(mySourcePath); } catch (IOException e) { LOG.info(e); } return null; } @Nullable public String getClassName() { try { return myClassName < 0? null : FSRecords.getNames().valueOf(myClassName); } catch (IOException e) { LOG.info(e); } return null; } public void save(final DataOutput out) throws IOException { out.writeInt(mySourcePath); out.writeInt(myClassName); } } private static class SourceFileInfo { private TIntLongHashMap myTimestamps; // ProjectId -> last compiled stamp private TIntObjectHashMap<Serializable> myProjectToOutputPathMap; // ProjectId -> either a single output path or a set of output paths private SourceFileInfo() { } private SourceFileInfo(@NotNull DataInput in) throws IOException { final int projCount = in.readInt(); for (int idx = 0; idx < projCount; idx++) { final int projectId = in.readInt(); final long stamp = in.readLong(); updateTimestamp(projectId, stamp); final int pathsCount = in.readInt(); for (int i = 0; i < pathsCount; i++) { final int path = in.readInt(); addOutputPath(projectId, path); } } } public void save(@NotNull final DataOutput out) throws IOException { final int[] projects = getProjectIds().toArray(); out.writeInt(projects.length); for (int projectId : projects) { out.writeInt(projectId); out.writeLong(getTimestamp(projectId)); final Object value = myProjectToOutputPathMap != null? myProjectToOutputPathMap.get(projectId) : null; if (value instanceof Integer) { out.writeInt(1); out.writeInt(((Integer)value).intValue()); } else if (value instanceof TIntHashSet) { final TIntHashSet set = (TIntHashSet)value; out.writeInt(set.size()); final IOException[] ex = new IOException[] {null}; set.forEach(new TIntProcedure() { public boolean execute(final int value) { try { out.writeInt(value); return true; } catch (IOException e) { ex[0] = e; return false; } } }); if (ex[0] != null) { throw ex[0]; } } else { out.writeInt(0); } } } private void updateTimestamp(final int projectId, final long stamp) { if (stamp > 0L) { if (myTimestamps == null) { myTimestamps = new TIntLongHashMap(1, 0.98f); } myTimestamps.put(projectId, stamp); } else { if (myTimestamps != null) { myTimestamps.remove(projectId); } } } TIntHashSet getProjectIds() { final TIntHashSet result = new TIntHashSet(); if (myTimestamps != null) { result.addAll(myTimestamps.keys()); } if (myProjectToOutputPathMap != null) { result.addAll(myProjectToOutputPathMap.keys()); } return result; } private void addOutputPath(final int projectId, String outputPath) { try { addOutputPath(projectId, FSRecords.getNames().enumerate(outputPath)); } catch (IOException e) { LOG.info(e); } } private void addOutputPath(final int projectId, final int outputPath) { if (myProjectToOutputPathMap == null) { myProjectToOutputPathMap = new TIntObjectHashMap<Serializable>(1, 0.98f); myProjectToOutputPathMap.put(projectId, outputPath); } else { final Object val = myProjectToOutputPathMap.get(projectId); if (val == null) { myProjectToOutputPathMap.put(projectId, outputPath); } else { TIntHashSet set; if (val instanceof Integer) { set = new TIntHashSet(); set.add(((Integer)val).intValue()); myProjectToOutputPathMap.put(projectId, set); } else { assert val instanceof TIntHashSet; set = (TIntHashSet)val; } set.add(outputPath); } } } public boolean clearPaths(final int projectId){ if (myProjectToOutputPathMap != null) { final Serializable removed = myProjectToOutputPathMap.remove(projectId); return removed != null; } return false; } long getTimestamp(final int projectId) { return myTimestamps == null? -1L : myTimestamps.get(projectId); } void processOutputPaths(final int projectId, final Proc proc){ if (myProjectToOutputPathMap != null) { try { final PersistentStringEnumerator symtable = FSRecords.getNames(); final Object val = myProjectToOutputPathMap.get(projectId); if (val instanceof Integer) { proc.execute(projectId, symtable.valueOf(((Integer)val).intValue())); } else if (val instanceof TIntHashSet) { ((TIntHashSet)val).forEach(new TIntProcedure() { public boolean execute(final int value) { try { proc.execute(projectId, symtable.valueOf(value)); return true; } catch (IOException e) { LOG.info(e); return false; } } }); } } catch (IOException e) { LOG.info(e); } } } boolean isAssociated(int projectId, String outputPath) { if (myProjectToOutputPathMap != null) { try { final Object val = myProjectToOutputPathMap.get(projectId); if (val instanceof Integer) { return FileUtil.pathsEqual(outputPath, FSRecords.getNames().valueOf(((Integer)val).intValue())); } if (val instanceof TIntHashSet) { final int _outputPath = FSRecords.getNames().enumerate(outputPath); return ((TIntHashSet)val).contains(_outputPath); } } catch (IOException e) { LOG.info(e); } } return false; } } public List<String> getCompiledClassNames(VirtualFile srcFile, Project project) { final SourceFileInfo info = loadSourceInfo(srcFile); if (info == null) { return Collections.emptyList(); } final ArrayList<String> result = new ArrayList<String>(); info.processOutputPaths(getProjectId(project), new Proc() { @Override public boolean execute(int projectId, String outputPath) { VirtualFile clsFile = LocalFileSystem.getInstance().findFileByPath(outputPath); if (clsFile != null) { OutputFileInfo outputInfo = loadOutputInfo(clsFile); if (outputInfo != null) { ContainerUtil.addIfNotNull(result, outputInfo.getClassName()); } } return true; } }); return result; } private interface FileProcessor { void execute(VirtualFile file); } private static void processRecursively(VirtualFile file, boolean dbOnly, final FileProcessor processor) { if (file.getFileSystem() instanceof LocalFileSystem) { if (file.isDirectory()) { if (dbOnly) { for (VirtualFile child : ((NewVirtualFile)file).iterInDbChildren()) { processRecursively(child, true, processor); } } else { for (VirtualFile child : file.getChildren()) { processRecursively(child, false, processor); } } } else { processor.execute(file); } } } // made public for tests public void scanSourceContent(final ProjectRef projRef, final Collection<VirtualFile> roots, final int totalRootCount, final boolean isNewRoots) { if (roots.isEmpty()) { return; } final int projectId = getProjectId(projRef.get()); if (LOG.isDebugEnabled()) { LOG.debug("Scanning source content for project projectId=" + projectId + "; url=" + projRef.get().getPresentableUrl()); } final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(projRef.get()).getFileIndex(); final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); int processed = 0; for (VirtualFile srcRoot : roots) { if (indicator != null) { projRef.get(); indicator.setText2(srcRoot.getPresentableUrl()); indicator.setFraction(++processed / (double)totalRootCount); } if (isNewRoots) { fileIndex.iterateContentUnderDirectory(srcRoot, new ContentIterator() { public boolean processFile(final VirtualFile file) { if (!file.isDirectory()) { if (!isMarkedForRecompilation(projectId, Math.abs(getFileId(file)))) { final SourceFileInfo srcInfo = loadSourceInfo(file); if (srcInfo == null || srcInfo.getTimestamp(projectId) != file.getTimeStamp()) { addSourceForRecompilation(projectId, file, srcInfo); } } } else { projRef.get(); } return true; } }); } else { final FileTypeManager fileTypeManager = FileTypeManager.getInstance(); new Object() { void processFile(VirtualFile file) { if (fileTypeManager.isFileIgnored(file)) { return; } final int fileId = getFileId(file); if (fileId > 0 /*file is valid*/) { if (file.isDirectory()) { projRef.get(); for (VirtualFile child : file.getChildren()) { processFile(child); } } else { if (!isMarkedForRecompilation(projectId, fileId)) { final SourceFileInfo srcInfo = loadSourceInfo(file); if (srcInfo != null) { addSourceForRecompilation(projectId, file, srcInfo); } } } } } }.processFile(srcRoot); } } } public void ensureInitializationCompleted(Project project, ProgressIndicator indicator) { final int id = getProjectId(project); synchronized (myAsyncScanLock) { while (myInitInProgress.containsKey(id)) { if (!project.isOpen() || project.isDisposed() || (indicator != null && indicator.isCanceled())) { // makes no sense to continue waiting break; } try { myAsyncScanLock.wait(500); } catch (InterruptedException ignored) { break; } } } } private void markOldOutputRoots(final ProjectRef projRef, final TIntObjectHashMap<Pair<Integer, Integer>> currentLayout) { final int projectId = getProjectId(projRef.get()); final TIntHashSet rootsToMark = new TIntHashSet(); synchronized (myProjectOutputRoots) { final TIntObjectHashMap<Pair<Integer, Integer>> oldLayout = myProjectOutputRoots.get(projectId); for (final TIntObjectIterator<Pair<Integer, Integer>> it = oldLayout.iterator(); it.hasNext();) { it.advance(); final Pair<Integer, Integer> currentRoots = currentLayout.get(it.key()); final Pair<Integer, Integer> oldRoots = it.value(); if (shouldMark(oldRoots.first, currentRoots != null? currentRoots.first : -1)) { rootsToMark.add(oldRoots.first); } if (shouldMark(oldRoots.second, currentRoots != null? currentRoots.second : -1)) { rootsToMark.add(oldRoots.second); } } } for (TIntIterator it = rootsToMark.iterator(); it.hasNext();) { final int id = it.next(); final VirtualFile outputRoot = findFileById(id); if (outputRoot != null) { processOldOutputRoot(projectId, outputRoot); } } } private static boolean shouldMark(Integer oldOutputRoot, Integer currentOutputRoot) { return oldOutputRoot != null && oldOutputRoot.intValue() > 0 && !Comparing.equal(oldOutputRoot, currentOutputRoot); } private void processOldOutputRoot(int projectId, VirtualFile outputRoot) { // recursively mark all corresponding sources for recompilation if (outputRoot.isDirectory()) { for (VirtualFile child : outputRoot.getChildren()) { processOldOutputRoot(projectId, child); } } else { // todo: possible optimization - process only those outputs that are not marked for deletion yet final OutputFileInfo outputInfo = loadOutputInfo(outputRoot); if (outputInfo != null) { final String srcPath = outputInfo.getSourceFilePath(); final VirtualFile srcFile = srcPath != null? LocalFileSystem.getInstance().findFileByPath(srcPath) : null; if (srcFile != null) { loadInfoAndAddSourceForRecompilation(projectId, srcFile); } } } } public void scanSourcesForCompilableFiles(final Project project) { final int projectId = getProjectId(project); if (isSuspended(projectId)) { return; } startAsyncScan(projectId); StartupManager.getInstance(project).runWhenProjectIsInitialized(new Runnable() { public void run() { new Task.Backgroundable(project, CompilerBundle.message("compiler.initial.scanning.progress.text"), false) { public void run(@NotNull final ProgressIndicator indicator) { final ProjectRef projRef = new ProjectRef(project); if (LOG.isDebugEnabled()) { LOG.debug("Initial sources scan for project hash=" + projectId + "; url="+ projRef.get().getPresentableUrl()); } try { final IntermediateOutputCompiler[] compilers = CompilerManager.getInstance(projRef.get()).getCompilers(IntermediateOutputCompiler.class); final Set<VirtualFile> intermediateRoots = new HashSet<VirtualFile>(); if (compilers.length > 0) { final Module[] modules = ModuleManager.getInstance(projRef.get()).getModules(); for (IntermediateOutputCompiler compiler : compilers) { for (Module module : modules) { if (module.isDisposed()) { continue; } final VirtualFile outputRoot = LocalFileSystem.getInstance().refreshAndFindFileByPath(CompilerPaths.getGenerationOutputPath(compiler, module, false)); if (outputRoot != null) { intermediateRoots.add(outputRoot); } final VirtualFile testsOutputRoot = LocalFileSystem.getInstance().refreshAndFindFileByPath(CompilerPaths.getGenerationOutputPath(compiler, module, true)); if (testsOutputRoot != null) { intermediateRoots.add(testsOutputRoot); } } } } final List<VirtualFile> projectRoots = Arrays.asList(ProjectRootManager.getInstance(projRef.get()).getContentSourceRoots()); final int totalRootsCount = projectRoots.size() + intermediateRoots.size(); scanSourceContent(projRef, projectRoots, totalRootsCount, true); if (!intermediateRoots.isEmpty()) { final FileProcessor processor = new FileProcessor() { public void execute(final VirtualFile file) { if (!isMarkedForRecompilation(projectId, Math.abs(getFileId(file)))) { final SourceFileInfo srcInfo = loadSourceInfo(file); if (srcInfo == null || srcInfo.getTimestamp(projectId) != file.getTimeStamp()) { addSourceForRecompilation(projectId, file, srcInfo); } } } }; int processed = projectRoots.size(); for (VirtualFile root : intermediateRoots) { projRef.get(); indicator.setText2(root.getPresentableUrl()); indicator.setFraction(++processed / (double)totalRootsCount); processRecursively(root, false, processor); } } markOldOutputRoots(projRef, buildOutputRootsLayout(projRef)); } catch (ProjectRef.ProjectClosedException swallowed) { } finally { terminateAsyncScan(projectId, false); } } }.queue(); } }); } private void terminateAsyncScan(int projectId, final boolean clearCounter) { synchronized (myAsyncScanLock) { int counter = myInitInProgress.remove(projectId); if (clearCounter) { myAsyncScanLock.notifyAll(); } else { if (--counter > 0) { myInitInProgress.put(projectId, counter); } else { myAsyncScanLock.notifyAll(); } } } } private void startAsyncScan(final int projectId) { synchronized (myAsyncScanLock) { int counter = myInitInProgress.get(projectId); counter = (counter > 0)? counter + 1 : 1; myInitInProgress.put(projectId, counter); myAsyncScanLock.notifyAll(); } } private class MyProjectManagerListener extends ProjectManagerAdapter { final Map<Project, MessageBusConnection> myConnections = new HashMap<Project, MessageBusConnection>(); public void projectOpened(final Project project) { final MessageBusConnection conn = project.getMessageBus().connect(); myConnections.put(project, conn); final ProjectRef projRef = new ProjectRef(project); final int projectId = getProjectId(project); if (CompilerWorkspaceConfiguration.getInstance(project).useOutOfProcessBuild()) { suspendProject(project); } else { watchProject(project); } conn.subscribe(ProjectTopics.PROJECT_ROOTS, new ModuleRootListener() { private VirtualFile[] myRootsBefore; private Alarm myAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD, project); public void beforeRootsChange(final ModuleRootEvent event) { if (isSuspended(projectId)) { return; } try { myRootsBefore = ProjectRootManager.getInstance(projRef.get()).getContentSourceRoots(); } catch (ProjectRef.ProjectClosedException e) { myRootsBefore = null; } } public void rootsChanged(final ModuleRootEvent event) { if (isSuspended(projectId)) { return; } if (LOG.isDebugEnabled()) { LOG.debug("Before roots changed for projectId=" + projectId + "; url="+ project.getPresentableUrl()); } try { final VirtualFile[] rootsBefore = myRootsBefore; myRootsBefore = null; final VirtualFile[] rootsAfter = ProjectRootManager.getInstance(projRef.get()).getContentSourceRoots(); final Set<VirtualFile> newRoots = new HashSet<VirtualFile>(); final Set<VirtualFile> oldRoots = new HashSet<VirtualFile>(); { if (rootsAfter.length > 0) { ContainerUtil.addAll(newRoots, rootsAfter); } if (rootsBefore != null) { newRoots.removeAll(Arrays.asList(rootsBefore)); } } { if (rootsBefore != null) { ContainerUtil.addAll(oldRoots, rootsBefore); } if (!oldRoots.isEmpty() && rootsAfter.length > 0) { oldRoots.removeAll(Arrays.asList(rootsAfter)); } } myAlarm.cancelAllRequests(); // need alarm to deal with multiple rootsChanged events myAlarm.addRequest(new Runnable() { public void run() { startAsyncScan(projectId); new Task.Backgroundable(project, CompilerBundle.message("compiler.initial.scanning.progress.text"), false) { public void run(@NotNull final ProgressIndicator indicator) { try { if (newRoots.size() > 0) { scanSourceContent(projRef, newRoots, newRoots.size(), true); } if (oldRoots.size() > 0) { scanSourceContent(projRef, oldRoots, oldRoots.size(), false); } markOldOutputRoots(projRef, buildOutputRootsLayout(projRef)); } catch (ProjectRef.ProjectClosedException swallowed) { // ignored } finally { terminateAsyncScan(projectId, false); } } }.queue(); } }, 500, ModalityState.NON_MODAL); } catch (ProjectRef.ProjectClosedException e) { LOG.info(e); } } }); scanSourcesForCompilableFiles(project); } public void projectClosed(final Project project) { final int projectId = getProjectId(project); terminateAsyncScan(projectId, true); myConnections.remove(project).disconnect(); synchronized (myDataLock) { mySourcesToRecompile.remove(projectId); myOutputsToDelete.remove(projectId); // drop cache to save memory } } } private class MyVfsListener extends VirtualFileAdapter { public void propertyChanged(final VirtualFilePropertyEvent event) { if (VirtualFile.PROP_NAME.equals(event.getPropertyName())) { final VirtualFile eventFile = event.getFile(); final VirtualFile parent = event.getParent(); if (parent != null) { final String oldName = (String)event.getOldValue(); final String root = parent.getPath() + "/" + oldName; final Set<String> toMark; if (eventFile.isDirectory()) { toMark = new HashSet<String>(); new Object() { void process(VirtualFile file, String filePath) { if (file.isDirectory()) { for (VirtualFile child : file.getChildren()) { process(child, filePath + "/" + child.getName()); } } else { toMark.add(filePath); } } }.process(eventFile, root); } else { toMark = Collections.singleton(root); } notifyFilesDeleted(toMark); } markDirtyIfSource(eventFile, false); } } public void contentsChanged(final VirtualFileEvent event) { markDirtyIfSource(event.getFile(), false); } public void fileCreated(final VirtualFileEvent event) { processNewFile(event.getFile(), true); } public void fileCopied(final VirtualFileCopyEvent event) { processNewFile(event.getFile(), true); } public void fileMoved(VirtualFileMoveEvent event) { processNewFile(event.getFile(), true); } public void beforeFileDeletion(final VirtualFileEvent event) { final VirtualFile eventFile = event.getFile(); if ((LOG.isDebugEnabled() && eventFile.isDirectory()) || ourDebugMode) { final String message = "Processing file deletion: " + eventFile.getPresentableUrl(); LOG.debug(message); if (ourDebugMode) { System.out.println(message); } } final Set<String> pathsToMark = new HashSet<String>(); processRecursively(eventFile, true, new FileProcessor() { private final TIntArrayList myAssociatedProjectIds = new TIntArrayList(); public void execute(final VirtualFile file) { final String filePath = file.getPath(); pathsToMark.add(filePath); myAssociatedProjectIds.clear(); try { final OutputFileInfo outputInfo = loadOutputInfo(file); if (outputInfo != null) { final String srcPath = outputInfo.getSourceFilePath(); final VirtualFile srcFile = srcPath != null? LocalFileSystem.getInstance().findFileByPath(srcPath) : null; if (srcFile != null) { final SourceFileInfo srcInfo = loadSourceInfo(srcFile); if (srcInfo != null) { final boolean srcWillBeDeleted = VfsUtil.isAncestor(eventFile, srcFile, false); for (int projectId : srcInfo.getProjectIds().toArray()) { if (isSuspended(projectId)) { continue; } if (srcInfo.isAssociated(projectId, filePath)) { myAssociatedProjectIds.add(projectId); if (srcWillBeDeleted) { if (LOG.isDebugEnabled() || ourDebugMode) { final String message = "Unschedule recompilation because of deletion " + srcFile.getPresentableUrl(); LOG.debug(message); if (ourDebugMode) { System.out.println(message); } } removeSourceForRecompilation(projectId, Math.abs(getFileId(srcFile))); } else { addSourceForRecompilation(projectId, srcFile, srcInfo); } } } } } } final SourceFileInfo srcInfo = loadSourceInfo(file); if (srcInfo != null) { final TIntHashSet projects = srcInfo.getProjectIds(); if (!projects.isEmpty()) { final ScheduleOutputsForDeletionProc deletionProc = new ScheduleOutputsForDeletionProc(file.getUrl()); deletionProc.setRootBeingDeleted(eventFile); final int sourceFileId = Math.abs(getFileId(file)); for (int projectId : projects.toArray()) { if (isSuspended(projectId)) { continue; } if (srcInfo.isAssociated(projectId, filePath)) { myAssociatedProjectIds.add(projectId); } // mark associated outputs for deletion srcInfo.processOutputPaths(projectId, deletionProc); if (LOG.isDebugEnabled() || ourDebugMode) { final String message = "Unschedule recompilation because of deletion " + file.getPresentableUrl(); LOG.debug(message); if (ourDebugMode) { System.out.println(message); } } removeSourceForRecompilation(projectId, sourceFileId); } } } } finally { // it is important that update of myOutputsToDelete is done at the end // otherwise the filePath of the file that is about to be deleted may be re-scheduled for deletion in addSourceForRecompilation() myAssociatedProjectIds.forEach(new TIntProcedure() { public boolean execute(int projectId) { unmarkOutputPathForDeletion(projectId, filePath); return true; } }); } } }); notifyFilesDeleted(pathsToMark); } public void beforeFileMovement(final VirtualFileMoveEvent event) { markDirtyIfSource(event.getFile(), true); } private void markDirtyIfSource(final VirtualFile file, final boolean fromMove) { final Set<String> pathsToMark = new HashSet<String>(); processRecursively(file, false, new FileProcessor() { public void execute(final VirtualFile file) { pathsToMark.add(file.getPath()); final SourceFileInfo srcInfo = file.isValid()? loadSourceInfo(file) : null; if (srcInfo != null) { for (int projectId : srcInfo.getProjectIds().toArray()) { if (isSuspended(projectId)) { if (srcInfo.clearPaths(projectId)) { srcInfo.updateTimestamp(projectId, -1L); saveSourceInfo(file, srcInfo); } } else { addSourceForRecompilation(projectId, file, srcInfo); // when the file is moved to a new location, we should 'forget' previous associations if (fromMove) { if (srcInfo.clearPaths(projectId)) { saveSourceInfo(file, srcInfo); } } } } } else { processNewFile(file, false); } } }); if (fromMove) { notifyFilesDeleted(pathsToMark); } else { notifyFilesChanged(pathsToMark); } } private void processNewFile(final VirtualFile file, final boolean notifyServer) { final Set<String> pathsToMark = notifyServer ? new HashSet<String>() : Collections.<String>emptySet(); ApplicationManager.getApplication().runReadAction(new Runnable() { // need read action to ensure that the project was not disposed during the iteration over the project list public void run() { for (final Project project : myProjectManager.getOpenProjects()) { if (!project.isInitialized()) { continue; // the content of this project will be scanned during its post-startup activities } final int projectId = getProjectId(project); final boolean projectSuspended = isSuspended(projectId); final ProjectRootManager rootManager = ProjectRootManager.getInstance(project); if (rootManager.getFileIndex().isInSourceContent(file)) { final TranslatingCompiler[] translators = CompilerManager.getInstance(project).getCompilers(TranslatingCompiler.class); processRecursively(file, false, new FileProcessor() { public void execute(final VirtualFile file) { if (notifyServer) { pathsToMark.add(file.getPath()); } if (!projectSuspended && isCompilable(file)) { loadInfoAndAddSourceForRecompilation(projectId, file); } } boolean isCompilable(VirtualFile file) { for (TranslatingCompiler translator : translators) { if (translator.isCompilableFile(file, DummyCompileContext.getInstance())) { return true; } } return false; } }); } else { if (!projectSuspended && belongsToIntermediateSources(file, project)) { processRecursively(file, false, new FileProcessor() { public void execute(final VirtualFile file) { loadInfoAndAddSourceForRecompilation(projectId, file); } }); } } } } }); if (notifyServer) { notifyFilesChanged(pathsToMark); } } } private static void notifyFilesChanged(Collection<String> paths) { if (!paths.isEmpty()) { CompileServerManager.getInstance().notifyFilesChanged(paths); BuildManager.getInstance().notifyFilesChanged(paths); } } private static void notifyFilesDeleted(Collection<String> paths) { if (!paths.isEmpty()) { CompileServerManager.getInstance().notifyFilesDeleted(paths); BuildManager.getInstance().notifyFilesDeleted(paths); } } private boolean belongsToIntermediateSources(VirtualFile file, Project project) { return FileUtil.isAncestor(myGeneratedDataPaths.get(project), new File(file.getPath()), true); } private void loadInfoAndAddSourceForRecompilation(final int projectId, final VirtualFile srcFile) { addSourceForRecompilation(projectId, srcFile, loadSourceInfo(srcFile)); } private void addSourceForRecompilation(final int projectId, final VirtualFile srcFile, @Nullable final SourceFileInfo srcInfo) { final boolean alreadyMarked; synchronized (myDataLock) { TIntHashSet set = mySourcesToRecompile.get(projectId); if (set == null) { set = new TIntHashSet(); mySourcesToRecompile.put(projectId, set); } alreadyMarked = !set.add(Math.abs(getFileId(srcFile))); if (!alreadyMarked && (LOG.isDebugEnabled() || ourDebugMode)) { final String message = "Scheduled recompilation " + srcFile.getPresentableUrl(); LOG.debug(message); if (ourDebugMode) { System.out.println(message); } } } if (!alreadyMarked && srcInfo != null) { srcInfo.updateTimestamp(projectId, -1L); srcInfo.processOutputPaths(projectId, new ScheduleOutputsForDeletionProc(srcFile.getUrl())); saveSourceInfo(srcFile, srcInfo); } } private void removeSourceForRecompilation(final int projectId, final int srcId) { synchronized (myDataLock) { TIntHashSet set = mySourcesToRecompile.get(projectId); if (set != null) { set.remove(srcId); if (set.isEmpty()) { mySourcesToRecompile.remove(projectId); } } } } public boolean isMarkedForCompilation(Project project, VirtualFile file) { return isMarkedForRecompilation(getProjectId(project), getFileId(file)); } private boolean isMarkedForRecompilation(int projectId, final int srcId) { synchronized (myDataLock) { final TIntHashSet set = mySourcesToRecompile.get(projectId); return set != null && set.contains(srcId); } } private interface Proc { boolean execute(final int projectId, String outputPath); } private class ScheduleOutputsForDeletionProc implements Proc { private final String mySrcUrl; private final LocalFileSystem myFileSystem; @Nullable private VirtualFile myRootBeingDeleted; private ScheduleOutputsForDeletionProc(final String srcUrl) { mySrcUrl = srcUrl; myFileSystem = LocalFileSystem.getInstance(); } public void setRootBeingDeleted(@Nullable VirtualFile rootBeingDeleted) { myRootBeingDeleted = rootBeingDeleted; } public boolean execute(final int projectId, String outputPath) { final VirtualFile outFile = myFileSystem.findFileByPath(outputPath); if (outFile != null) { // not deleted yet if (myRootBeingDeleted != null && VfsUtil.isAncestor(myRootBeingDeleted, outFile, false)) { unmarkOutputPathForDeletion(projectId, outputPath); } else { final OutputFileInfo outputInfo = loadOutputInfo(outFile); final String classname = outputInfo != null? outputInfo.getClassName() : null; markOutputPathForDeletion(projectId, outputPath, classname, mySrcUrl); } } return true; } } private void markOutputPathForDeletion(final int projectId, final String outputPath, final String classname, final String srcUrl) { final SourceUrlClassNamePair pair = new SourceUrlClassNamePair(srcUrl, classname); synchronized (myDataLock) { final Outputs outputs = myOutputsToDelete.get(projectId); try { outputs.put(outputPath, pair); if (LOG.isDebugEnabled() || ourDebugMode) { final String message = "ADD path to delete: " + outputPath + "; source: " + srcUrl; LOG.debug(message); if (ourDebugMode) { System.out.println(message); } } } finally { outputs.release(); } } } private void unmarkOutputPathForDeletion(final int projectId, String outputPath) { synchronized (myDataLock) { final Outputs outputs = myOutputsToDelete.get(projectId); try { final SourceUrlClassNamePair val = outputs.remove(outputPath); if (val != null) { if (LOG.isDebugEnabled() || ourDebugMode) { final String message = "REMOVE path to delete: " + outputPath; LOG.debug(message); if (ourDebugMode) { System.out.println(message); } } } } finally { outputs.release(); } } } public static final class ProjectRef extends Ref<Project> { static class ProjectClosedException extends RuntimeException { } public ProjectRef(Project project) { super(project); } public Project get() { final Project project = super.get(); if (project != null && project.isDisposed()) { throw new ProjectClosedException(); } return project; } } private static class Outputs { private boolean myIsDirty = false; @Nullable private final File myStoreFile; private final Map<String, SourceUrlClassNamePair> myMap; private final AtomicInteger myRefCount = new AtomicInteger(1); Outputs(@Nullable File storeFile, Map<String, SourceUrlClassNamePair> map) { myStoreFile = storeFile; myMap = map; } public Set<Map.Entry<String, SourceUrlClassNamePair>> getEntries() { return Collections.unmodifiableSet(myMap.entrySet()); } public void put(String outputPath, SourceUrlClassNamePair pair) { if (myStoreFile == null) { return; } if (pair == null) { remove(outputPath); } else { myMap.put(outputPath, pair); myIsDirty = true; } } public SourceUrlClassNamePair remove(String outputPath) { if (myStoreFile == null) { return null; } final SourceUrlClassNamePair removed = myMap.remove(outputPath); myIsDirty |= removed != null; return removed; } void allocate() { myRefCount.incrementAndGet(); } public void release() { if (myRefCount.decrementAndGet() == 0) { if (myIsDirty && myStoreFile != null) { savePathsToDelete(myStoreFile, myMap); } } } } }
java/compiler/impl/src/com/intellij/compiler/impl/TranslatingCompilerFilesMonitor.java
/* * Copyright 2000-2009 JetBrains s.r.o. * * 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.intellij.compiler.impl; import com.intellij.ProjectTopics; import com.intellij.compiler.CompileServerManager; import com.intellij.compiler.CompilerConfiguration; import com.intellij.compiler.CompilerIOUtil; import com.intellij.compiler.CompilerWorkspaceConfiguration; import com.intellij.compiler.make.MakeUtil; import com.intellij.compiler.server.BuildManager; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.compiler.*; import com.intellij.openapi.compiler.ex.CompileContextEx; import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.project.ProjectManagerAdapter; import com.intellij.openapi.roots.*; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.*; import com.intellij.openapi.vfs.newvfs.FileAttribute; import com.intellij.openapi.vfs.newvfs.ManagingFS; import com.intellij.openapi.vfs.newvfs.NewVirtualFile; import com.intellij.openapi.vfs.newvfs.persistent.FSRecords; import com.intellij.openapi.vfs.newvfs.persistent.PersistentFS; import com.intellij.util.Alarm; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.SLRUCache; import com.intellij.util.indexing.FileBasedIndex; import com.intellij.util.indexing.IndexInfrastructure; import com.intellij.util.io.*; import com.intellij.util.io.DataOutputStream; import com.intellij.util.messages.MessageBusConnection; import gnu.trove.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.*; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; /** * @author Eugene Zhuravlev * Date: Jun 3, 2008 * * A source file is scheduled for recompilation if * 1. its timestamp has changed * 2. one of its corresponding output files was deleted * 3. output root of containing module has changed * * An output file is scheduled for deletion if: * 1. corresponding source file has been scheduled for recompilation (see above) * 2. corresponding source file has been deleted */ public class TranslatingCompilerFilesMonitor implements ApplicationComponent { private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.impl.TranslatingCompilerFilesMonitor"); public static boolean ourDebugMode = false; private static final FileAttribute ourSourceFileAttribute = new FileAttribute("_make_source_file_info_", 3); private static final FileAttribute ourOutputFileAttribute = new FileAttribute("_make_output_file_info_", 3); private static final Key<Map<String, VirtualFile>> SOURCE_FILES_CACHE = Key.create("_source_url_to_vfile_cache_"); private final Object myDataLock = new Object(); private final TIntHashSet mySuspendedProjects = new TIntHashSet(); // projectId for allprojects that should not be monitored private final TIntObjectHashMap<TIntHashSet> mySourcesToRecompile = new TIntObjectHashMap<TIntHashSet>(); // ProjectId->set of source file paths private PersistentHashMap<Integer, TIntObjectHashMap<Pair<Integer, Integer>>> myOutputRootsStorage; // ProjectId->map[moduleId->Pair(outputDirId, testOutputDirId)] // Map: projectId -> Map{output path -> [sourceUrl; classname]} private final SLRUCache<Integer, Outputs> myOutputsToDelete = new SLRUCache<Integer, Outputs>(3, 3) { @Override public Outputs getIfCached(Integer key) { final Outputs value = super.getIfCached(key); if (value != null) { value.allocate(); } return value; } @NotNull @Override public Outputs get(Integer key) { final Outputs value = super.get(key); value.allocate(); return value; } @NotNull @Override public Outputs createValue(Integer key) { try { final String dirName = FSRecords.getNames().valueOf(key); final File storeFile; if (StringUtil.isEmpty(dirName)) { storeFile = null; } else { final File compilerCacheDir = CompilerPaths.getCacheStoreDirectory(dirName); storeFile = compilerCacheDir.exists()? new File(compilerCacheDir, "paths_to_delete.dat") : null; } return new Outputs(storeFile, loadPathsToDelete(storeFile)); } catch (IOException e) { LOG.info(e); return new Outputs(null, new HashMap<String, SourceUrlClassNamePair>()); } } @Override protected void onDropFromCache(Integer key, Outputs value) { value.release(); } }; private final SLRUCache<Project, File> myGeneratedDataPaths = new SLRUCache<Project, File>(8, 8) { @NotNull public File createValue(final Project project) { Disposer.register(project, new Disposable() { public void dispose() { myGeneratedDataPaths.remove(project); } }); return CompilerPaths.getGeneratedDataDirectory(project); } }; private final SLRUCache<Integer, TIntObjectHashMap<Pair<Integer, Integer>>> myProjectOutputRoots = new SLRUCache<Integer, TIntObjectHashMap<Pair<Integer, Integer>>>(2, 2) { protected void onDropFromCache(Integer key, TIntObjectHashMap<Pair<Integer, Integer>> value) { try { myOutputRootsStorage.put(key, value); } catch (IOException e) { LOG.info(e); } } @NotNull public TIntObjectHashMap<Pair<Integer, Integer>> createValue(Integer key) { TIntObjectHashMap<Pair<Integer, Integer>> map = null; try { ensureOutputStorageInitialized(); map = myOutputRootsStorage.get(key); } catch (IOException e) { LOG.info(e); } return map != null? map : new TIntObjectHashMap<Pair<Integer, Integer>>(); } }; private final ProjectManager myProjectManager; private final TIntIntHashMap myInitInProgress = new TIntIntHashMap(); // projectId for successfully initialized projects private final Object myAsyncScanLock = new Object(); public TranslatingCompilerFilesMonitor(VirtualFileManager vfsManager, ProjectManager projectManager, Application application) { myProjectManager = projectManager; projectManager.addProjectManagerListener(new MyProjectManagerListener()); vfsManager.addVirtualFileListener(new MyVfsListener(), application); } public static TranslatingCompilerFilesMonitor getInstance() { return ApplicationManager.getApplication().getComponent(TranslatingCompilerFilesMonitor.class); } public void suspendProject(Project project) { final int projectId = getProjectId(project); synchronized (myDataLock) { if (!mySuspendedProjects.add(projectId)) { return; } FileUtil.createIfDoesntExist(CompilerPaths.getRebuildMarkerFile(project)); // cleanup internal structures to free memory mySourcesToRecompile.remove(projectId); myOutputsToDelete.remove(projectId); myGeneratedDataPaths.remove(project); } synchronized (myProjectOutputRoots) { myProjectOutputRoots.remove(projectId); } try { myOutputRootsStorage.remove(projectId); } catch (IOException e) { LOG.info(e); } } public void watchProject(Project project) { synchronized (myDataLock) { mySuspendedProjects.remove(getProjectId(project)); } } public boolean isSuspended(Project project) { return isSuspended(getProjectId(project)); } public boolean isSuspended(int projectId) { synchronized (myDataLock) { return mySuspendedProjects.contains(projectId); } } @Nullable public static VirtualFile getSourceFileByOutput(VirtualFile outputFile) { final OutputFileInfo outputFileInfo = loadOutputInfo(outputFile); if (outputFileInfo != null) { final String path = outputFileInfo.getSourceFilePath(); if (path != null) { return LocalFileSystem.getInstance().findFileByPath(path); } } return null; } public void collectFiles(CompileContext context, final TranslatingCompiler compiler, Iterator<VirtualFile> scopeSrcIterator, boolean forceCompile, final boolean isRebuild, Collection<VirtualFile> toCompile, Collection<Trinity<File, String, Boolean>> toDelete) { final Project project = context.getProject(); final int projectId = getProjectId(project); final CompilerConfiguration configuration = CompilerConfiguration.getInstance(project); final boolean _forceCompile = forceCompile || isRebuild; final Set<VirtualFile> selectedForRecompilation = new HashSet<VirtualFile>(); synchronized (myDataLock) { final TIntHashSet pathsToRecompile = mySourcesToRecompile.get(projectId); if (_forceCompile || pathsToRecompile != null && !pathsToRecompile.isEmpty()) { if (ourDebugMode) { System.out.println("Analysing potentially recompilable files for " + compiler.getDescription()); } while (scopeSrcIterator.hasNext()) { final VirtualFile file = scopeSrcIterator.next(); if (!file.isValid()) { if (LOG.isDebugEnabled() || ourDebugMode) { LOG.debug("Skipping invalid file " + file.getPresentableUrl()); if (ourDebugMode) { System.out.println("\t SKIPPED(INVALID) " + file.getPresentableUrl()); } } continue; } final int fileId = getFileId(file); if (_forceCompile) { if (compiler.isCompilableFile(file, context) && !configuration.isExcludedFromCompilation(file)) { toCompile.add(file); if (ourDebugMode) { System.out.println("\t INCLUDED " + file.getPresentableUrl()); } selectedForRecompilation.add(file); if (pathsToRecompile == null || !pathsToRecompile.contains(fileId)) { loadInfoAndAddSourceForRecompilation(projectId, file); } } else { if (ourDebugMode) { System.out.println("\t NOT COMPILABLE OR EXCLUDED " + file.getPresentableUrl()); } } } else if (pathsToRecompile.contains(fileId)) { if (compiler.isCompilableFile(file, context) && !configuration.isExcludedFromCompilation(file)) { toCompile.add(file); if (ourDebugMode) { System.out.println("\t INCLUDED " + file.getPresentableUrl()); } selectedForRecompilation.add(file); } else { if (ourDebugMode) { System.out.println("\t NOT COMPILABLE OR EXCLUDED " + file.getPresentableUrl()); } } } else { if (ourDebugMode) { System.out.println("\t NOT INCLUDED " + file.getPresentableUrl()); } } } } // it is important that files to delete are collected after the files to compile (see what happens if forceCompile == true) if (!isRebuild) { final Outputs outputs = myOutputsToDelete.get(projectId); try { final VirtualFileManager vfm = VirtualFileManager.getInstance(); final LocalFileSystem lfs = LocalFileSystem.getInstance(); final List<String> zombieEntries = new ArrayList<String>(); final Map<String, VirtualFile> srcFileCache = getFileCache(context); for (Map.Entry<String, SourceUrlClassNamePair> entry : outputs.getEntries()) { final String outputPath = entry.getKey(); final SourceUrlClassNamePair classNamePair = entry.getValue(); final String sourceUrl = classNamePair.getSourceUrl(); final VirtualFile srcFile; if (srcFileCache.containsKey(sourceUrl)) { srcFile = srcFileCache.get(sourceUrl); } else { srcFile = vfm.findFileByUrl(sourceUrl); srcFileCache.put(sourceUrl, srcFile); } final boolean sourcePresent = srcFile != null; if (sourcePresent) { if (!compiler.isCompilableFile(srcFile, context)) { continue; // do not collect files that were compiled by another compiler } if (!selectedForRecompilation.contains(srcFile)) { if (!isMarkedForRecompilation(projectId, getFileId(srcFile))) { if (LOG.isDebugEnabled() || ourDebugMode) { final String message = "Found zombie entry (output is marked, but source is present and up-to-date): " + outputPath; LOG.debug(message); if (ourDebugMode) { System.out.println(message); } } zombieEntries.add(outputPath); } continue; } } if (lfs.findFileByPath(outputPath) != null) { //noinspection UnnecessaryBoxing final File file = new File(outputPath); toDelete.add(new Trinity<File, String, Boolean>(file, classNamePair.getClassName(), Boolean.valueOf(sourcePresent))); if (LOG.isDebugEnabled() || ourDebugMode) { final String message = "Found file to delete: " + file; LOG.debug(message); if (ourDebugMode) { System.out.println(message); } } } else { if (LOG.isDebugEnabled() || ourDebugMode) { final String message = "Found zombie entry marked for deletion: " + outputPath; LOG.debug(message); if (ourDebugMode) { System.out.println(message); } } // must be gagbage entry, should cleanup zombieEntries.add(outputPath); } } for (String path : zombieEntries) { unmarkOutputPathForDeletion(projectId, path); } } finally { outputs.release(); } } } } private static Map<String, VirtualFile> getFileCache(CompileContext context) { Map<String, VirtualFile> cache = context.getUserData(SOURCE_FILES_CACHE); if (cache == null) { context.putUserData(SOURCE_FILES_CACHE, cache = new HashMap<String, VirtualFile>()); } return cache; } private static int getFileId(final VirtualFile file) { return FileBasedIndex.getFileId(file); } private static VirtualFile findFileById(int id) { return IndexInfrastructure.findFileById((PersistentFS)ManagingFS.getInstance(), id); } public void update(final CompileContext context, @Nullable final String outputRoot, final Collection<TranslatingCompiler.OutputItem> successfullyCompiled, final VirtualFile[] filesToRecompile) throws IOException { final Project project = context.getProject(); final int projectId = getProjectId(project); if (!successfullyCompiled.isEmpty()) { final LocalFileSystem lfs = LocalFileSystem.getInstance(); final IOException[] exceptions = {null}; // need read action here to ensure that no modifications were made to VFS while updating file attributes ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { try { final Map<VirtualFile, SourceFileInfo> compiledSources = new HashMap<VirtualFile, SourceFileInfo>(); final Set<VirtualFile> forceRecompile = new HashSet<VirtualFile>(); for (TranslatingCompiler.OutputItem item : successfullyCompiled) { final VirtualFile sourceFile = item.getSourceFile(); final boolean isSourceValid = sourceFile.isValid(); SourceFileInfo srcInfo = compiledSources.get(sourceFile); if (isSourceValid && srcInfo == null) { srcInfo = loadSourceInfo(sourceFile); if (srcInfo != null) { srcInfo.clearPaths(projectId); } else { srcInfo = new SourceFileInfo(); } compiledSources.put(sourceFile, srcInfo); } final String outputPath = item.getOutputPath(); if (outputPath != null) { // can be null for packageinfo final VirtualFile outputFile = lfs.findFileByPath(outputPath); //assert outputFile != null : "Virtual file was not found for \"" + outputPath + "\""; if (outputFile != null) { if (!sourceFile.equals(outputFile)) { final String className = outputRoot == null? null : MakeUtil.relativeClassPathToQName(outputPath.substring(outputRoot.length()), '/'); if (isSourceValid) { srcInfo.addOutputPath(projectId, outputPath); saveOutputInfo(outputFile, new OutputFileInfo(sourceFile.getPath(), className)); } else { markOutputPathForDeletion(projectId, outputPath, className, sourceFile.getUrl()); } } } else { // output file was not found LOG.warn("TranslatingCompilerFilesMonitor.update(): Virtual file was not found for \"" + outputPath + "\""); if (isSourceValid) { forceRecompile.add(sourceFile); } } } } final long compilationStartStamp = ((CompileContextEx)context).getStartCompilationStamp(); for (Map.Entry<VirtualFile, SourceFileInfo> entry : compiledSources.entrySet()) { final SourceFileInfo info = entry.getValue(); final VirtualFile file = entry.getKey(); final long fileStamp = file.getTimeStamp(); info.updateTimestamp(projectId, fileStamp); saveSourceInfo(file, info); if (LOG.isDebugEnabled() || ourDebugMode) { final String message = "Unschedule recompilation (successfully compiled) " + file.getPresentableUrl(); LOG.debug(message); if (ourDebugMode) { System.out.println(message); } } removeSourceForRecompilation(projectId, Math.abs(getFileId(file))); if (fileStamp > compilationStartStamp && !((CompileContextEx)context).isGenerated(file) || forceRecompile.contains(file)) { // changes were made during compilation, need to re-schedule compilation // it is important to invoke removeSourceForRecompilation() before this call to make sure // the corresponding output paths will be scheduled for deletion addSourceForRecompilation(projectId, file, info); } } } catch (IOException e) { exceptions[0] = e; } } }); if (exceptions[0] != null) { throw exceptions[0]; } } if (filesToRecompile.length > 0) { ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { for (VirtualFile file : filesToRecompile) { if (file.isValid()) { loadInfoAndAddSourceForRecompilation(projectId, file); } } } }); } } public void updateOutputRootsLayout(Project project) { final TIntObjectHashMap<Pair<Integer, Integer>> map = buildOutputRootsLayout(new ProjectRef(project)); final int projectId = getProjectId(project); synchronized (myProjectOutputRoots) { myProjectOutputRoots.put(projectId, map); } } @NotNull public String getComponentName() { return "TranslatingCompilerFilesMonitor"; } public void initComponent() { ensureOutputStorageInitialized(); } private static File getOutputRootsFile() { return new File(CompilerPaths.getCompilerSystemDirectory(), "output_roots.dat"); } private static void deleteStorageFiles(File tableFile) { final File[] files = tableFile.getParentFile().listFiles(); if (files != null) { final String name = tableFile.getName(); for (File file : files) { if (file.getName().startsWith(name)) { FileUtil.delete(file); } } } } private static Map<String, SourceUrlClassNamePair> loadPathsToDelete(@Nullable final File file) { final Map<String, SourceUrlClassNamePair> map = new HashMap<String, SourceUrlClassNamePair>(); try { if (file != null && file.length() > 0) { final DataInputStream is = new DataInputStream(new BufferedInputStream(new FileInputStream(file))); try { final int size = is.readInt(); for (int i = 0; i < size; i++) { final String _outputPath = CompilerIOUtil.readString(is); final String srcUrl = CompilerIOUtil.readString(is); final String className = CompilerIOUtil.readString(is); map.put(FileUtil.toSystemIndependentName(_outputPath), new SourceUrlClassNamePair(srcUrl, className)); } } finally { is.close(); } } } catch (FileNotFoundException ignored) { } catch (IOException e) { LOG.info(e); } return map; } private void ensureOutputStorageInitialized() { if (myOutputRootsStorage != null) { return; } final File rootsFile = getOutputRootsFile(); try { initOutputRootsFile(rootsFile); } catch (IOException e) { LOG.info(e); deleteStorageFiles(rootsFile); try { initOutputRootsFile(rootsFile); } catch (IOException e1) { LOG.error(e1); } } } private TIntObjectHashMap<Pair<Integer, Integer>> buildOutputRootsLayout(ProjectRef projRef) { final TIntObjectHashMap<Pair<Integer, Integer>> map = new TIntObjectHashMap<Pair<Integer, Integer>>(); for (Module module : ModuleManager.getInstance(projRef.get()).getModules()) { final CompilerModuleExtension manager = CompilerModuleExtension.getInstance(module); if (manager != null) { final VirtualFile output = manager.getCompilerOutputPath(); final int first = output != null? Math.abs(getFileId(output)) : -1; final VirtualFile testsOutput = manager.getCompilerOutputPathForTests(); final int second = testsOutput != null? Math.abs(getFileId(testsOutput)) : -1; map.put(getModuleId(module), new Pair<Integer, Integer>(first, second)); } } return map; } private void initOutputRootsFile(File rootsFile) throws IOException { myOutputRootsStorage = new PersistentHashMap<Integer, TIntObjectHashMap<Pair<Integer, Integer>>>(rootsFile, EnumeratorIntegerDescriptor.INSTANCE, new DataExternalizer<TIntObjectHashMap<Pair<Integer, Integer>>>() { public void save(DataOutput out, TIntObjectHashMap<Pair<Integer, Integer>> value) throws IOException { for (final TIntObjectIterator<Pair<Integer, Integer>> it = value.iterator(); it.hasNext();) { it.advance(); DataInputOutputUtil.writeINT(out, it.key()); final Pair<Integer, Integer> pair = it.value(); DataInputOutputUtil.writeINT(out, pair.first); DataInputOutputUtil.writeINT(out, pair.second); } } public TIntObjectHashMap<Pair<Integer, Integer>> read(DataInput in) throws IOException { final DataInputStream _in = (DataInputStream)in; final TIntObjectHashMap<Pair<Integer, Integer>> map = new TIntObjectHashMap<Pair<Integer, Integer>>(); while (_in.available() > 0) { final int key = DataInputOutputUtil.readINT(_in); final int first = DataInputOutputUtil.readINT(_in); final int second = DataInputOutputUtil.readINT(_in); map.put(key, new Pair<Integer, Integer>(first, second)); } return map; } }); } public void disposeComponent() { try { synchronized (myProjectOutputRoots) { myProjectOutputRoots.clear(); } } finally { synchronized (myDataLock) { myOutputsToDelete.clear(); } } try { myOutputRootsStorage.close(); } catch (IOException e) { LOG.info(e); deleteStorageFiles(getOutputRootsFile()); } } private static void savePathsToDelete(final File file, final Map<String, SourceUrlClassNamePair> outputs) { try { FileUtil.createParentDirs(file); final DataOutputStream os = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file))); try { if (outputs != null) { os.writeInt(outputs.size()); for (Map.Entry<String, SourceUrlClassNamePair> entry : outputs.entrySet()) { CompilerIOUtil.writeString(entry.getKey(), os); final SourceUrlClassNamePair pair = entry.getValue(); CompilerIOUtil.writeString(pair.getSourceUrl(), os); CompilerIOUtil.writeString(pair.getClassName(), os); } } else { os.writeInt(0); } } finally { os.close(); } } catch (IOException e) { LOG.error(e); } } @Nullable private static SourceFileInfo loadSourceInfo(final VirtualFile file) { try { final DataInputStream is = ourSourceFileAttribute.readAttribute(file); if (is != null) { try { return new SourceFileInfo(is); } finally { is.close(); } } } catch (RuntimeException e) { final Throwable cause = e.getCause(); if (cause instanceof IOException) { LOG.info(e); // ignore IOExceptions } else { throw e; } } catch (IOException ignored) { LOG.info(ignored); } return null; } public static void removeSourceInfo(VirtualFile file) { saveSourceInfo(file, new SourceFileInfo()); } private static void saveSourceInfo(VirtualFile file, SourceFileInfo descriptor) { final java.io.DataOutputStream out = ourSourceFileAttribute.writeAttribute(file); try { try { descriptor.save(out); } finally { out.close(); } } catch (IOException ignored) { LOG.info(ignored); } } @Nullable private static OutputFileInfo loadOutputInfo(final VirtualFile file) { try { final DataInputStream is = ourOutputFileAttribute.readAttribute(file); if (is != null) { try { return new OutputFileInfo(is); } finally { is.close(); } } } catch (RuntimeException e) { final Throwable cause = e.getCause(); if (cause instanceof IOException) { LOG.info(e); // ignore IO exceptions } else { throw e; } } catch (IOException ignored) { LOG.info(ignored); } return null; } private static void saveOutputInfo(VirtualFile file, OutputFileInfo descriptor) { final java.io.DataOutputStream out = ourOutputFileAttribute.writeAttribute(file); try { try { descriptor.save(out); } finally { out.close(); } } catch (IOException ignored) { LOG.info(ignored); } } private int getProjectId(Project project) { try { return FSRecords.getNames().enumerate(CompilerPaths.getCompilerSystemDirectoryName(project)); } catch (IOException e) { LOG.info(e); } return -1; } private int getModuleId(Module module) { try { return FSRecords.getNames().enumerate(module.getName().toLowerCase(Locale.US)); } catch (IOException e) { LOG.info(e); } return -1; } private static class OutputFileInfo { private final int mySourcePath; private final int myClassName; OutputFileInfo(final String sourcePath, @Nullable String className) throws IOException { final PersistentStringEnumerator symtable = FSRecords.getNames(); mySourcePath = symtable.enumerate(sourcePath); myClassName = className != null? symtable.enumerate(className) : -1; } OutputFileInfo(final DataInput in) throws IOException { mySourcePath = in.readInt(); myClassName = in.readInt(); } String getSourceFilePath() { try { return FSRecords.getNames().valueOf(mySourcePath); } catch (IOException e) { LOG.info(e); } return null; } @Nullable public String getClassName() { try { return myClassName < 0? null : FSRecords.getNames().valueOf(myClassName); } catch (IOException e) { LOG.info(e); } return null; } public void save(final DataOutput out) throws IOException { out.writeInt(mySourcePath); out.writeInt(myClassName); } } private static class SourceFileInfo { private TIntLongHashMap myTimestamps; // ProjectId -> last compiled stamp private TIntObjectHashMap<Serializable> myProjectToOutputPathMap; // ProjectId -> either a single output path or a set of output paths private SourceFileInfo() { } private SourceFileInfo(@NotNull DataInput in) throws IOException { final int projCount = in.readInt(); for (int idx = 0; idx < projCount; idx++) { final int projectId = in.readInt(); final long stamp = in.readLong(); updateTimestamp(projectId, stamp); final int pathsCount = in.readInt(); for (int i = 0; i < pathsCount; i++) { final int path = in.readInt(); addOutputPath(projectId, path); } } } public void save(@NotNull final DataOutput out) throws IOException { final int[] projects = getProjectIds().toArray(); out.writeInt(projects.length); for (int projectId : projects) { out.writeInt(projectId); out.writeLong(getTimestamp(projectId)); final Object value = myProjectToOutputPathMap != null? myProjectToOutputPathMap.get(projectId) : null; if (value instanceof Integer) { out.writeInt(1); out.writeInt(((Integer)value).intValue()); } else if (value instanceof TIntHashSet) { final TIntHashSet set = (TIntHashSet)value; out.writeInt(set.size()); final IOException[] ex = new IOException[] {null}; set.forEach(new TIntProcedure() { public boolean execute(final int value) { try { out.writeInt(value); return true; } catch (IOException e) { ex[0] = e; return false; } } }); if (ex[0] != null) { throw ex[0]; } } else { out.writeInt(0); } } } private void updateTimestamp(final int projectId, final long stamp) { if (stamp > 0L) { if (myTimestamps == null) { myTimestamps = new TIntLongHashMap(1, 0.98f); } myTimestamps.put(projectId, stamp); } else { if (myTimestamps != null) { myTimestamps.remove(projectId); } } } TIntHashSet getProjectIds() { final TIntHashSet result = new TIntHashSet(); if (myTimestamps != null) { result.addAll(myTimestamps.keys()); } if (myProjectToOutputPathMap != null) { result.addAll(myProjectToOutputPathMap.keys()); } return result; } private void addOutputPath(final int projectId, String outputPath) { try { addOutputPath(projectId, FSRecords.getNames().enumerate(outputPath)); } catch (IOException e) { LOG.info(e); } } private void addOutputPath(final int projectId, final int outputPath) { if (myProjectToOutputPathMap == null) { myProjectToOutputPathMap = new TIntObjectHashMap<Serializable>(1, 0.98f); myProjectToOutputPathMap.put(projectId, outputPath); } else { final Object val = myProjectToOutputPathMap.get(projectId); if (val == null) { myProjectToOutputPathMap.put(projectId, outputPath); } else { TIntHashSet set; if (val instanceof Integer) { set = new TIntHashSet(); set.add(((Integer)val).intValue()); myProjectToOutputPathMap.put(projectId, set); } else { assert val instanceof TIntHashSet; set = (TIntHashSet)val; } set.add(outputPath); } } } public boolean clearPaths(final int projectId){ if (myProjectToOutputPathMap != null) { final Serializable removed = myProjectToOutputPathMap.remove(projectId); return removed != null; } return false; } long getTimestamp(final int projectId) { return myTimestamps == null? -1L : myTimestamps.get(projectId); } void processOutputPaths(final int projectId, final Proc proc){ if (myProjectToOutputPathMap != null) { try { final PersistentStringEnumerator symtable = FSRecords.getNames(); final Object val = myProjectToOutputPathMap.get(projectId); if (val instanceof Integer) { proc.execute(projectId, symtable.valueOf(((Integer)val).intValue())); } else if (val instanceof TIntHashSet) { ((TIntHashSet)val).forEach(new TIntProcedure() { public boolean execute(final int value) { try { proc.execute(projectId, symtable.valueOf(value)); return true; } catch (IOException e) { LOG.info(e); return false; } } }); } } catch (IOException e) { LOG.info(e); } } } boolean isAssociated(int projectId, String outputPath) { if (myProjectToOutputPathMap != null) { try { final Object val = myProjectToOutputPathMap.get(projectId); if (val instanceof Integer) { return FileUtil.pathsEqual(outputPath, FSRecords.getNames().valueOf(((Integer)val).intValue())); } if (val instanceof TIntHashSet) { final int _outputPath = FSRecords.getNames().enumerate(outputPath); return ((TIntHashSet)val).contains(_outputPath); } } catch (IOException e) { LOG.info(e); } } return false; } } public List<String> getCompiledClassNames(VirtualFile srcFile, Project project) { final SourceFileInfo info = loadSourceInfo(srcFile); if (info == null) { return Collections.emptyList(); } final ArrayList<String> result = new ArrayList<String>(); info.processOutputPaths(getProjectId(project), new Proc() { @Override public boolean execute(int projectId, String outputPath) { VirtualFile clsFile = LocalFileSystem.getInstance().findFileByPath(outputPath); if (clsFile != null) { OutputFileInfo outputInfo = loadOutputInfo(clsFile); if (outputInfo != null) { ContainerUtil.addIfNotNull(result, outputInfo.getClassName()); } } return true; } }); return result; } private interface FileProcessor { void execute(VirtualFile file); } private static void processRecursively(VirtualFile file, boolean dbOnly, final FileProcessor processor) { if (file.getFileSystem() instanceof LocalFileSystem) { if (file.isDirectory()) { if (dbOnly) { for (VirtualFile child : ((NewVirtualFile)file).iterInDbChildren()) { processRecursively(child, true, processor); } } else { for (VirtualFile child : file.getChildren()) { processRecursively(child, false, processor); } } } else { processor.execute(file); } } } // made public for tests public void scanSourceContent(final ProjectRef projRef, final Collection<VirtualFile> roots, final int totalRootCount, final boolean isNewRoots) { if (roots.isEmpty()) { return; } final int projectId = getProjectId(projRef.get()); if (LOG.isDebugEnabled()) { LOG.debug("Scanning source content for project projectId=" + projectId + "; url=" + projRef.get().getPresentableUrl()); } final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(projRef.get()).getFileIndex(); final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); int processed = 0; for (VirtualFile srcRoot : roots) { if (indicator != null) { projRef.get(); indicator.setText2(srcRoot.getPresentableUrl()); indicator.setFraction(++processed / (double)totalRootCount); } if (isNewRoots) { fileIndex.iterateContentUnderDirectory(srcRoot, new ContentIterator() { public boolean processFile(final VirtualFile file) { if (!file.isDirectory()) { if (!isMarkedForRecompilation(projectId, Math.abs(getFileId(file)))) { final SourceFileInfo srcInfo = loadSourceInfo(file); if (srcInfo == null || srcInfo.getTimestamp(projectId) != file.getTimeStamp()) { addSourceForRecompilation(projectId, file, srcInfo); } } } else { projRef.get(); } return true; } }); } else { final FileTypeManager fileTypeManager = FileTypeManager.getInstance(); new Object() { void processFile(VirtualFile file) { if (fileTypeManager.isFileIgnored(file)) { return; } final int fileId = getFileId(file); if (fileId > 0 /*file is valid*/) { if (file.isDirectory()) { projRef.get(); for (VirtualFile child : file.getChildren()) { processFile(child); } } else { if (!isMarkedForRecompilation(projectId, fileId)) { final SourceFileInfo srcInfo = loadSourceInfo(file); if (srcInfo != null) { addSourceForRecompilation(projectId, file, srcInfo); } } } } } }.processFile(srcRoot); } } } public void ensureInitializationCompleted(Project project, ProgressIndicator indicator) { final int id = getProjectId(project); synchronized (myAsyncScanLock) { while (myInitInProgress.containsKey(id)) { if (!project.isOpen() || project.isDisposed() || (indicator != null && indicator.isCanceled())) { // makes no sense to continue waiting break; } try { myAsyncScanLock.wait(500); } catch (InterruptedException ignored) { break; } } } } private void markOldOutputRoots(final ProjectRef projRef, final TIntObjectHashMap<Pair<Integer, Integer>> currentLayout) { final int projectId = getProjectId(projRef.get()); final TIntHashSet rootsToMark = new TIntHashSet(); synchronized (myProjectOutputRoots) { final TIntObjectHashMap<Pair<Integer, Integer>> oldLayout = myProjectOutputRoots.get(projectId); for (final TIntObjectIterator<Pair<Integer, Integer>> it = oldLayout.iterator(); it.hasNext();) { it.advance(); final Pair<Integer, Integer> currentRoots = currentLayout.get(it.key()); final Pair<Integer, Integer> oldRoots = it.value(); if (shouldMark(oldRoots.first, currentRoots != null? currentRoots.first : -1)) { rootsToMark.add(oldRoots.first); } if (shouldMark(oldRoots.second, currentRoots != null? currentRoots.second : -1)) { rootsToMark.add(oldRoots.second); } } } for (TIntIterator it = rootsToMark.iterator(); it.hasNext();) { final int id = it.next(); final VirtualFile outputRoot = findFileById(id); if (outputRoot != null) { processOldOutputRoot(projectId, outputRoot); } } } private static boolean shouldMark(Integer oldOutputRoot, Integer currentOutputRoot) { return oldOutputRoot != null && oldOutputRoot.intValue() > 0 && !Comparing.equal(oldOutputRoot, currentOutputRoot); } private void processOldOutputRoot(int projectId, VirtualFile outputRoot) { // recursively mark all corresponding sources for recompilation if (outputRoot.isDirectory()) { for (VirtualFile child : outputRoot.getChildren()) { processOldOutputRoot(projectId, child); } } else { // todo: possible optimization - process only those outputs that are not marked for deletion yet final OutputFileInfo outputInfo = loadOutputInfo(outputRoot); if (outputInfo != null) { final String srcPath = outputInfo.getSourceFilePath(); final VirtualFile srcFile = srcPath != null? LocalFileSystem.getInstance().findFileByPath(srcPath) : null; if (srcFile != null) { loadInfoAndAddSourceForRecompilation(projectId, srcFile); } } } } public void scanSourcesForCompilableFiles(final Project project) { final int projectId = getProjectId(project); if (isSuspended(projectId)) { return; } startAsyncScan(projectId); StartupManager.getInstance(project).runWhenProjectIsInitialized(new Runnable() { public void run() { new Task.Backgroundable(project, CompilerBundle.message("compiler.initial.scanning.progress.text"), false) { public void run(@NotNull final ProgressIndicator indicator) { final ProjectRef projRef = new ProjectRef(project); if (LOG.isDebugEnabled()) { LOG.debug("Initial sources scan for project hash=" + projectId + "; url="+ projRef.get().getPresentableUrl()); } try { final IntermediateOutputCompiler[] compilers = CompilerManager.getInstance(projRef.get()).getCompilers(IntermediateOutputCompiler.class); final Set<VirtualFile> intermediateRoots = new HashSet<VirtualFile>(); if (compilers.length > 0) { final Module[] modules = ModuleManager.getInstance(projRef.get()).getModules(); for (IntermediateOutputCompiler compiler : compilers) { for (Module module : modules) { if (module.isDisposed()) { continue; } final VirtualFile outputRoot = LocalFileSystem.getInstance().refreshAndFindFileByPath(CompilerPaths.getGenerationOutputPath(compiler, module, false)); if (outputRoot != null) { intermediateRoots.add(outputRoot); } final VirtualFile testsOutputRoot = LocalFileSystem.getInstance().refreshAndFindFileByPath(CompilerPaths.getGenerationOutputPath(compiler, module, true)); if (testsOutputRoot != null) { intermediateRoots.add(testsOutputRoot); } } } } final List<VirtualFile> projectRoots = Arrays.asList(ProjectRootManager.getInstance(projRef.get()).getContentSourceRoots()); final int totalRootsCount = projectRoots.size() + intermediateRoots.size(); scanSourceContent(projRef, projectRoots, totalRootsCount, true); if (!intermediateRoots.isEmpty()) { final FileProcessor processor = new FileProcessor() { public void execute(final VirtualFile file) { if (!isMarkedForRecompilation(projectId, Math.abs(getFileId(file)))) { final SourceFileInfo srcInfo = loadSourceInfo(file); if (srcInfo == null || srcInfo.getTimestamp(projectId) != file.getTimeStamp()) { addSourceForRecompilation(projectId, file, srcInfo); } } } }; int processed = projectRoots.size(); for (VirtualFile root : intermediateRoots) { projRef.get(); indicator.setText2(root.getPresentableUrl()); indicator.setFraction(++processed / (double)totalRootsCount); processRecursively(root, false, processor); } } markOldOutputRoots(projRef, buildOutputRootsLayout(projRef)); } catch (ProjectRef.ProjectClosedException swallowed) { } finally { terminateAsyncScan(projectId, false); } } }.queue(); } }); } private void terminateAsyncScan(int projectId, final boolean clearCounter) { synchronized (myAsyncScanLock) { int counter = myInitInProgress.remove(projectId); if (clearCounter) { myAsyncScanLock.notifyAll(); } else { if (--counter > 0) { myInitInProgress.put(projectId, counter); } else { myAsyncScanLock.notifyAll(); } } } } private void startAsyncScan(final int projectId) { synchronized (myAsyncScanLock) { int counter = myInitInProgress.get(projectId); counter = (counter > 0)? counter + 1 : 1; myInitInProgress.put(projectId, counter); myAsyncScanLock.notifyAll(); } } private class MyProjectManagerListener extends ProjectManagerAdapter { final Map<Project, MessageBusConnection> myConnections = new HashMap<Project, MessageBusConnection>(); public void projectOpened(final Project project) { final MessageBusConnection conn = project.getMessageBus().connect(); myConnections.put(project, conn); final ProjectRef projRef = new ProjectRef(project); final int projectId = getProjectId(project); if (CompilerWorkspaceConfiguration.getInstance(project).useOutOfProcessBuild()) { suspendProject(project); } else { watchProject(project); } conn.subscribe(ProjectTopics.PROJECT_ROOTS, new ModuleRootListener() { private VirtualFile[] myRootsBefore; private Alarm myAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD, project); public void beforeRootsChange(final ModuleRootEvent event) { if (isSuspended(projectId)) { return; } try { myRootsBefore = ProjectRootManager.getInstance(projRef.get()).getContentSourceRoots(); } catch (ProjectRef.ProjectClosedException e) { myRootsBefore = null; } } public void rootsChanged(final ModuleRootEvent event) { if (isSuspended(projectId)) { return; } if (LOG.isDebugEnabled()) { LOG.debug("Before roots changed for projectId=" + projectId + "; url="+ project.getPresentableUrl()); } try { final VirtualFile[] rootsBefore = myRootsBefore; myRootsBefore = null; final VirtualFile[] rootsAfter = ProjectRootManager.getInstance(projRef.get()).getContentSourceRoots(); final Set<VirtualFile> newRoots = new HashSet<VirtualFile>(); final Set<VirtualFile> oldRoots = new HashSet<VirtualFile>(); { if (rootsAfter.length > 0) { ContainerUtil.addAll(newRoots, rootsAfter); } if (rootsBefore != null) { newRoots.removeAll(Arrays.asList(rootsBefore)); } } { if (rootsBefore != null) { ContainerUtil.addAll(oldRoots, rootsBefore); } if (!oldRoots.isEmpty() && rootsAfter.length > 0) { oldRoots.removeAll(Arrays.asList(rootsAfter)); } } myAlarm.cancelAllRequests(); // need alarm to deal with multiple rootsChanged events myAlarm.addRequest(new Runnable() { public void run() { startAsyncScan(projectId); new Task.Backgroundable(project, CompilerBundle.message("compiler.initial.scanning.progress.text"), false) { public void run(@NotNull final ProgressIndicator indicator) { try { if (newRoots.size() > 0) { scanSourceContent(projRef, newRoots, newRoots.size(), true); } if (oldRoots.size() > 0) { scanSourceContent(projRef, oldRoots, oldRoots.size(), false); } markOldOutputRoots(projRef, buildOutputRootsLayout(projRef)); } catch (ProjectRef.ProjectClosedException swallowed) { // ignored } finally { terminateAsyncScan(projectId, false); } } }.queue(); } }, 500, ModalityState.NON_MODAL); } catch (ProjectRef.ProjectClosedException e) { LOG.info(e); } } }); scanSourcesForCompilableFiles(project); } public void projectClosed(final Project project) { final int projectId = getProjectId(project); terminateAsyncScan(projectId, true); myConnections.remove(project).disconnect(); synchronized (myDataLock) { mySourcesToRecompile.remove(projectId); myOutputsToDelete.remove(projectId); // drop cache to save memory } } } private class MyVfsListener extends VirtualFileAdapter { public void propertyChanged(final VirtualFilePropertyEvent event) { if (VirtualFile.PROP_NAME.equals(event.getPropertyName())) { final VirtualFile eventFile = event.getFile(); final VirtualFile parent = event.getParent(); if (parent != null) { final String oldName = (String)event.getOldValue(); final String root = parent.getPath() + "/" + oldName; final Set<String> toMark; if (eventFile.isDirectory()) { toMark = new HashSet<String>(); new Object() { void process(VirtualFile file, String filePath) { if (file.isDirectory()) { for (VirtualFile child : file.getChildren()) { process(child, filePath + "/" + child.getName()); } } else { toMark.add(filePath); } } }.process(eventFile, root); } else { toMark = Collections.singleton(root); } if (!toMark.isEmpty()) { notifyFilesDeleted(toMark); } } markDirtyIfSource(eventFile, false); } } public void contentsChanged(final VirtualFileEvent event) { markDirtyIfSource(event.getFile(), false); } public void fileCreated(final VirtualFileEvent event) { processNewFile(event.getFile(), true); } public void fileCopied(final VirtualFileCopyEvent event) { processNewFile(event.getFile(), true); } public void fileMoved(VirtualFileMoveEvent event) { processNewFile(event.getFile(), true); } public void beforeFileDeletion(final VirtualFileEvent event) { final VirtualFile eventFile = event.getFile(); if ((LOG.isDebugEnabled() && eventFile.isDirectory()) || ourDebugMode) { final String message = "Processing file deletion: " + eventFile.getPresentableUrl(); LOG.debug(message); if (ourDebugMode) { System.out.println(message); } } final Set<String> pathsToMark = new HashSet<String>(); processRecursively(eventFile, true, new FileProcessor() { private final TIntArrayList myAssociatedProjectIds = new TIntArrayList(); public void execute(final VirtualFile file) { final String filePath = file.getPath(); pathsToMark.add(filePath); myAssociatedProjectIds.clear(); try { final OutputFileInfo outputInfo = loadOutputInfo(file); if (outputInfo != null) { final String srcPath = outputInfo.getSourceFilePath(); final VirtualFile srcFile = srcPath != null? LocalFileSystem.getInstance().findFileByPath(srcPath) : null; if (srcFile != null) { final SourceFileInfo srcInfo = loadSourceInfo(srcFile); if (srcInfo != null) { final boolean srcWillBeDeleted = VfsUtil.isAncestor(eventFile, srcFile, false); for (int projectId : srcInfo.getProjectIds().toArray()) { if (isSuspended(projectId)) { continue; } if (srcInfo.isAssociated(projectId, filePath)) { myAssociatedProjectIds.add(projectId); if (srcWillBeDeleted) { if (LOG.isDebugEnabled() || ourDebugMode) { final String message = "Unschedule recompilation because of deletion " + srcFile.getPresentableUrl(); LOG.debug(message); if (ourDebugMode) { System.out.println(message); } } removeSourceForRecompilation(projectId, Math.abs(getFileId(srcFile))); } else { addSourceForRecompilation(projectId, srcFile, srcInfo); } } } } } } final SourceFileInfo srcInfo = loadSourceInfo(file); if (srcInfo != null) { final TIntHashSet projects = srcInfo.getProjectIds(); if (!projects.isEmpty()) { final ScheduleOutputsForDeletionProc deletionProc = new ScheduleOutputsForDeletionProc(file.getUrl()); deletionProc.setRootBeingDeleted(eventFile); final int sourceFileId = Math.abs(getFileId(file)); for (int projectId : projects.toArray()) { if (isSuspended(projectId)) { continue; } if (srcInfo.isAssociated(projectId, filePath)) { myAssociatedProjectIds.add(projectId); } // mark associated outputs for deletion srcInfo.processOutputPaths(projectId, deletionProc); if (LOG.isDebugEnabled() || ourDebugMode) { final String message = "Unschedule recompilation because of deletion " + file.getPresentableUrl(); LOG.debug(message); if (ourDebugMode) { System.out.println(message); } } removeSourceForRecompilation(projectId, sourceFileId); } } } } finally { // it is important that update of myOutputsToDelete is done at the end // otherwise the filePath of the file that is about to be deleted may be re-scheduled for deletion in addSourceForRecompilation() myAssociatedProjectIds.forEach(new TIntProcedure() { public boolean execute(int projectId) { unmarkOutputPathForDeletion(projectId, filePath); return true; } }); } } }); if (!pathsToMark.isEmpty()) { notifyFilesDeleted(pathsToMark); } } public void beforeFileMovement(final VirtualFileMoveEvent event) { markDirtyIfSource(event.getFile(), true); } private void markDirtyIfSource(final VirtualFile file, final boolean fromMove) { final Set<String> pathsToMark = new HashSet<String>(); processRecursively(file, false, new FileProcessor() { public void execute(final VirtualFile file) { pathsToMark.add(file.getPath()); final SourceFileInfo srcInfo = file.isValid()? loadSourceInfo(file) : null; if (srcInfo != null) { for (int projectId : srcInfo.getProjectIds().toArray()) { if (isSuspended(projectId)) { if (srcInfo.clearPaths(projectId)) { srcInfo.updateTimestamp(projectId, -1L); saveSourceInfo(file, srcInfo); } } else { addSourceForRecompilation(projectId, file, srcInfo); // when the file is moved to a new location, we should 'forget' previous associations if (fromMove) { if (srcInfo.clearPaths(projectId)) { saveSourceInfo(file, srcInfo); } } } } } else { processNewFile(file, false); } } }); if (fromMove) { notifyFilesDeleted(pathsToMark); } else { notifyFilesChanged(pathsToMark); } } private void processNewFile(final VirtualFile file, final boolean notifyServer) { final Set<String> pathsToMark = notifyServer ? new HashSet<String>() : Collections.<String>emptySet(); ApplicationManager.getApplication().runReadAction(new Runnable() { // need read action to ensure that the project was not disposed during the iteration over the project list public void run() { for (final Project project : myProjectManager.getOpenProjects()) { if (!project.isInitialized()) { continue; // the content of this project will be scanned during its post-startup activities } final int projectId = getProjectId(project); final boolean projectSuspended = isSuspended(projectId); final ProjectRootManager rootManager = ProjectRootManager.getInstance(project); if (rootManager.getFileIndex().isInSourceContent(file)) { final TranslatingCompiler[] translators = CompilerManager.getInstance(project).getCompilers(TranslatingCompiler.class); processRecursively(file, false, new FileProcessor() { public void execute(final VirtualFile file) { if (notifyServer) { pathsToMark.add(file.getPath()); } if (!projectSuspended && isCompilable(file)) { loadInfoAndAddSourceForRecompilation(projectId, file); } } boolean isCompilable(VirtualFile file) { for (TranslatingCompiler translator : translators) { if (translator.isCompilableFile(file, DummyCompileContext.getInstance())) { return true; } } return false; } }); } else { if (!projectSuspended && belongsToIntermediateSources(file, project)) { processRecursively(file, false, new FileProcessor() { public void execute(final VirtualFile file) { loadInfoAndAddSourceForRecompilation(projectId, file); } }); } } } } }); if (notifyServer) { notifyFilesChanged(pathsToMark); } } } private static void notifyFilesChanged(Collection<String> paths) { CompileServerManager.getInstance().notifyFilesChanged(paths); BuildManager.getInstance().notifyFilesChanged(paths); } private static void notifyFilesDeleted(Collection<String> paths) { CompileServerManager.getInstance().notifyFilesDeleted(paths); BuildManager.getInstance().notifyFilesDeleted(paths); } private boolean belongsToIntermediateSources(VirtualFile file, Project project) { return FileUtil.isAncestor(myGeneratedDataPaths.get(project), new File(file.getPath()), true); } private void loadInfoAndAddSourceForRecompilation(final int projectId, final VirtualFile srcFile) { addSourceForRecompilation(projectId, srcFile, loadSourceInfo(srcFile)); } private void addSourceForRecompilation(final int projectId, final VirtualFile srcFile, @Nullable final SourceFileInfo srcInfo) { final boolean alreadyMarked; synchronized (myDataLock) { TIntHashSet set = mySourcesToRecompile.get(projectId); if (set == null) { set = new TIntHashSet(); mySourcesToRecompile.put(projectId, set); } alreadyMarked = !set.add(Math.abs(getFileId(srcFile))); if (!alreadyMarked && (LOG.isDebugEnabled() || ourDebugMode)) { final String message = "Scheduled recompilation " + srcFile.getPresentableUrl(); LOG.debug(message); if (ourDebugMode) { System.out.println(message); } } } if (!alreadyMarked && srcInfo != null) { srcInfo.updateTimestamp(projectId, -1L); srcInfo.processOutputPaths(projectId, new ScheduleOutputsForDeletionProc(srcFile.getUrl())); saveSourceInfo(srcFile, srcInfo); } } private void removeSourceForRecompilation(final int projectId, final int srcId) { synchronized (myDataLock) { TIntHashSet set = mySourcesToRecompile.get(projectId); if (set != null) { set.remove(srcId); if (set.isEmpty()) { mySourcesToRecompile.remove(projectId); } } } } public boolean isMarkedForCompilation(Project project, VirtualFile file) { return isMarkedForRecompilation(getProjectId(project), getFileId(file)); } private boolean isMarkedForRecompilation(int projectId, final int srcId) { synchronized (myDataLock) { final TIntHashSet set = mySourcesToRecompile.get(projectId); return set != null && set.contains(srcId); } } private interface Proc { boolean execute(final int projectId, String outputPath); } private class ScheduleOutputsForDeletionProc implements Proc { private final String mySrcUrl; private final LocalFileSystem myFileSystem; @Nullable private VirtualFile myRootBeingDeleted; private ScheduleOutputsForDeletionProc(final String srcUrl) { mySrcUrl = srcUrl; myFileSystem = LocalFileSystem.getInstance(); } public void setRootBeingDeleted(@Nullable VirtualFile rootBeingDeleted) { myRootBeingDeleted = rootBeingDeleted; } public boolean execute(final int projectId, String outputPath) { final VirtualFile outFile = myFileSystem.findFileByPath(outputPath); if (outFile != null) { // not deleted yet if (myRootBeingDeleted != null && VfsUtil.isAncestor(myRootBeingDeleted, outFile, false)) { unmarkOutputPathForDeletion(projectId, outputPath); } else { final OutputFileInfo outputInfo = loadOutputInfo(outFile); final String classname = outputInfo != null? outputInfo.getClassName() : null; markOutputPathForDeletion(projectId, outputPath, classname, mySrcUrl); } } return true; } } private void markOutputPathForDeletion(final int projectId, final String outputPath, final String classname, final String srcUrl) { final SourceUrlClassNamePair pair = new SourceUrlClassNamePair(srcUrl, classname); synchronized (myDataLock) { final Outputs outputs = myOutputsToDelete.get(projectId); try { outputs.put(outputPath, pair); if (LOG.isDebugEnabled() || ourDebugMode) { final String message = "ADD path to delete: " + outputPath + "; source: " + srcUrl; LOG.debug(message); if (ourDebugMode) { System.out.println(message); } } } finally { outputs.release(); } } } private void unmarkOutputPathForDeletion(final int projectId, String outputPath) { synchronized (myDataLock) { final Outputs outputs = myOutputsToDelete.get(projectId); try { final SourceUrlClassNamePair val = outputs.remove(outputPath); if (val != null) { if (LOG.isDebugEnabled() || ourDebugMode) { final String message = "REMOVE path to delete: " + outputPath; LOG.debug(message); if (ourDebugMode) { System.out.println(message); } } } } finally { outputs.release(); } } } public static final class ProjectRef extends Ref<Project> { static class ProjectClosedException extends RuntimeException { } public ProjectRef(Project project) { super(project); } public Project get() { final Project project = super.get(); if (project != null && project.isDisposed()) { throw new ProjectClosedException(); } return project; } } private static class Outputs { private boolean myIsDirty = false; @Nullable private final File myStoreFile; private final Map<String, SourceUrlClassNamePair> myMap; private final AtomicInteger myRefCount = new AtomicInteger(1); Outputs(@Nullable File storeFile, Map<String, SourceUrlClassNamePair> map) { myStoreFile = storeFile; myMap = map; } public Set<Map.Entry<String, SourceUrlClassNamePair>> getEntries() { return Collections.unmodifiableSet(myMap.entrySet()); } public void put(String outputPath, SourceUrlClassNamePair pair) { if (myStoreFile == null) { return; } if (pair == null) { remove(outputPath); } else { myMap.put(outputPath, pair); myIsDirty = true; } } public SourceUrlClassNamePair remove(String outputPath) { if (myStoreFile == null) { return null; } final SourceUrlClassNamePair removed = myMap.remove(outputPath); myIsDirty |= removed != null; return removed; } void allocate() { myRefCount.incrementAndGet(); } public void release() { if (myRefCount.decrementAndGet() == 0) { if (myIsDirty && myStoreFile != null) { savePathsToDelete(myStoreFile, myMap); } } } } }
do not send empty notifications
java/compiler/impl/src/com/intellij/compiler/impl/TranslatingCompilerFilesMonitor.java
do not send empty notifications
<ide><path>ava/compiler/impl/src/com/intellij/compiler/impl/TranslatingCompilerFilesMonitor.java <ide> else { <ide> toMark = Collections.singleton(root); <ide> } <del> if (!toMark.isEmpty()) { <del> notifyFilesDeleted(toMark); <del> } <add> notifyFilesDeleted(toMark); <ide> } <ide> markDirtyIfSource(eventFile, false); <ide> } <ide> } <ide> }); <ide> <del> if (!pathsToMark.isEmpty()) { <del> notifyFilesDeleted(pathsToMark); <del> } <add> notifyFilesDeleted(pathsToMark); <ide> } <ide> <ide> public void beforeFileMovement(final VirtualFileMoveEvent event) { <ide> } <ide> <ide> private static void notifyFilesChanged(Collection<String> paths) { <del> CompileServerManager.getInstance().notifyFilesChanged(paths); <del> BuildManager.getInstance().notifyFilesChanged(paths); <add> if (!paths.isEmpty()) { <add> CompileServerManager.getInstance().notifyFilesChanged(paths); <add> BuildManager.getInstance().notifyFilesChanged(paths); <add> } <ide> } <ide> <ide> private static void notifyFilesDeleted(Collection<String> paths) { <del> CompileServerManager.getInstance().notifyFilesDeleted(paths); <del> BuildManager.getInstance().notifyFilesDeleted(paths); <add> if (!paths.isEmpty()) { <add> CompileServerManager.getInstance().notifyFilesDeleted(paths); <add> BuildManager.getInstance().notifyFilesDeleted(paths); <add> } <ide> } <ide> <ide> private boolean belongsToIntermediateSources(VirtualFile file, Project project) {
Java
agpl-3.0
3372a3e91f0687d99c7e98c0c065e607d2ac737c
0
JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio
/* * HelpPane.java * * Copyright (C) 2009-20 by RStudio, PBC * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.studio.client.workbench.views.help; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.RepeatingCommand; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.dom.client.*; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; 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.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.event.dom.client.LoadEvent; import com.google.gwt.event.dom.client.LoadHandler; import com.google.gwt.event.logical.shared.ResizeEvent; import com.google.gwt.event.logical.shared.ResizeHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.http.client.URL; import com.google.gwt.resources.client.ClientBundle; import com.google.gwt.resources.client.CssResource; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.*; import com.google.inject.Inject; import com.google.inject.Provider; import org.rstudio.core.client.BrowseCap; import org.rstudio.core.client.CommandWithArg; import org.rstudio.core.client.ElementIds; import org.rstudio.core.client.Point; import org.rstudio.core.client.StringUtil; import org.rstudio.core.client.command.KeyboardShortcut; import org.rstudio.core.client.command.ShortcutManager; import org.rstudio.core.client.dom.DomUtils; import org.rstudio.core.client.dom.ElementEx; import org.rstudio.core.client.dom.IFrameElementEx; import org.rstudio.core.client.dom.WindowEx; import org.rstudio.core.client.events.NativeKeyDownEvent; import org.rstudio.core.client.files.FileSystemItem; import org.rstudio.core.client.theme.res.ThemeStyles; import org.rstudio.core.client.widget.CanFocus; import org.rstudio.core.client.widget.FindTextBox; import org.rstudio.core.client.widget.FocusHelper; import org.rstudio.core.client.widget.MessageDialog; import org.rstudio.core.client.widget.RStudioThemedFrame; import org.rstudio.core.client.widget.SearchDisplay; import org.rstudio.core.client.widget.SecondaryToolbar; import org.rstudio.core.client.widget.SmallButton; import org.rstudio.core.client.widget.Toolbar; import org.rstudio.core.client.widget.ToolbarButton; import org.rstudio.studio.client.application.Desktop; import org.rstudio.studio.client.application.events.EventBus; import org.rstudio.studio.client.application.ui.RStudioThemes; import org.rstudio.studio.client.common.AutoGlassPanel; import org.rstudio.studio.client.common.GlobalDisplay; import org.rstudio.studio.client.common.GlobalDisplay.NewWindowOptions; import org.rstudio.studio.client.workbench.commands.Commands; import org.rstudio.studio.client.workbench.prefs.model.UserPrefs; import org.rstudio.studio.client.workbench.ui.WorkbenchPane; import org.rstudio.studio.client.workbench.views.console.events.SendToConsoleEvent; import org.rstudio.studio.client.workbench.views.help.Help.LinkMenu; import org.rstudio.studio.client.workbench.views.help.events.HelpNavigateEvent; import org.rstudio.studio.client.workbench.views.help.events.HelpNavigateHandler; import org.rstudio.studio.client.workbench.views.help.model.VirtualHistory; import org.rstudio.studio.client.workbench.views.help.search.HelpSearch; public class HelpPane extends WorkbenchPane implements Help.Display { @Inject public HelpPane(Provider<HelpSearch> searchProvider, GlobalDisplay globalDisplay, Commands commands, EventBus events, UserPrefs prefs) { super("Help"); searchProvider_ = searchProvider; globalDisplay_ = globalDisplay; commands_ = commands; events_ = events; prefs_ = prefs; prefs_.helpFontSizePoints().bind(new CommandWithArg<Double>() { public void execute(Double value) { refresh(); } }); MenuItem clear = commands.clearHelpHistory().createMenuItem(false); history_ = new ToolbarLinkMenu(12, true, null, new MenuItem[] { clear }); Window.addResizeHandler(new ResizeHandler() { public void onResize(ResizeEvent event) { history_.getMenu().hide(); } }); frame_ = new RStudioThemedFrame( "Help Pane", null, RES.editorStyles().getText(), null, false, RStudioThemes.isFlat()); frame_.setSize("100%", "100%"); frame_.setStylePrimaryName("rstudio-HelpFrame"); frame_.addStyleName("ace_editor_theme"); ElementIds.assignElementId(frame_.getElement(), ElementIds.HELP_FRAME); navStack_ = new VirtualHistory(frame_); // NOTE: we do some pretty strange gymnastics to save the scroll // position for the iframe. when the Help Pane is deactivated // (e.g. another tab in the tabset is selected), a synthetic scroll // event is sent to the iframe's window, forcing it to scroll back // to the top of the window. in order to suppress this behavior, we // track whether the scroll event occurred when the tab was deactivated; // if it was, then we restore the last-recorded scroll position instead. scrollTimer_ = new Timer() { @Override public void run() { WindowEx contentWindow = getContentWindow(); if (contentWindow != null) { if (selected_) { scrollPos_ = contentWindow.getScrollPosition(); } else if (scrollPos_ != null) { contentWindow.setScrollPosition(scrollPos_); } } } }; ensureWidget(); } @Override protected Widget createMainWidget() { return new AutoGlassPanel(frame_); } @Override public void onBeforeUnselected() { super.onBeforeUnselected(); selected_ = false; } @Override public void onSelected() { super.onSelected(); selected_ = true; if (scrollPos_ == null) return; IFrameElementEx iframeEl = getIFrameEx(); if (iframeEl == null) return; WindowEx windowEl = iframeEl.getContentWindow(); if (windowEl == null) return; windowEl.setScrollPosition(scrollPos_); } @Override public void onResize() { manageTitleLabelMaxSize(); super.onResize(); } private void manageTitleLabelMaxSize() { if (title_ != null) { int offsetWidth = getOffsetWidth(); if (offsetWidth > 0) { int newWidth = offsetWidth - 25; if (newWidth > 0) title_.getElement().getStyle().setPropertyPx("maxWidth", newWidth); } } } @Override protected void onLoad() { super.onLoad(); if (!initialized_) { initialized_ = true; initHelpCallbacks(); Scheduler.get().scheduleDeferred(new ScheduledCommand() { public void execute() { manageTitleLabelMaxSize(); } }); } } public final native void initHelpCallbacks() /*-{ function addEventHandler(subject, eventName, handler) { if (subject.addEventListener) { subject.addEventListener(eventName, handler, false); } else { subject.attachEvent(eventName, handler); } } var thiz = this; $wnd.helpNavigated = function(document, win) { [email protected]::helpNavigated(Lcom/google/gwt/dom/client/Document;)(document); addEventHandler(win, "unload", function () { [email protected]::unload()(); }); }; $wnd.helpNavigate = function(url) { if (url.length) [email protected]::showHelp(Ljava/lang/String;)(url); }; $wnd.helpKeydown = function(e) { [email protected]::handleKeyDown(Lcom/google/gwt/dom/client/NativeEvent;)(e); }; }-*/; // delegate shortcuts which occur while Help has focus private void handleKeyDown(NativeEvent e) { // determine whether this key-combination means we should focus find int mod = KeyboardShortcut.getModifierValue(e); if (mod == (BrowseCap.hasMetaKey() ? KeyboardShortcut.META : KeyboardShortcut.CTRL)) { if (e.getKeyCode() == 'F') { e.preventDefault(); e.stopPropagation(); WindowEx.get().focus(); findTextBox_.focus(); findTextBox_.selectAll(); return; } else if (e.getKeyCode() == KeyCodes.KEY_ENTER) { // extract the selected code, if any String code = frame_.getWindow().getSelectedText(); if (code.isEmpty()) return; // send it to the console events_.fireEvent(new SendToConsoleEvent( code, true, // execute false // focus )); return; } } // don't let backspace perform browser back DomUtils.preventBackspaceCausingBrowserBack(e); // delegate to the shortcut manager NativeKeyDownEvent evt = new NativeKeyDownEvent(e); ShortcutManager.INSTANCE.onKeyDown(evt); if (evt.isCanceled()) { e.preventDefault(); e.stopPropagation(); // since this is a shortcut handled by the main window // we set focus to it WindowEx.get().focus(); } } private void helpNavigated(Document doc) { NodeList<Element> elements = doc.getElementsByTagName("a"); for (int i = 0; i < elements.getLength(); i++) { ElementEx a = (ElementEx) elements.getItem(i); String href = a.getAttribute("href", 2); if (href == null) continue; if (href.contains(":") || href.endsWith(".pdf")) { // external links AnchorElement aElement = a.cast(); aElement.setTarget("_blank"); } else { // Internal links need to be handled in JavaScript so that // they can participate in virtual session history. This // won't have any effect for right-click > Show in New Window // but that's a good thing. a.setAttribute( "onclick", "window.parent.helpNavigate(this.href); return false"); } } String effectiveTitle = getDocTitle(doc); title_.setText(effectiveTitle); this.fireEvent(new HelpNavigateEvent(doc.getURL(), effectiveTitle)); } private String getDocTitle(Document doc) { String docUrl = StringUtil.notNull(doc.getURL()); String docTitle = doc.getTitle(); String previewPrefix = new String("/help/preview?file="); int previewLoc = docUrl.indexOf(previewPrefix); if (previewLoc != -1) { String file = docUrl.substring(previewLoc + previewPrefix.length()); file = URL.decodeQueryString(file); FileSystemItem fsi = FileSystemItem.createFile(file); docTitle = fsi.getName(); } else if (StringUtil.isNullOrEmpty(docTitle)) { String url = new String(docUrl); url = url.split("\\?")[0]; url = url.split("#")[0]; String[] chunks = url.split("/"); docTitle = chunks[chunks.length - 1]; } return docTitle; } private void unload() { title_.setText(""); } @Override protected Toolbar createMainToolbar() { Toolbar toolbar = new Toolbar("Help Tab"); toolbar.addLeftWidget(commands_.helpBack().createToolbarButton()); toolbar.addLeftWidget(commands_.helpForward().createToolbarButton()); toolbar.addLeftWidget(commands_.helpHome().createToolbarButton()); toolbar.addLeftSeparator(); if (!Desktop.isDesktop()) { // QtWebEngine doesn't currently support window.print(); see: // https://bugreports.qt.io/browse/QTBUG-53745 toolbar.addLeftWidget(commands_.printHelp().createToolbarButton()); toolbar.addLeftSeparator(); } toolbar.addLeftWidget(commands_.helpPopout().createToolbarButton()); searchWidget_ = searchProvider_.get().getSearchWidget(); toolbar.addRightWidget((Widget)searchWidget_); toolbar.addRightSeparator(); ToolbarButton refreshButton = commands_.refreshHelp().createToolbarButton(); refreshButton.addStyleName(ThemeStyles.INSTANCE.refreshToolbarButton()); toolbar.addRightWidget(refreshButton); return toolbar; } @Override protected SecondaryToolbar createSecondaryToolbar() { SecondaryToolbar toolbar = new SecondaryToolbar("Help Tab Second"); title_ = new Label(); title_.addStyleName(RES.styles().topicTitle()); toolbar.addLeftPopupMenu(title_, history_.getMenu()); ThemeStyles styles = ThemeStyles.INSTANCE; toolbar.getWrapper().addStyleName(styles.tallerToolbarWrapper()); if (isFindSupported()) { final SmallButton btnNext = new SmallButton("&gt;", true); btnNext.setTitle("Find next (Enter)"); btnNext.addStyleName(RES.styles().topicNavigationButton()); btnNext.setVisible(false); btnNext.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { findNext(); } }); final SmallButton btnPrev = new SmallButton("&lt;", true); btnPrev.setTitle("Find previous"); btnPrev.addStyleName(RES.styles().topicNavigationButton()); btnPrev.setVisible(false); btnPrev.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { findPrev(); } }); findTextBox_ = new FindTextBox("Find in Topic"); findTextBox_.addStyleName(RES.styles().findTopicTextbox()); findTextBox_.setOverrideWidth(90); ElementIds.assignElementId(findTextBox_, ElementIds.SW_HELP_FIND_IN_TOPIC); toolbar.addLeftWidget(findTextBox_); findTextBox_.addKeyUpHandler(new KeyUpHandler() { @Override public void onKeyUp(KeyUpEvent event) { // ignore modifier key release if (event.getNativeKeyCode() == KeyCodes.KEY_CTRL || event.getNativeKeyCode() == KeyCodes.KEY_ALT || event.getNativeKeyCode() == KeyCodes.KEY_SHIFT) { return; } WindowEx contentWindow = getContentWindow(); if (contentWindow != null) { // escape means exit find mode and put focus // into the main content window if (event.getNativeKeyCode() == KeyCodes.KEY_ESCAPE) { event.preventDefault(); event.stopPropagation(); clearTerm(); contentWindow.focus(); } else { // prevent two enter keys in rapid succession from // minimizing or maximizing the help pane if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { event.preventDefault(); event.stopPropagation(); } // check for term String term = findTextBox_.getValue().trim(); int modifier = KeyboardShortcut.getModifierValue(event.getNativeEvent()); boolean isShift = modifier == KeyboardShortcut.SHIFT; // if there is a term then search for it if (term.length() > 0) { // make buttons visible setButtonVisibility(true); // perform the find (check for incremental) if (isIncrementalFindSupported()) { boolean incremental = !event.isAnyModifierKeyDown() && (event.getNativeKeyCode() != KeyCodes.KEY_ENTER); performFind(term, !isShift, incremental); } else { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) performFind(term, !isShift, false); } } // no term means clear term and remove selection else { if (isIncrementalFindSupported()) { clearTerm(); contentWindow.removeSelection(); } } } } } private void clearTerm() { findTextBox_.setValue(""); setButtonVisibility(false); } private void setButtonVisibility(final boolean visible) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { btnNext.setVisible(visible); btnPrev.setVisible(visible); } }); } }); findTextBox_.addKeyDownHandler(new KeyDownHandler() { @Override public void onKeyDown(KeyDownEvent event) { // we handle these directly so prevent the browser // from handling them if (event.getNativeKeyCode() == KeyCodes.KEY_ESCAPE || event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { event.preventDefault(); event.stopPropagation(); } } }); if (isIncrementalFindSupported()) { btnPrev.getElement().getStyle().setMarginRight(3, Unit.PX); toolbar.addLeftWidget(btnPrev); toolbar.addLeftWidget(btnNext); } } return toolbar; } private String getTerm() { return findTextBox_.getValue().trim(); } private void findNext() { String term = getTerm(); if (term.length() > 0) performFind(term, true, false); } private void findPrev() { String term = getTerm(); if (term.length() > 0) performFind(term, false, false); } private void performFind(String term, boolean forwards, boolean incremental) { WindowEx contentWindow = getContentWindow(); if (contentWindow == null) return; // if this is an incremental search then reset the selection first if (incremental) contentWindow.removeSelection(); contentWindow.find(term, false, !forwards, true, false); } private boolean isFindSupported() { return BrowseCap.INSTANCE.hasWindowFind(); } // Firefox changes focus during our typeahead search (it must take // focus when you set the selection into the iframe) which breaks // typeahead entirely. rather than code around this we simply // disable it for Firefox private boolean isIncrementalFindSupported() { return isFindSupported() && !BrowseCap.isFirefox(); } @Override public String getUrl() { String url = null; try { if (getIFrameEx() != null) url = getIFrameEx().getContentWindow().getLocationHref(); } catch (Exception e) { // attempting to get the URL can throw with a DOM security exception if // the current URL is on another domain--in this case we'll just want // to return null, so eat the exception. } return url; } @Override public String getDocTitle() { return getIFrameEx().getContentDocument().getTitle(); } @Override public void focusSearchHelp() { if (searchWidget_ != null) FocusHelper.setFocusDeferred(searchWidget_); } @Override public void showHelp(String url) { ensureWidget(); bringToFront(); navStack_.navigate(url); setLocation(url, Point.create(0, 0)); navigated_ = true; } private void setLocation(final String url, final Point scrollPos) { // allow subsequent calls to setLocation to override any previous // call (necessary so two consecutive calls like we get during // some startup scenarios don't result in the first url displaying // rather than the second) targetUrl_ = url; RepeatingCommand navigateCommand = new RepeatingCommand() { @SuppressWarnings("unused") private HandlerRegistration handler_ = frame_.addLoadHandler(new LoadHandler() { @Override public void onLoad(LoadEvent event) { WindowEx contentWindow = getIFrameEx().getContentWindow(); contentWindow.setScrollPosition(scrollPos); setWindowScrollHandler(contentWindow); handler_.removeHandler(); handler_ = null; } }); @Override public boolean execute() { if (getIFrameEx() == null) return true; if (getIFrameEx().getContentWindow() == null) return true; if (targetUrl_ == getUrl()) { getIFrameEx().getContentWindow().reload(); } else { frame_.setUrl(targetUrl_); replaceFrameUrl(frame_.getIFrame().cast(), targetUrl_); } return false; } }; if (navigateCommand.execute()) { Scheduler.get().scheduleFixedDelay(navigateCommand, 100); } } @Override public void refresh() { String url = getUrl(); if (url != null) setLocation(url, Point.create(0, 0)); } private WindowEx getContentWindow() { return getIFrameEx() != null ? getIFrameEx().getContentWindow() : null; } @Override public void back() { VirtualHistory.Data back = navStack_.back(); if (back != null) setLocation(back.getUrl(), back.getScrollPosition()); } @Override public void forward() { VirtualHistory.Data fwd = navStack_.forward(); if (fwd != null) setLocation(fwd.getUrl(), fwd.getScrollPosition()); } @Override public void print() { getContentWindow().focus(); getContentWindow().print(); } @Override public void popout() { String href = getContentWindow().getLocationHref(); NewWindowOptions options = new NewWindowOptions(); options.setName("helppanepopout_" + popoutCount_++); globalDisplay_.openWebMinimalWindow(href, false, 0, 0, options); } @Override public void focus() { WindowEx contentWindow = getContentWindow(); if (contentWindow != null) contentWindow.focus(); } @Override public HandlerRegistration addHelpNavigateHandler(HelpNavigateHandler handler) { return addHandler(handler, HelpNavigateEvent.TYPE); } @Override public LinkMenu getHistory() { return history_; } @Override public boolean navigated() { return navigated_; } private IFrameElementEx getIFrameEx() { return frame_.getElement().cast(); } private void findInTopic(String term, CanFocus findInputSource) { // get content window WindowEx contentWindow = getContentWindow(); if (contentWindow == null) return; if (!contentWindow.find(term, false, false, true, false)) { globalDisplay_.showMessage(MessageDialog.INFO, "Find in Topic", "No occurrences found", findInputSource); } } private final native void replaceFrameUrl(JavaScriptObject frame, String url) /*-{ frame.contentWindow.setTimeout(function() { this.location.replace(url); }, 0); }-*/; private final native void setWindowScrollHandler(WindowEx window) /*-{ var self = this; window.onscroll = $entry(function() { [email protected]::onScroll()(); }); }-*/; private void onScroll() { scrollTimer_.schedule(50); } public interface Styles extends CssResource { String findTopicTextbox(); String topicNavigationButton(); String topicTitle(); } public interface EditorStyles extends CssResource { } public interface Resources extends ClientBundle { @Source("HelpPane.css") Styles styles(); @Source("HelpPaneEditorStyles.css") EditorStyles editorStyles(); } private static final Resources RES = GWT.create(Resources.class); static { RES.styles().ensureInjected(); } private UserPrefs prefs_; private final VirtualHistory navStack_; private final ToolbarLinkMenu history_; private Label title_; private RStudioThemedFrame frame_; private FindTextBox findTextBox_; private final Provider<HelpSearch> searchProvider_; private GlobalDisplay globalDisplay_; private final Commands commands_; private final EventBus events_; private boolean navigated_; private boolean initialized_; private String targetUrl_; private Point scrollPos_; private Timer scrollTimer_; private boolean selected_; private static int popoutCount_ = 0; private SearchDisplay searchWidget_; }
src/gwt/src/org/rstudio/studio/client/workbench/views/help/HelpPane.java
/* * HelpPane.java * * Copyright (C) 2009-20 by RStudio, PBC * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.studio.client.workbench.views.help; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.RepeatingCommand; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.dom.client.*; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; 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.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.event.dom.client.LoadEvent; import com.google.gwt.event.dom.client.LoadHandler; import com.google.gwt.event.logical.shared.ResizeEvent; import com.google.gwt.event.logical.shared.ResizeHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.http.client.URL; import com.google.gwt.resources.client.ClientBundle; import com.google.gwt.resources.client.CssResource; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.*; import com.google.inject.Inject; import com.google.inject.Provider; import org.rstudio.core.client.BrowseCap; import org.rstudio.core.client.CommandWithArg; import org.rstudio.core.client.ElementIds; import org.rstudio.core.client.Point; import org.rstudio.core.client.StringUtil; import org.rstudio.core.client.command.KeyboardShortcut; import org.rstudio.core.client.command.ShortcutManager; import org.rstudio.core.client.dom.DomUtils; import org.rstudio.core.client.dom.ElementEx; import org.rstudio.core.client.dom.IFrameElementEx; import org.rstudio.core.client.dom.WindowEx; import org.rstudio.core.client.events.NativeKeyDownEvent; import org.rstudio.core.client.files.FileSystemItem; import org.rstudio.core.client.theme.res.ThemeStyles; import org.rstudio.core.client.widget.CanFocus; import org.rstudio.core.client.widget.FindTextBox; import org.rstudio.core.client.widget.FocusHelper; import org.rstudio.core.client.widget.MessageDialog; import org.rstudio.core.client.widget.RStudioThemedFrame; import org.rstudio.core.client.widget.SearchDisplay; import org.rstudio.core.client.widget.SecondaryToolbar; import org.rstudio.core.client.widget.SmallButton; import org.rstudio.core.client.widget.Toolbar; import org.rstudio.core.client.widget.ToolbarButton; import org.rstudio.studio.client.application.Desktop; import org.rstudio.studio.client.application.events.EventBus; import org.rstudio.studio.client.application.ui.RStudioThemes; import org.rstudio.studio.client.common.AutoGlassPanel; import org.rstudio.studio.client.common.GlobalDisplay; import org.rstudio.studio.client.common.GlobalDisplay.NewWindowOptions; import org.rstudio.studio.client.workbench.commands.Commands; import org.rstudio.studio.client.workbench.prefs.model.UserPrefs; import org.rstudio.studio.client.workbench.ui.WorkbenchPane; import org.rstudio.studio.client.workbench.views.console.events.SendToConsoleEvent; import org.rstudio.studio.client.workbench.views.help.Help.LinkMenu; import org.rstudio.studio.client.workbench.views.help.events.HelpNavigateEvent; import org.rstudio.studio.client.workbench.views.help.events.HelpNavigateHandler; import org.rstudio.studio.client.workbench.views.help.model.VirtualHistory; import org.rstudio.studio.client.workbench.views.help.search.HelpSearch; public class HelpPane extends WorkbenchPane implements Help.Display { @Inject public HelpPane(Provider<HelpSearch> searchProvider, GlobalDisplay globalDisplay, Commands commands, EventBus events, UserPrefs prefs) { super("Help"); searchProvider_ = searchProvider; globalDisplay_ = globalDisplay; commands_ = commands; events_ = events; prefs_ = prefs; prefs_.helpFontSizePoints().bind(new CommandWithArg<Double>() { public void execute(Double value) { refresh(); } }); MenuItem clear = commands.clearHelpHistory().createMenuItem(false); history_ = new ToolbarLinkMenu(12, true, null, new MenuItem[] { clear }); Window.addResizeHandler(new ResizeHandler() { public void onResize(ResizeEvent event) { history_.getMenu().hide(); } }); frame_ = new RStudioThemedFrame( "Help Pane", null, RES.editorStyles().getText(), null, false, RStudioThemes.isFlat()); frame_.setSize("100%", "100%"); frame_.setStylePrimaryName("rstudio-HelpFrame"); frame_.addStyleName("ace_editor_theme"); ElementIds.assignElementId(frame_.getElement(), ElementIds.HELP_FRAME); navStack_ = new VirtualHistory(frame_); // NOTE: we do some pretty strange gymnastics to save the scroll // position for the iframe. when the Help Pane is deactivated // (e.g. another tab in the tabset is selected), a synthetic scroll // event is sent to the iframe's window, forcing it to scroll back // to the top of the window. in order to suppress this behavior, we // track whether the scroll event occurred when the tab was deactivated; // if it was, then we restore the last-recorded scroll position instead. scrollTimer_ = new Timer() { @Override public void run() { WindowEx contentWindow = getContentWindow(); if (contentWindow != null) { if (selected_) { scrollPos_ = contentWindow.getScrollPosition(); } else if (scrollPos_ != null) { contentWindow.setScrollPosition(scrollPos_); } } } }; ensureWidget(); } @Override protected Widget createMainWidget() { return new AutoGlassPanel(frame_); } @Override public void onBeforeUnselected() { super.onBeforeUnselected(); selected_ = false; } @Override public void onSelected() { super.onSelected(); selected_ = true; if (scrollPos_ == null) return; IFrameElementEx iframeEl = getIFrameEx(); if (iframeEl == null) return; WindowEx windowEl = iframeEl.getContentWindow(); if (windowEl == null) return; windowEl.setScrollPosition(scrollPos_); } @Override public void onResize() { manageTitleLabelMaxSize(); super.onResize(); } private void manageTitleLabelMaxSize() { if (title_ != null) { int offsetWidth = getOffsetWidth(); if (offsetWidth > 0) { int newWidth = offsetWidth - 25; if (newWidth > 0) title_.getElement().getStyle().setPropertyPx("maxWidth", newWidth); } } } @Override protected void onLoad() { super.onLoad(); if (!initialized_) { initialized_ = true; initHelpCallbacks(); Scheduler.get().scheduleDeferred(new ScheduledCommand() { public void execute() { manageTitleLabelMaxSize(); } }); } } public final native void initHelpCallbacks() /*-{ function addEventHandler(subject, eventName, handler) { if (subject.addEventListener) { subject.addEventListener(eventName, handler, false); } else { subject.attachEvent(eventName, handler); } } var thiz = this; $wnd.helpNavigated = function(document, win) { [email protected]::helpNavigated(Lcom/google/gwt/dom/client/Document;)(document); addEventHandler(win, "unload", function () { [email protected]::unload()(); }); }; $wnd.helpNavigate = function(url) { if (url.length) [email protected]::showHelp(Ljava/lang/String;)(url); }; $wnd.helpKeydown = function(e) { [email protected]::handleKeyDown(Lcom/google/gwt/dom/client/NativeEvent;)(e); }; }-*/; // delegate shortcuts which occur while Help has focus private void handleKeyDown(NativeEvent e) { // determine whether this key-combination means we should focus find int mod = KeyboardShortcut.getModifierValue(e); if (mod == (BrowseCap.hasMetaKey() ? KeyboardShortcut.META : KeyboardShortcut.CTRL)) { if (e.getKeyCode() == 'F') { e.preventDefault(); e.stopPropagation(); WindowEx.get().focus(); findTextBox_.focus(); findTextBox_.selectAll(); return; } else if (e.getKeyCode() == KeyCodes.KEY_ENTER) { // extract the selected code, if any String code = frame_.getWindow().getSelectedText(); if (code.isEmpty()) return; // send it to the console events_.fireEvent(new SendToConsoleEvent( code, true, // execute false // focus )); return; } } // don't let backspace perform browser back DomUtils.preventBackspaceCausingBrowserBack(e); // delegate to the shortcut manager NativeKeyDownEvent evt = new NativeKeyDownEvent(e); ShortcutManager.INSTANCE.onKeyDown(evt); if (evt.isCanceled()) { e.preventDefault(); e.stopPropagation(); // since this is a shortcut handled by the main window // we set focus to it WindowEx.get().focus(); } } private void helpNavigated(Document doc) { NodeList<Element> elements = doc.getElementsByTagName("a"); for (int i = 0; i < elements.getLength(); i++) { ElementEx a = (ElementEx) elements.getItem(i); String href = a.getAttribute("href", 2); if (href == null) continue; if (href.contains(":") || href.endsWith(".pdf")) { // external links AnchorElement aElement = a.cast(); aElement.setTarget("_blank"); } else { // Internal links need to be handled in JavaScript so that // they can participate in virtual session history. This // won't have any effect for right-click > Show in New Window // but that's a good thing. a.setAttribute( "onclick", "window.parent.helpNavigate(this.href); return false"); } } String effectiveTitle = getDocTitle(doc); title_.setText(effectiveTitle); this.fireEvent(new HelpNavigateEvent(doc.getURL(), effectiveTitle)); } private String getDocTitle(Document doc) { String docUrl = StringUtil.notNull(doc.getURL()); String docTitle = doc.getTitle(); String previewPrefix = new String("/help/preview?file="); int previewLoc = docUrl.indexOf(previewPrefix); if (previewLoc != -1) { String file = docUrl.substring(previewLoc + previewPrefix.length()); file = URL.decodeQueryString(file); FileSystemItem fsi = FileSystemItem.createFile(file); docTitle = fsi.getName(); } else if (StringUtil.isNullOrEmpty(docTitle)) { String url = new String(docUrl); url = url.split("\\?")[0]; url = url.split("#")[0]; String[] chunks = url.split("/"); docTitle = chunks[chunks.length - 1]; } return docTitle; } private void unload() { title_.setText(""); } @Override protected Toolbar createMainToolbar() { Toolbar toolbar = new Toolbar("Help Tab"); toolbar.addLeftWidget(commands_.helpBack().createToolbarButton()); toolbar.addLeftWidget(commands_.helpForward().createToolbarButton()); toolbar.addLeftWidget(commands_.helpHome().createToolbarButton()); toolbar.addLeftSeparator(); if (!Desktop.isDesktop()) { // QtWebEngine doesn't currently support window.print(); see: // https://bugreports.qt.io/browse/QTBUG-53745 toolbar.addLeftWidget(commands_.printHelp().createToolbarButton()); toolbar.addLeftSeparator(); } toolbar.addLeftWidget(commands_.helpPopout().createToolbarButton()); searchWidget_ = searchProvider_.get().getSearchWidget(); toolbar.addRightWidget((Widget)searchWidget_); toolbar.addRightSeparator(); ToolbarButton refreshButton = commands_.refreshHelp().createToolbarButton(); refreshButton.addStyleName(ThemeStyles.INSTANCE.refreshToolbarButton()); toolbar.addRightWidget(refreshButton); return toolbar; } @Override protected SecondaryToolbar createSecondaryToolbar() { SecondaryToolbar toolbar = new SecondaryToolbar("Help Tab Second"); title_ = new Label(); title_.addStyleName(RES.styles().topicTitle()); toolbar.addLeftPopupMenu(title_, history_.getMenu()); ThemeStyles styles = ThemeStyles.INSTANCE; toolbar.getWrapper().addStyleName(styles.tallerToolbarWrapper()); if (isFindSupported()) { final SmallButton btnNext = new SmallButton("&gt;", true); btnNext.setTitle("Find next (Enter)"); btnNext.addStyleName(RES.styles().topicNavigationButton()); btnNext.setVisible(false); btnNext.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { findNext(); } }); final SmallButton btnPrev = new SmallButton("&lt;", true); btnPrev.setTitle("Find previous"); btnPrev.addStyleName(RES.styles().topicNavigationButton()); btnPrev.setVisible(false); btnPrev.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { findPrev(); } }); findTextBox_ = new FindTextBox("Find in Topic"); findTextBox_.addStyleName(RES.styles().findTopicTextbox()); findTextBox_.setOverrideWidth(90); ElementIds.assignElementId(findTextBox_, ElementIds.SW_HELP_FIND_IN_TOPIC); toolbar.addLeftWidget(findTextBox_); findTextBox_.addKeyUpHandler(new KeyUpHandler() { @Override public void onKeyUp(KeyUpEvent event) { // ignore modifier key release if (event.getNativeKeyCode() == KeyCodes.KEY_CTRL || event.getNativeKeyCode() == KeyCodes.KEY_ALT || event.getNativeKeyCode() == KeyCodes.KEY_SHIFT) { return; } WindowEx contentWindow = getContentWindow(); if (contentWindow != null) { // escape or tab means exit find mode and put focus // into the main content window if (event.getNativeKeyCode() == KeyCodes.KEY_ESCAPE || event.getNativeKeyCode() == KeyCodes.KEY_TAB) { event.preventDefault(); event.stopPropagation(); if (event.getNativeKeyCode() == KeyCodes.KEY_ESCAPE) clearTerm(); contentWindow.focus(); } else { // prevent two enter keys in rapid succession from // minimizing or maximizing the help pane if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { event.preventDefault(); event.stopPropagation(); } // check for term String term = findTextBox_.getValue().trim(); int modifier = KeyboardShortcut.getModifierValue(event.getNativeEvent()); boolean isShift = modifier == KeyboardShortcut.SHIFT; // if there is a term then search for it if (term.length() > 0) { // make buttons visible setButtonVisibility(true); // perform the find (check for incremental) if (isIncrementalFindSupported()) { boolean incremental = !event.isAnyModifierKeyDown() && (event.getNativeKeyCode() != KeyCodes.KEY_ENTER); performFind(term, !isShift, incremental); } else { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) performFind(term, !isShift, false); } } // no term means clear term and remove selection else { if (isIncrementalFindSupported()) { clearTerm(); contentWindow.removeSelection(); } } } } } private void clearTerm() { findTextBox_.setValue(""); setButtonVisibility(false); } private void setButtonVisibility(final boolean visible) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { btnNext.setVisible(visible); btnPrev.setVisible(visible); } }); } }); findTextBox_.addKeyDownHandler(new KeyDownHandler() { @Override public void onKeyDown(KeyDownEvent event) { // we handle these directly so prevent the browser // from handling them if (event.getNativeKeyCode() == KeyCodes.KEY_ESCAPE || event.getNativeKeyCode() == KeyCodes.KEY_TAB || event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { event.preventDefault(); event.stopPropagation(); } } }); if (isIncrementalFindSupported()) { btnPrev.getElement().getStyle().setMarginRight(3, Unit.PX); toolbar.addLeftWidget(btnPrev); toolbar.addLeftWidget(btnNext); } } return toolbar; } private String getTerm() { return findTextBox_.getValue().trim(); } private void findNext() { String term = getTerm(); if (term.length() > 0) performFind(term, true, false); } private void findPrev() { String term = getTerm(); if (term.length() > 0) performFind(term, false, false); } private void performFind(String term, boolean forwards, boolean incremental) { WindowEx contentWindow = getContentWindow(); if (contentWindow == null) return; // if this is an incremental search then reset the selection first if (incremental) contentWindow.removeSelection(); contentWindow.find(term, false, !forwards, true, false); } private boolean isFindSupported() { return BrowseCap.INSTANCE.hasWindowFind(); } // Firefox changes focus during our typeahead search (it must take // focus when you set the selection into the iframe) which breaks // typeahead entirely. rather than code around this we simply // disable it for Firefox private boolean isIncrementalFindSupported() { return isFindSupported() && !BrowseCap.isFirefox(); } @Override public String getUrl() { String url = null; try { if (getIFrameEx() != null) url = getIFrameEx().getContentWindow().getLocationHref(); } catch (Exception e) { // attempting to get the URL can throw with a DOM security exception if // the current URL is on another domain--in this case we'll just want // to return null, so eat the exception. } return url; } @Override public String getDocTitle() { return getIFrameEx().getContentDocument().getTitle(); } @Override public void focusSearchHelp() { if (searchWidget_ != null) FocusHelper.setFocusDeferred(searchWidget_); } @Override public void showHelp(String url) { ensureWidget(); bringToFront(); navStack_.navigate(url); setLocation(url, Point.create(0, 0)); navigated_ = true; } private void setLocation(final String url, final Point scrollPos) { // allow subsequent calls to setLocation to override any previous // call (necessary so two consecutive calls like we get during // some startup scenarios don't result in the first url displaying // rather than the second) targetUrl_ = url; RepeatingCommand navigateCommand = new RepeatingCommand() { @SuppressWarnings("unused") private HandlerRegistration handler_ = frame_.addLoadHandler(new LoadHandler() { @Override public void onLoad(LoadEvent event) { WindowEx contentWindow = getIFrameEx().getContentWindow(); contentWindow.setScrollPosition(scrollPos); setWindowScrollHandler(contentWindow); handler_.removeHandler(); handler_ = null; } }); @Override public boolean execute() { if (getIFrameEx() == null) return true; if (getIFrameEx().getContentWindow() == null) return true; if (targetUrl_ == getUrl()) { getIFrameEx().getContentWindow().reload(); } else { frame_.setUrl(targetUrl_); replaceFrameUrl(frame_.getIFrame().cast(), targetUrl_); } return false; } }; if (navigateCommand.execute()) { Scheduler.get().scheduleFixedDelay(navigateCommand, 100); } } @Override public void refresh() { String url = getUrl(); if (url != null) setLocation(url, Point.create(0, 0)); } private WindowEx getContentWindow() { return getIFrameEx() != null ? getIFrameEx().getContentWindow() : null; } @Override public void back() { VirtualHistory.Data back = navStack_.back(); if (back != null) setLocation(back.getUrl(), back.getScrollPosition()); } @Override public void forward() { VirtualHistory.Data fwd = navStack_.forward(); if (fwd != null) setLocation(fwd.getUrl(), fwd.getScrollPosition()); } @Override public void print() { getContentWindow().focus(); getContentWindow().print(); } @Override public void popout() { String href = getContentWindow().getLocationHref(); NewWindowOptions options = new NewWindowOptions(); options.setName("helppanepopout_" + popoutCount_++); globalDisplay_.openWebMinimalWindow(href, false, 0, 0, options); } @Override public void focus() { WindowEx contentWindow = getContentWindow(); if (contentWindow != null) contentWindow.focus(); } @Override public HandlerRegistration addHelpNavigateHandler(HelpNavigateHandler handler) { return addHandler(handler, HelpNavigateEvent.TYPE); } @Override public LinkMenu getHistory() { return history_; } @Override public boolean navigated() { return navigated_; } private IFrameElementEx getIFrameEx() { return frame_.getElement().cast(); } private void findInTopic(String term, CanFocus findInputSource) { // get content window WindowEx contentWindow = getContentWindow(); if (contentWindow == null) return; if (!contentWindow.find(term, false, false, true, false)) { globalDisplay_.showMessage(MessageDialog.INFO, "Find in Topic", "No occurrences found", findInputSource); } } private final native void replaceFrameUrl(JavaScriptObject frame, String url) /*-{ frame.contentWindow.setTimeout(function() { this.location.replace(url); }, 0); }-*/; private final native void setWindowScrollHandler(WindowEx window) /*-{ var self = this; window.onscroll = $entry(function() { [email protected]::onScroll()(); }); }-*/; private void onScroll() { scrollTimer_.schedule(50); } public interface Styles extends CssResource { String findTopicTextbox(); String topicNavigationButton(); String topicTitle(); } public interface EditorStyles extends CssResource { } public interface Resources extends ClientBundle { @Source("HelpPane.css") Styles styles(); @Source("HelpPaneEditorStyles.css") EditorStyles editorStyles(); } private static final Resources RES = GWT.create(Resources.class); static { RES.styles().ensureInjected(); } private UserPrefs prefs_; private final VirtualHistory navStack_; private final ToolbarLinkMenu history_; private Label title_; private RStudioThemedFrame frame_; private FindTextBox findTextBox_; private final Provider<HelpSearch> searchProvider_; private GlobalDisplay globalDisplay_; private final Commands commands_; private final EventBus events_; private boolean navigated_; private boolean initialized_; private String targetUrl_; private Point scrollPos_; private Timer scrollTimer_; private boolean selected_; private static int popoutCount_ = 0; private SearchDisplay searchWidget_; }
allow Tab key to move focus normally in Help pane secondary toolbar - Fixes #6091
src/gwt/src/org/rstudio/studio/client/workbench/views/help/HelpPane.java
allow Tab key to move focus normally in Help pane secondary toolbar
<ide><path>rc/gwt/src/org/rstudio/studio/client/workbench/views/help/HelpPane.java <ide> WindowEx contentWindow = getContentWindow(); <ide> if (contentWindow != null) <ide> { <del> // escape or tab means exit find mode and put focus <add> // escape means exit find mode and put focus <ide> // into the main content window <del> if (event.getNativeKeyCode() == KeyCodes.KEY_ESCAPE || <del> event.getNativeKeyCode() == KeyCodes.KEY_TAB) <add> if (event.getNativeKeyCode() == KeyCodes.KEY_ESCAPE) <ide> { <ide> event.preventDefault(); <ide> event.stopPropagation(); <del> if (event.getNativeKeyCode() == KeyCodes.KEY_ESCAPE) <del> clearTerm(); <add> clearTerm(); <ide> contentWindow.focus(); <ide> } <ide> else <ide> // we handle these directly so prevent the browser <ide> // from handling them <ide> if (event.getNativeKeyCode() == KeyCodes.KEY_ESCAPE || <del> event.getNativeKeyCode() == KeyCodes.KEY_TAB || <ide> event.getNativeKeyCode() == KeyCodes.KEY_ENTER) <ide> { <ide> event.preventDefault();
Java
apache-2.0
6f22aded4fbfcc163d8e2b7d54a13606f9470159
0
abel-von/commons,atollena/commons,abel-von/commons,Yasumoto/commons,jsirois/commons,ericzundel/commons,nkhuyu/commons,jsirois/commons,nkhuyu/commons,ericzundel/commons,WCCCEDU/twitter-commons,nkhuyu/commons,nkhuyu/commons,abel-von/commons,cevaris/commons,brutkin/commons,pombredanne/commons,pombredanne/commons,jsirois/commons,Yasumoto/commons,WCCCEDU/twitter-commons,ericzundel/commons,cevaris/commons,WCCCEDU/twitter-commons,Yasumoto/commons,Yasumoto/commons,atollena/commons,abel-von/commons,atollena/commons,WCCCEDU/twitter-commons,nkhuyu/commons,brutkin/commons,brutkin/commons,brutkin/commons,VaybhavSharma/commons,VaybhavSharma/commons,jsirois/commons,cevaris/commons,cevaris/commons,imsut/commons,imsut/commons,ericzundel/commons,VaybhavSharma/commons,Yasumoto/commons,pombredanne/commons,cevaris/commons,VaybhavSharma/commons,ericzundel/commons,pombredanne/commons,abel-von/commons,WCCCEDU/twitter-commons,brutkin/commons,pombredanne/commons,atollena/commons,imsut/commons,jsirois/commons,atollena/commons,VaybhavSharma/commons
// ================================================================================================= // Copyright 2011 Twitter, Inc. // ------------------------------------------------------------------------------------------------- // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this work except in compliance with the License. // You may obtain a copy of the License in the LICENSE file, or 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.twitter.common.zookeeper; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Ordering; import org.apache.zookeeper.KeeperException; import com.twitter.common.base.Command; import com.twitter.common.base.ExceptionalCommand; import com.twitter.common.zookeeper.Group.GroupChangeListener; import com.twitter.common.zookeeper.Group.JoinException; import com.twitter.common.zookeeper.Group.Membership; import com.twitter.common.zookeeper.Group.WatchException; import com.twitter.common.zookeeper.ZooKeeperClient.ZooKeeperConnectionException; /** * Implements leader election for small groups of candidates. This implementation is subject to the * <a href="http://hadoop.apache.org/zookeeper/docs/r3.2.1/recipes.html#sc_leaderElection"> * herd effect</a> for a given group and should only be used for small (~10 member) candidate pools. * * @author John Sirois */ public class CandidateImpl implements Candidate { private static final Logger LOG = Logger.getLogger(CandidateImpl.class.getName()); private final Group group; private final Function<Iterable<String>, String> judge; private final Supplier<byte[]> dataSupplier; static final Supplier<byte[]> IP_ADDRESS_DATA_SUPPLIER = new Supplier<byte[]>() { @Override public byte[] get() { try { return InetAddress.getLocalHost().getAddress(); } catch (UnknownHostException e) { LOG.log(Level.WARNING, "Failed to determine local address!", e); return new byte[0]; } } }; public static final Function<Iterable<String>, String> MOST_RECENT_JUDGE = new Function<Iterable<String>, String>() { @Override public String apply(Iterable<String> candidates) { return Ordering.natural().min(candidates); } }; /** * Equivalent to {@link #CandidateImpl(Group, com.google.common.base.Function, Supplier)} using a judge that * always picks the lowest numbered candidate ephemeral node - by proxy the oldest or 1st * candidate and a default supplier that populates the data in the underlying znode with the byte representation * of the ip address according to {@link java.net.InetAddress#getLocalHost()}. */ public CandidateImpl(Group group) { this(group, MOST_RECENT_JUDGE, IP_ADDRESS_DATA_SUPPLIER); } /** * Creates a candidate that can be used to offer leadership for the given {@code group} using a judge that * always picks the lowest numbered candidate ephemeral node - by proxy the oldest or 1st. The dataSupplier is the * source of the data that will be stored in the leader-znode and which is available to all participants via the * getLeaderData method. */ public CandidateImpl(Group group, Supplier<byte[]> dataSupplier) { this(group, MOST_RECENT_JUDGE, dataSupplier); } /** * Creates a candidate that can be used to offer leadership for the given {@code group}. The * {@code judge} is used to pick the current leader from all group members whenever the group * membership changes. To form a well-behaved election group with one leader, all candidates * should use the same judge. The dataSupplier is the source of the data that will be stored * in the leader-znode and which is available to all participants via the getLeaderData method. */ public CandidateImpl(Group group, Function<Iterable<String>, String> judge, Supplier<byte[]> dataSupplier) { this.group = Preconditions.checkNotNull(group); this.judge = Preconditions.checkNotNull(judge); this.dataSupplier = Preconditions.checkNotNull(dataSupplier); } @Override public byte[] getLeaderData() throws ZooKeeperConnectionException, KeeperException, InterruptedException { String leaderId = getLeader(group.getMemberIds()); if (leaderId == null) { return null; } byte[] data = group.getMemberData(leaderId); return data == null ? new byte[0] : data; } @Override public Supplier<Boolean> offerLeadership(final Leader leader) throws JoinException, WatchException, InterruptedException { final Membership membership = group.join(dataSupplier, new Command() { @Override public void execute() { leader.onDefeated(); } }); final AtomicBoolean elected = new AtomicBoolean(false); final AtomicBoolean abdicated = new AtomicBoolean(false); group.watch(new GroupChangeListener() { @Override public void onGroupChange(Iterable<String> memberIds) { boolean noCandidates = Iterables.isEmpty(memberIds); String memberId = membership.getMemberId(); if (noCandidates) { LOG.warning("All candidates have temporarily left the group: " + group); } else if (!Iterables.contains(memberIds, memberId)) { LOG.severe(String.format( "Current member ID %s is not a candidate for leader, current voting: %s", memberId, memberIds)); } else { boolean electedLeader = memberId.equals(getLeader(memberIds)); boolean previouslyElected = elected.getAndSet(electedLeader); if (!previouslyElected && electedLeader) { LOG.info(String.format("Candidate %s is now leader of group: %s", membership.getMemberPath(), memberIds)); leader.onElected(new ExceptionalCommand<JoinException>() { @Override public void execute() throws JoinException { membership.cancel(); abdicated.set(true); } }); } else if (!electedLeader) { if (previouslyElected) { leader.onDefeated(); } LOG.info(String.format( "Candidate %s waiting for the next leader election, current voting: %s", membership.getMemberPath(), memberIds)); } } } }); return new Supplier<Boolean>() { @Override public Boolean get() { return !abdicated.get() && elected.get(); } }; } private String getLeader(Iterable<String> memberIds) { return judge.apply(memberIds); } }
src/java/com/twitter/common/zookeeper/CandidateImpl.java
// ================================================================================================= // Copyright 2011 Twitter, Inc. // ------------------------------------------------------------------------------------------------- // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this work except in compliance with the License. // You may obtain a copy of the License in the LICENSE file, or 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.twitter.common.zookeeper; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Ordering; import org.apache.zookeeper.KeeperException; import com.twitter.common.base.Command; import com.twitter.common.base.ExceptionalCommand; import com.twitter.common.zookeeper.Group.GroupChangeListener; import com.twitter.common.zookeeper.Group.JoinException; import com.twitter.common.zookeeper.Group.Membership; import com.twitter.common.zookeeper.Group.WatchException; import com.twitter.common.zookeeper.ZooKeeperClient.ZooKeeperConnectionException; /** * Implements leader election for small groups of candidates. This implementation is subject to the * <a href="http://hadoop.apache.org/zookeeper/docs/r3.2.1/recipes.html#sc_leaderElection"> * herd effect</a> for a given group and should only be used for small (~10 member) candidate pools. * * @author John Sirois */ public class CandidateImpl implements Candidate { private static final Logger LOG = Logger.getLogger(CandidateImpl.class.getName()); private final Group group; private final Function<Iterable<String>, String> judge; private final Supplier<byte[]> dataSupplier; static final Supplier<byte[]> IP_ADDRESS_DATA_SUPPLIER = new Supplier<byte[]>() { @Override public byte[] get() { try { return InetAddress.getLocalHost().getAddress(); } catch (UnknownHostException e) { LOG.log(Level.WARNING, "Failed to determine local address!", e); return new byte[0]; } } }; public static final Function<Iterable<String>, String> MOST_RECENT_JUDGE = new Function<Iterable<String>, String>() { @Override public String apply(Iterable<String> candidates) { return Ordering.natural().min(candidates); } }; /** * Equivalent to {@link #CandidateImpl(Group, com.google.common.base.Function, Supplier)} using a judge that * always picks the lowest numbered candidate ephemeral node - by proxy the oldest or 1st * candidate and a default supplier that populates the data in the underlying znode with the byte representation * of the ip address according to {@link java.net.InetAddress#getLocalHost()}. */ public CandidateImpl(Group group) { this(group, MOST_RECENT_JUDGE, IP_ADDRESS_DATA_SUPPLIER); } /** * Creates a candidate that can be used to offer leadership for the given {@code group}. The * {@code judge} is used to pick the current leader from all group members whenever the group * membership changes. To form a well-behaved election group with one leader, all candidates * should use the same judge. The dataSupplier is the source of the data that will be stored * in the leader-znode and which is available to all participants via the getLeaderData method. */ public CandidateImpl(Group group, Function<Iterable<String>, String> judge, Supplier<byte[]> dataSupplier) { this.group = Preconditions.checkNotNull(group); this.judge = Preconditions.checkNotNull(judge); this.dataSupplier = Preconditions.checkNotNull(dataSupplier); } @Override public byte[] getLeaderData() throws ZooKeeperConnectionException, KeeperException, InterruptedException { String leaderId = getLeader(group.getMemberIds()); if (leaderId == null) { return null; } byte[] data = group.getMemberData(leaderId); return data == null ? new byte[0] : data; } @Override public Supplier<Boolean> offerLeadership(final Leader leader) throws JoinException, WatchException, InterruptedException { final Membership membership = group.join(dataSupplier, new Command() { @Override public void execute() { leader.onDefeated(); } }); final AtomicBoolean elected = new AtomicBoolean(false); final AtomicBoolean abdicated = new AtomicBoolean(false); group.watch(new GroupChangeListener() { @Override public void onGroupChange(Iterable<String> memberIds) { boolean noCandidates = Iterables.isEmpty(memberIds); String memberId = membership.getMemberId(); if (noCandidates) { LOG.warning("All candidates have temporarily left the group: " + group); } else if (!Iterables.contains(memberIds, memberId)) { LOG.severe(String.format( "Current member ID %s is not a candidate for leader, current voting: %s", memberId, memberIds)); } else { boolean electedLeader = memberId.equals(getLeader(memberIds)); boolean previouslyElected = elected.getAndSet(electedLeader); if (!previouslyElected && electedLeader) { LOG.info(String.format("Candidate %s is now leader of group: %s", membership.getMemberPath(), memberIds)); leader.onElected(new ExceptionalCommand<JoinException>() { @Override public void execute() throws JoinException { membership.cancel(); abdicated.set(true); } }); } else if (!electedLeader) { if (previouslyElected) { leader.onDefeated(); } LOG.info(String.format( "Candidate %s waiting for the next leader election, current voting: %s", membership.getMemberPath(), memberIds)); } } } }); return new Supplier<Boolean>() { @Override public Boolean get() { return !abdicated.get() && elected.get(); } }; } private String getLeader(Iterable<String> memberIds) { return judge.apply(memberIds); } }
Adding constructor for custom data supplier.
src/java/com/twitter/common/zookeeper/CandidateImpl.java
Adding constructor for custom data supplier.
<ide><path>rc/java/com/twitter/common/zookeeper/CandidateImpl.java <ide> */ <ide> public CandidateImpl(Group group) { <ide> this(group, MOST_RECENT_JUDGE, IP_ADDRESS_DATA_SUPPLIER); <add> } <add> <add> /** <add> * Creates a candidate that can be used to offer leadership for the given {@code group} using a judge that <add> * always picks the lowest numbered candidate ephemeral node - by proxy the oldest or 1st. The dataSupplier is the <add> * source of the data that will be stored in the leader-znode and which is available to all participants via the <add> * getLeaderData method. <add> */ <add> public CandidateImpl(Group group, Supplier<byte[]> dataSupplier) { <add> this(group, MOST_RECENT_JUDGE, dataSupplier); <ide> } <ide> <ide> /**
Java
mit
572ad9e02ab5f45d325c7053e921d27b82a4e5f3
0
enanomapper/slimmer
package com.github.enanomapper; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.StringReader; import java.util.Iterator; import java.util.Set; import org.junit.Assert; import org.junit.Test; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLClass; import org.semanticweb.owlapi.model.OWLClassAxiom; import org.semanticweb.owlapi.model.OWLEntity; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyCreationException; import org.semanticweb.owlapi.model.parameters.Imports; import org.semanticweb.owlapi.search.Searcher; public class SlimmerTest { @Test public void testLoading() throws OWLOntologyCreationException { InputStream stream = this.getClass().getClassLoader().getResourceAsStream("bfo-1.1.owl"); Slimmer slimmer = new Slimmer(stream); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertNotSame(0, ontology.getAxiomCount()); } @Test public void testParsingUp() throws Exception { String test = "+U:http://www.ifomis.org/bfo/1.1/snap#DependentContinuant"; Configuration conf = new Configuration(); conf.read(new StringReader(test)); Set<Instruction> irisToSave = conf.getTreePartsToSave(); Assert.assertEquals(1, conf.getTreePartsToSave().size()); InputStream stream = this.getClass().getClassLoader().getResourceAsStream("bfo-1.1.owl"); Slimmer slimmer = new Slimmer(stream); slimmer.removeAllExcept(irisToSave); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(3, ontology.getClassesInSignature().size()); } @Test public void testParsingSingle() throws Exception { String test = "+:http://www.ifomis.org/bfo/1.1/snap#DependentContinuant"; Configuration conf = new Configuration(); conf.read(new StringReader(test)); Set<Instruction> irisToSave = conf.getTreePartsToSave(); Assert.assertEquals(1, conf.getTreePartsToSave().size()); InputStream stream = this.getClass().getClassLoader().getResourceAsStream("bfo-1.1.owl"); Slimmer slimmer = new Slimmer(stream); slimmer.removeAllExcept(irisToSave); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(1, ontology.getClassesInSignature().size()); } @Test public void testParsingDown() throws Exception { String test = "+D:http://www.ifomis.org/bfo/1.1/snap#MaterialEntity"; Configuration conf = new Configuration(); conf.read(new StringReader(test)); Set<Instruction> irisToSave = conf.getTreePartsToSave(); Assert.assertEquals(1, conf.getTreePartsToSave().size()); InputStream stream = this.getClass().getClassLoader().getResourceAsStream("bfo-1.1.owl"); Slimmer slimmer = new Slimmer(stream); slimmer.removeAllExcept(irisToSave); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(4, ontology.getClassesInSignature().size()); } @Test public void testKeepAll() throws Exception { String test = "+D:http://www.ifomis.org/bfo/1.1#Entity"; Configuration conf = new Configuration(); conf.read(new StringReader(test)); Set<Instruction> irisToSave = conf.getTreePartsToSave(); Assert.assertEquals(1, conf.getTreePartsToSave().size()); InputStream stream = this.getClass().getClassLoader().getResourceAsStream("bfo-1.1.owl"); Slimmer slimmer = new Slimmer(stream); slimmer.removeAllExcept(irisToSave); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(39, ontology.getClassesInSignature().size()); } @Test public void testParsingDownLeave() throws Exception { String test = "+D:http://www.ifomis.org/bfo/1.1/snap#FiatObjectPart"; Configuration conf = new Configuration(); conf.read(new StringReader(test)); Set<Instruction> irisToSave = conf.getTreePartsToSave(); Assert.assertEquals(1, conf.getTreePartsToSave().size()); InputStream stream = this.getClass().getClassLoader().getResourceAsStream("bfo-1.1.owl"); Slimmer slimmer = new Slimmer(stream); slimmer.removeAllExcept(irisToSave); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(1, ontology.getClassesInSignature().size()); } @Test public void testDeleteUp() throws Exception { String test = "+U:http://www.ifomis.org/bfo/1.1/snap#DependentContinuant\n" + "-U:http://www.ifomis.org/bfo/1.1/snap#DependentContinuant"; Configuration conf = new Configuration(); conf.read(new StringReader(test)); Set<Instruction> irisToSave = conf.getTreePartsToSave(); Set<Instruction> irisToRemove = conf.getTreePartsToRemove(); Assert.assertEquals(1, conf.getTreePartsToSave().size()); InputStream stream = this.getClass().getClassLoader().getResourceAsStream("bfo-1.1.owl"); Slimmer slimmer = new Slimmer(stream); slimmer.removeAllExcept(irisToSave); slimmer.removeAll(irisToRemove); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(0, ontology.getClassesInSignature().size()); } @Test public void testKeepAllButOne() throws Exception { String test = "+D:http://www.ifomis.org/bfo/1.1#Entity\n" + "-D:http://www.ifomis.org/bfo/1.1/snap#FiatObjectPart\n"; Configuration conf = new Configuration(); conf.read(new StringReader(test)); Set<Instruction> irisToSave = conf.getTreePartsToSave(); Set<Instruction> irisToRemove = conf.getTreePartsToRemove(); Assert.assertEquals(1, conf.getTreePartsToSave().size()); InputStream stream = this.getClass().getClassLoader().getResourceAsStream("bfo-1.1.owl"); Slimmer slimmer = new Slimmer(stream); slimmer.removeAllExcept(irisToSave); slimmer.removeAll(irisToRemove); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(38, ontology.getClassesInSignature().size()); } @Test public void testDeleteDown() throws Exception { String test = "+D:http://www.ifomis.org/bfo/1.1/snap#MaterialEntity\n" + "-D:http://www.ifomis.org/bfo/1.1/snap#FiatObjectPart"; Configuration conf = new Configuration(); conf.read(new StringReader(test)); Set<Instruction> irisToSave = conf.getTreePartsToSave(); Set<Instruction> irisToRemove = conf.getTreePartsToRemove(); Assert.assertEquals(1, conf.getTreePartsToSave().size()); InputStream stream = this.getClass().getClassLoader().getResourceAsStream("bfo-1.1.owl"); Slimmer slimmer = new Slimmer(stream); slimmer.removeAllExcept(irisToSave); slimmer.removeAll(irisToRemove); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(3, ontology.getClassesInSignature().size()); } @Test public void testDeleteDownWithComment() throws Exception { String test = "+D:http://www.ifomis.org/bfo/1.1/snap#MaterialEntity Comment\n" + "-D:http://www.ifomis.org/bfo/1.1/snap#FiatObjectPart"; Configuration conf = new Configuration(); conf.read(new StringReader(test)); Set<Instruction> irisToSave = conf.getTreePartsToSave(); Set<Instruction> irisToRemove = conf.getTreePartsToRemove(); Assert.assertEquals(1, conf.getTreePartsToSave().size()); InputStream stream = this.getClass().getClassLoader().getResourceAsStream("bfo-1.1.owl"); Slimmer slimmer = new Slimmer(stream); slimmer.removeAllExcept(irisToSave); slimmer.removeAll(irisToRemove); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(3, ontology.getClassesInSignature().size()); } @Test public void testParsingWithNewSuperClass() throws Exception { String test = "+D(http://www.ifomis.org/bfo/1.1/snap#Entity):http://www.ifomis.org/bfo/1.1/snap#Object"; Configuration conf = new Configuration(); conf.read(new StringReader(test)); Set<Instruction> irisToSave = conf.getTreePartsToSave(); Iterator<Instruction> instructions = irisToSave.iterator(); Instruction instruction = instructions.next(); if (!instruction.getUriString().endsWith("Object")) instruction = instructions.next(); String baseClass = instruction.getUriString(); Assert.assertEquals(1, conf.getTreePartsToSave().size()); InputStream stream = this.getClass().getClassLoader().getResourceAsStream("bfo-1.1.owl"); Slimmer slimmer = new Slimmer(stream); slimmer.removeAllExcept(irisToSave); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(2, ontology.getClassesInSignature().size()); Set<OWLEntity> entities = ontology.getEntitiesInSignature(IRI.create(baseClass)); Assert.assertEquals(1, entities.size()); OWLEntity entity = entities.iterator().next(); Assert.assertTrue(entity.isOWLClass()); OWLClass owlClass = entity.asOWLClass(); Set<OWLClassAxiom> axioms = ontology.getAxioms(owlClass, Imports.INCLUDED); Assert.assertEquals(1, axioms.size()); Assert.assertEquals("SubClassOf", axioms.iterator().next().getAxiomType().getName()); } @Test public void testMakeNewSubclassProperty() throws Exception { String test = "+:http://www.ifomis.org/bfo/1.1#Entity\n" + "+(http://www.ifomis.org/bfo/1.1#Entity):http://www.ifomis.org/bfo/1.1/snap#MaterialEntity"; Configuration conf = new Configuration(); conf.read(new StringReader(test)); Set<Instruction> irisToSave = conf.getTreePartsToSave(); Iterator<Instruction> instructions = irisToSave.iterator(); Instruction instruction = instructions.next(); if (!instruction.getUriString().endsWith("MaterialEntity")) instruction = instructions.next(); String baseClass = instruction.getUriString(); Assert.assertEquals(2, conf.getTreePartsToSave().size()); InputStream stream = this.getClass().getClassLoader().getResourceAsStream("bfo-1.1.owl"); Slimmer slimmer = new Slimmer(stream); slimmer.removeAllExcept(irisToSave); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(2, ontology.getClassesInSignature().size()); Set<OWLEntity> entities = ontology.getEntitiesInSignature(IRI.create(baseClass)); Assert.assertEquals(1, entities.size()); OWLEntity entity = entities.iterator().next(); Assert.assertTrue(entity.isOWLClass()); OWLClass owlClass = entity.asOWLClass(); Set<OWLClassAxiom> axioms = ontology.getAxioms(owlClass, Imports.INCLUDED); Assert.assertEquals(1, axioms.size()); Assert.assertEquals("SubClassOf", axioms.iterator().next().getAxiomType().getName()); } @Test public void testMakeNewSuperClassFromOtherOntology() throws Exception { String test = "+(http://purl.obolibrary.org/obo/CHEBI_23367):http://www.ifomis.org/bfo/1.1/snap#MaterialEntity"; Configuration conf = new Configuration(); conf.read(new StringReader(test)); Set<Instruction> irisToSave = conf.getTreePartsToSave(); Instruction instruction = irisToSave.iterator().next(); String baseClass = instruction.getUriString(); Assert.assertEquals(1, conf.getTreePartsToSave().size()); InputStream stream = this.getClass().getClassLoader().getResourceAsStream("bfo-1.1.owl"); Slimmer slimmer = new Slimmer(stream); slimmer.removeAllExcept(irisToSave); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(2, ontology.getClassesInSignature().size()); Set<OWLEntity> entities = ontology.getEntitiesInSignature(IRI.create(baseClass)); Assert.assertEquals(1, entities.size()); OWLEntity entity = entities.iterator().next(); Assert.assertTrue(entity.isOWLClass()); OWLClass owlClass = entity.asOWLClass(); Assert.assertEquals(1, Searcher.sup(ontology.getSubClassAxiomsForSubClass(owlClass)).size()); Set<OWLClassAxiom> axioms = ontology.getAxioms(owlClass, Imports.INCLUDED); Assert.assertEquals("SubClassOf", axioms.iterator().next().getAxiomType().getName()); } @Test public void testNotRemoveDeclaredProperties() throws Exception { String test = "+:http://purl.obolibrary.org/obo/uo#is_unit_of"; Configuration conf = new Configuration(); conf.read(new StringReader(test)); Set<Instruction> irisToSave = conf.getTreePartsToSave(); Assert.assertNotNull(irisToSave); Assert.assertEquals(1, conf.getTreePartsToSave().size()); InputStream stream = this.getClass().getClassLoader().getResourceAsStream("uo.owl"); Slimmer slimmer = new Slimmer(stream); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(3203, ontology.getAxiomCount()); // test the removing; should result in exactly one less axiom slimmer.removeAllExcept(irisToSave); ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(68, ontology.getAxiomCount()); } @Test public void testRemoveDeclaredProperties() throws Exception { Configuration conf = new Configuration(); Set<Instruction> irisToSave = conf.getTreePartsToSave(); Assert.assertNotNull(irisToSave); Assert.assertEquals(0, conf.getTreePartsToSave().size()); InputStream stream = this.getClass().getClassLoader().getResourceAsStream("uo.owl"); Slimmer slimmer = new Slimmer(stream); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(3203, ontology.getAxiomCount()); // test the removing; should result in exactly one less axiom slimmer.removeAllExcept(irisToSave); ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(67, ontology.getAxiomCount()); } @Test public void testRemoveMoreDeclaredProperties() throws Exception { String test = "+:http://www.bioassayontology.org/bao#BAO_0000555"; Configuration conf = new Configuration(); conf.read(new StringReader(test)); Set<Instruction> irisToSave = conf.getTreePartsToSave(); Assert.assertNotNull(irisToSave); Assert.assertEquals(1, conf.getTreePartsToSave().size()); InputStream stream = this.getClass().getClassLoader().getResourceAsStream("bao_core.owl"); Slimmer slimmer = new Slimmer(stream); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(899, ontology.getAxiomCount()); // test the removing; should result in exactly one less axiom slimmer.removeAllExcept(irisToSave); ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(47, ontology.getAxiomCount()); } @Test public void testExtraNamespaces() throws Exception { Configuration conf = new Configuration(); Set<Instruction> irisToSave = conf.getTreePartsToSave(); String ontoFile = "uo.owl"; InputStream stream = this.getClass().getClassLoader().getResourceAsStream(ontoFile); Slimmer slimmer = new Slimmer(stream); OWLOntology ontology = slimmer.getOntology(); slimmer.removeAllExcept(irisToSave); ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(67, ontology.getAxiomCount()); ByteArrayOutputStream output = new ByteArrayOutputStream(); slimmer.saveAs(output, ontoFile); String owlOutput = output.toString(); System.out.println(owlOutput); Assert.assertTrue(owlOutput.contains("xmlns:ncicp")); } @Test public void testSlimmingVersionAnnotation() throws Exception { Configuration conf = new Configuration(); Set<Instruction> irisToSave = conf.getTreePartsToSave(); String ontoFile = "uo.owl"; InputStream stream = this.getClass().getClassLoader().getResourceAsStream(ontoFile); Slimmer slimmer = new Slimmer(stream); OWLOntology ontology = slimmer.getOntology(); slimmer.removeAllExcept(irisToSave); ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(67, ontology.getAxiomCount()); ByteArrayOutputStream output = new ByteArrayOutputStream(); slimmer.saveAs(output, ontoFile); String owlOutput = output.toString(); Assert.assertTrue(owlOutput.contains("This SLIM file")); } @Test public void testSourceAnnotation() throws Exception { Configuration conf = new Configuration(); Set<Instruction> irisToSave = conf.getTreePartsToSave(); String ontoFile = "uo.owl"; InputStream stream = this.getClass().getClassLoader().getResourceAsStream(ontoFile); Slimmer slimmer = new Slimmer(stream); OWLOntology ontology = slimmer.getOntology(); slimmer.removeAllExcept(irisToSave); ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(67, ontology.getAxiomCount()); ByteArrayOutputStream output = new ByteArrayOutputStream(); slimmer.saveAs(output, ontoFile); String owlOutput = output.toString(); Assert.assertTrue(owlOutput.contains("pav:importedFrom")); } @Test public void testGenerationDate() throws Exception { Configuration conf = new Configuration(); Set<Instruction> irisToSave = conf.getTreePartsToSave(); String ontoFile = "uo.owl"; InputStream stream = this.getClass().getClassLoader().getResourceAsStream(ontoFile); Slimmer slimmer = new Slimmer(stream); OWLOntology ontology = slimmer.getOntology(); slimmer.removeAllExcept(irisToSave); ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(67, ontology.getAxiomCount()); ByteArrayOutputStream output = new ByteArrayOutputStream(); slimmer.saveAs(output, ontoFile); String owlOutput = output.toString(); System.out.println(owlOutput); Assert.assertTrue(owlOutput.contains(">2015-")); // TODO: update every year :) } }
src/test/java/com/github/enanomapper/SlimmerTest.java
package com.github.enanomapper; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.StringReader; import java.util.Iterator; import java.util.Set; import org.junit.Assert; import org.junit.Test; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLClass; import org.semanticweb.owlapi.model.OWLClassAxiom; import org.semanticweb.owlapi.model.OWLEntity; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyCreationException; import org.semanticweb.owlapi.model.parameters.Imports; import org.semanticweb.owlapi.search.Searcher; public class SlimmerTest { @Test public void testLoading() throws OWLOntologyCreationException { InputStream stream = this.getClass().getClassLoader().getResourceAsStream("bfo-1.1.owl"); Slimmer slimmer = new Slimmer(stream); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertNotSame(0, ontology.getAxiomCount()); } @Test public void testParsingUp() throws Exception { String test = "+U:http://www.ifomis.org/bfo/1.1/snap#DependentContinuant"; Configuration conf = new Configuration(); conf.read(new StringReader(test)); Set<Instruction> irisToSave = conf.getTreePartsToSave(); Assert.assertEquals(1, conf.getTreePartsToSave().size()); InputStream stream = this.getClass().getClassLoader().getResourceAsStream("bfo-1.1.owl"); Slimmer slimmer = new Slimmer(stream); slimmer.removeAllExcept(irisToSave); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(3, ontology.getClassesInSignature().size()); } @Test public void testParsingSingle() throws Exception { String test = "+:http://www.ifomis.org/bfo/1.1/snap#DependentContinuant"; Configuration conf = new Configuration(); conf.read(new StringReader(test)); Set<Instruction> irisToSave = conf.getTreePartsToSave(); Assert.assertEquals(1, conf.getTreePartsToSave().size()); InputStream stream = this.getClass().getClassLoader().getResourceAsStream("bfo-1.1.owl"); Slimmer slimmer = new Slimmer(stream); slimmer.removeAllExcept(irisToSave); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(1, ontology.getClassesInSignature().size()); } @Test public void testParsingDown() throws Exception { String test = "+D:http://www.ifomis.org/bfo/1.1/snap#MaterialEntity"; Configuration conf = new Configuration(); conf.read(new StringReader(test)); Set<Instruction> irisToSave = conf.getTreePartsToSave(); Assert.assertEquals(1, conf.getTreePartsToSave().size()); InputStream stream = this.getClass().getClassLoader().getResourceAsStream("bfo-1.1.owl"); Slimmer slimmer = new Slimmer(stream); slimmer.removeAllExcept(irisToSave); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(4, ontology.getClassesInSignature().size()); } @Test public void testKeepAll() throws Exception { String test = "+D:http://www.ifomis.org/bfo/1.1#Entity"; Configuration conf = new Configuration(); conf.read(new StringReader(test)); Set<Instruction> irisToSave = conf.getTreePartsToSave(); Assert.assertEquals(1, conf.getTreePartsToSave().size()); InputStream stream = this.getClass().getClassLoader().getResourceAsStream("bfo-1.1.owl"); Slimmer slimmer = new Slimmer(stream); slimmer.removeAllExcept(irisToSave); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(39, ontology.getClassesInSignature().size()); } @Test public void testParsingDownLeave() throws Exception { String test = "+D:http://www.ifomis.org/bfo/1.1/snap#FiatObjectPart"; Configuration conf = new Configuration(); conf.read(new StringReader(test)); Set<Instruction> irisToSave = conf.getTreePartsToSave(); Assert.assertEquals(1, conf.getTreePartsToSave().size()); InputStream stream = this.getClass().getClassLoader().getResourceAsStream("bfo-1.1.owl"); Slimmer slimmer = new Slimmer(stream); slimmer.removeAllExcept(irisToSave); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(1, ontology.getClassesInSignature().size()); } @Test public void testDeleteUp() throws Exception { String test = "+U:http://www.ifomis.org/bfo/1.1/snap#DependentContinuant\n" + "-U:http://www.ifomis.org/bfo/1.1/snap#DependentContinuant"; Configuration conf = new Configuration(); conf.read(new StringReader(test)); Set<Instruction> irisToSave = conf.getTreePartsToSave(); Set<Instruction> irisToRemove = conf.getTreePartsToRemove(); Assert.assertEquals(1, conf.getTreePartsToSave().size()); InputStream stream = this.getClass().getClassLoader().getResourceAsStream("bfo-1.1.owl"); Slimmer slimmer = new Slimmer(stream); slimmer.removeAllExcept(irisToSave); slimmer.removeAll(irisToRemove); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(0, ontology.getClassesInSignature().size()); } @Test public void testKeepAllButOne() throws Exception { String test = "+D:http://www.ifomis.org/bfo/1.1#Entity\n" + "-D:http://www.ifomis.org/bfo/1.1/snap#FiatObjectPart\n"; Configuration conf = new Configuration(); conf.read(new StringReader(test)); Set<Instruction> irisToSave = conf.getTreePartsToSave(); Set<Instruction> irisToRemove = conf.getTreePartsToRemove(); Assert.assertEquals(1, conf.getTreePartsToSave().size()); InputStream stream = this.getClass().getClassLoader().getResourceAsStream("bfo-1.1.owl"); Slimmer slimmer = new Slimmer(stream); slimmer.removeAllExcept(irisToSave); slimmer.removeAll(irisToRemove); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(38, ontology.getClassesInSignature().size()); } @Test public void testDeleteDown() throws Exception { String test = "+D:http://www.ifomis.org/bfo/1.1/snap#MaterialEntity\n" + "-D:http://www.ifomis.org/bfo/1.1/snap#FiatObjectPart"; Configuration conf = new Configuration(); conf.read(new StringReader(test)); Set<Instruction> irisToSave = conf.getTreePartsToSave(); Set<Instruction> irisToRemove = conf.getTreePartsToRemove(); Assert.assertEquals(1, conf.getTreePartsToSave().size()); InputStream stream = this.getClass().getClassLoader().getResourceAsStream("bfo-1.1.owl"); Slimmer slimmer = new Slimmer(stream); slimmer.removeAllExcept(irisToSave); slimmer.removeAll(irisToRemove); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(3, ontology.getClassesInSignature().size()); } @Test public void testDeleteDownWithComment() throws Exception { String test = "+D:http://www.ifomis.org/bfo/1.1/snap#MaterialEntity Comment\n" + "-D:http://www.ifomis.org/bfo/1.1/snap#FiatObjectPart"; Configuration conf = new Configuration(); conf.read(new StringReader(test)); Set<Instruction> irisToSave = conf.getTreePartsToSave(); Set<Instruction> irisToRemove = conf.getTreePartsToRemove(); Assert.assertEquals(1, conf.getTreePartsToSave().size()); InputStream stream = this.getClass().getClassLoader().getResourceAsStream("bfo-1.1.owl"); Slimmer slimmer = new Slimmer(stream); slimmer.removeAllExcept(irisToSave); slimmer.removeAll(irisToRemove); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(3, ontology.getClassesInSignature().size()); } @Test public void testMakeNewSubclassProperty() throws Exception { String test = "+:http://www.ifomis.org/bfo/1.1#Entity\n" + "+(http://www.ifomis.org/bfo/1.1#Entity):http://www.ifomis.org/bfo/1.1/snap#MaterialEntity"; Configuration conf = new Configuration(); conf.read(new StringReader(test)); Set<Instruction> irisToSave = conf.getTreePartsToSave(); Iterator<Instruction> instructions = irisToSave.iterator(); Instruction instruction = instructions.next(); if (!instruction.getUriString().endsWith("MaterialEntity")) instruction = instructions.next(); String baseClass = instruction.getUriString(); Assert.assertEquals(2, conf.getTreePartsToSave().size()); InputStream stream = this.getClass().getClassLoader().getResourceAsStream("bfo-1.1.owl"); Slimmer slimmer = new Slimmer(stream); slimmer.removeAllExcept(irisToSave); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(2, ontology.getClassesInSignature().size()); Set<OWLEntity> entities = ontology.getEntitiesInSignature(IRI.create(baseClass)); Assert.assertEquals(1, entities.size()); OWLEntity entity = entities.iterator().next(); Assert.assertTrue(entity.isOWLClass()); OWLClass owlClass = entity.asOWLClass(); Set<OWLClassAxiom> axioms = ontology.getAxioms(owlClass, Imports.INCLUDED); Assert.assertEquals(1, axioms.size()); Assert.assertEquals("SubClassOf", axioms.iterator().next().getAxiomType().getName()); } @Test public void testMakeNewSuperClassFromOtherOntology() throws Exception { String test = "+(http://purl.obolibrary.org/obo/CHEBI_23367):http://www.ifomis.org/bfo/1.1/snap#MaterialEntity"; Configuration conf = new Configuration(); conf.read(new StringReader(test)); Set<Instruction> irisToSave = conf.getTreePartsToSave(); Instruction instruction = irisToSave.iterator().next(); String baseClass = instruction.getUriString(); Assert.assertEquals(1, conf.getTreePartsToSave().size()); InputStream stream = this.getClass().getClassLoader().getResourceAsStream("bfo-1.1.owl"); Slimmer slimmer = new Slimmer(stream); slimmer.removeAllExcept(irisToSave); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(2, ontology.getClassesInSignature().size()); Set<OWLEntity> entities = ontology.getEntitiesInSignature(IRI.create(baseClass)); Assert.assertEquals(1, entities.size()); OWLEntity entity = entities.iterator().next(); Assert.assertTrue(entity.isOWLClass()); OWLClass owlClass = entity.asOWLClass(); Assert.assertEquals(1, Searcher.sup(ontology.getSubClassAxiomsForSubClass(owlClass)).size()); Set<OWLClassAxiom> axioms = ontology.getAxioms(owlClass, Imports.INCLUDED); Assert.assertEquals("SubClassOf", axioms.iterator().next().getAxiomType().getName()); } @Test public void testNotRemoveDeclaredProperties() throws Exception { String test = "+:http://purl.obolibrary.org/obo/uo#is_unit_of"; Configuration conf = new Configuration(); conf.read(new StringReader(test)); Set<Instruction> irisToSave = conf.getTreePartsToSave(); Assert.assertNotNull(irisToSave); Assert.assertEquals(1, conf.getTreePartsToSave().size()); InputStream stream = this.getClass().getClassLoader().getResourceAsStream("uo.owl"); Slimmer slimmer = new Slimmer(stream); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(3203, ontology.getAxiomCount()); // test the removing; should result in exactly one less axiom slimmer.removeAllExcept(irisToSave); ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(68, ontology.getAxiomCount()); } @Test public void testRemoveDeclaredProperties() throws Exception { Configuration conf = new Configuration(); Set<Instruction> irisToSave = conf.getTreePartsToSave(); Assert.assertNotNull(irisToSave); Assert.assertEquals(0, conf.getTreePartsToSave().size()); InputStream stream = this.getClass().getClassLoader().getResourceAsStream("uo.owl"); Slimmer slimmer = new Slimmer(stream); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(3203, ontology.getAxiomCount()); // test the removing; should result in exactly one less axiom slimmer.removeAllExcept(irisToSave); ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(67, ontology.getAxiomCount()); } @Test public void testRemoveMoreDeclaredProperties() throws Exception { String test = "+:http://www.bioassayontology.org/bao#BAO_0000555"; Configuration conf = new Configuration(); conf.read(new StringReader(test)); Set<Instruction> irisToSave = conf.getTreePartsToSave(); Assert.assertNotNull(irisToSave); Assert.assertEquals(1, conf.getTreePartsToSave().size()); InputStream stream = this.getClass().getClassLoader().getResourceAsStream("bao_core.owl"); Slimmer slimmer = new Slimmer(stream); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(899, ontology.getAxiomCount()); // test the removing; should result in exactly one less axiom slimmer.removeAllExcept(irisToSave); ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(47, ontology.getAxiomCount()); } @Test public void testExtraNamespaces() throws Exception { Configuration conf = new Configuration(); Set<Instruction> irisToSave = conf.getTreePartsToSave(); String ontoFile = "uo.owl"; InputStream stream = this.getClass().getClassLoader().getResourceAsStream(ontoFile); Slimmer slimmer = new Slimmer(stream); OWLOntology ontology = slimmer.getOntology(); slimmer.removeAllExcept(irisToSave); ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(67, ontology.getAxiomCount()); ByteArrayOutputStream output = new ByteArrayOutputStream(); slimmer.saveAs(output, ontoFile); String owlOutput = output.toString(); System.out.println(owlOutput); Assert.assertTrue(owlOutput.contains("xmlns:ncicp")); } @Test public void testSlimmingVersionAnnotation() throws Exception { Configuration conf = new Configuration(); Set<Instruction> irisToSave = conf.getTreePartsToSave(); String ontoFile = "uo.owl"; InputStream stream = this.getClass().getClassLoader().getResourceAsStream(ontoFile); Slimmer slimmer = new Slimmer(stream); OWLOntology ontology = slimmer.getOntology(); slimmer.removeAllExcept(irisToSave); ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(67, ontology.getAxiomCount()); ByteArrayOutputStream output = new ByteArrayOutputStream(); slimmer.saveAs(output, ontoFile); String owlOutput = output.toString(); Assert.assertTrue(owlOutput.contains("This SLIM file")); } @Test public void testSourceAnnotation() throws Exception { Configuration conf = new Configuration(); Set<Instruction> irisToSave = conf.getTreePartsToSave(); String ontoFile = "uo.owl"; InputStream stream = this.getClass().getClassLoader().getResourceAsStream(ontoFile); Slimmer slimmer = new Slimmer(stream); OWLOntology ontology = slimmer.getOntology(); slimmer.removeAllExcept(irisToSave); ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(67, ontology.getAxiomCount()); ByteArrayOutputStream output = new ByteArrayOutputStream(); slimmer.saveAs(output, ontoFile); String owlOutput = output.toString(); Assert.assertTrue(owlOutput.contains("pav:importedFrom")); } @Test public void testGenerationDate() throws Exception { Configuration conf = new Configuration(); Set<Instruction> irisToSave = conf.getTreePartsToSave(); String ontoFile = "uo.owl"; InputStream stream = this.getClass().getClassLoader().getResourceAsStream(ontoFile); Slimmer slimmer = new Slimmer(stream); OWLOntology ontology = slimmer.getOntology(); slimmer.removeAllExcept(irisToSave); ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(67, ontology.getAxiomCount()); ByteArrayOutputStream output = new ByteArrayOutputStream(); slimmer.saveAs(output, ontoFile); String owlOutput = output.toString(); System.out.println(owlOutput); Assert.assertTrue(owlOutput.contains(">2015-")); // TODO: update every year :) } }
Testing the combination of 'select down' with a new super class
src/test/java/com/github/enanomapper/SlimmerTest.java
Testing the combination of 'select down' with a new super class
<ide><path>rc/test/java/com/github/enanomapper/SlimmerTest.java <ide> } <ide> <ide> @Test <add> public void testParsingWithNewSuperClass() throws Exception { <add> String test = "+D(http://www.ifomis.org/bfo/1.1/snap#Entity):http://www.ifomis.org/bfo/1.1/snap#Object"; <add> Configuration conf = new Configuration(); <add> conf.read(new StringReader(test)); <add> Set<Instruction> irisToSave = conf.getTreePartsToSave(); <add> Iterator<Instruction> instructions = irisToSave.iterator(); <add> Instruction instruction = instructions.next(); <add> if (!instruction.getUriString().endsWith("Object")) instruction = instructions.next(); <add> String baseClass = instruction.getUriString(); <add> <add> Assert.assertEquals(1, conf.getTreePartsToSave().size()); <add> InputStream stream = this.getClass().getClassLoader().getResourceAsStream("bfo-1.1.owl"); <add> Slimmer slimmer = new Slimmer(stream); <add> slimmer.removeAllExcept(irisToSave); <add> OWLOntology ontology = slimmer.getOntology(); <add> Assert.assertNotNull(ontology); <add> Assert.assertEquals(2, ontology.getClassesInSignature().size()); <add> <add> Set<OWLEntity> entities = ontology.getEntitiesInSignature(IRI.create(baseClass)); <add> Assert.assertEquals(1, entities.size()); <add> OWLEntity entity = entities.iterator().next(); <add> Assert.assertTrue(entity.isOWLClass()); <add> OWLClass owlClass = entity.asOWLClass(); <add> Set<OWLClassAxiom> axioms = ontology.getAxioms(owlClass, Imports.INCLUDED); <add> Assert.assertEquals(1, axioms.size()); <add> Assert.assertEquals("SubClassOf", axioms.iterator().next().getAxiomType().getName()); <add> } <add> <add> @Test <ide> public void testMakeNewSubclassProperty() throws Exception { <ide> String test = "+:http://www.ifomis.org/bfo/1.1#Entity\n" <ide> + "+(http://www.ifomis.org/bfo/1.1#Entity):http://www.ifomis.org/bfo/1.1/snap#MaterialEntity";
JavaScript
mit
9e8e0d9d039746ee72fc8baf0848615f0058a8f3
0
atlefren/sosi.js,kartverket/sosi.js,atlefren/sosi.js
var SOSI = window.SOSI || {}; /** * This is adopted from backbone.js which * is available for use under the MIT software license. * see http://github.com/jashkenas/backbone/blob/master/LICENSE */ (function (ns, undefined) { "use strict"; ns.Base = function() { this.initialize.apply(this, arguments); }; _.extend(ns.Base.prototype, { initialize: function () {} }); ns.Base.extend = function(protoProps, staticProps) { var parent = this; var child; if (protoProps && _.has(protoProps, 'constructor')) { child = protoProps.constructor; } else { child = function(){ return parent.apply(this, arguments); }; } _.extend(child, parent, staticProps); var Surrogate = function(){ this.constructor = child; }; Surrogate.prototype = parent.prototype; child.prototype = new Surrogate; if (protoProps) _.extend(child.prototype, protoProps); child.__super__ = parent.prototype; return child; }; }(SOSI));
src/class_system.js
var SOSI = window.SOSI || {}; (function (ns, undefined) { "use strict"; ns.Base = function() { this.initialize.apply(this, arguments); }; _.extend(ns.Base.prototype, { initialize: function () {} }); var extend = function(protoProps, staticProps) { var parent = this; var child; if (protoProps && _.has(protoProps, 'constructor')) { child = protoProps.constructor; } else { child = function(){ return parent.apply(this, arguments); }; } _.extend(child, parent, staticProps); var Surrogate = function(){ this.constructor = child; }; Surrogate.prototype = parent.prototype; child.prototype = new Surrogate; if (protoProps) _.extend(child.prototype, protoProps); child.__super__ = parent.prototype; return child; }; ns.Base.extend = extend; }(SOSI));
credit to backbone
src/class_system.js
credit to backbone
<ide><path>rc/class_system.js <ide> var SOSI = window.SOSI || {}; <ide> <add>/** <add> * This is adopted from backbone.js which <add> * is available for use under the MIT software license. <add> * see http://github.com/jashkenas/backbone/blob/master/LICENSE <add> */ <ide> (function (ns, undefined) { <ide> "use strict"; <ide> <ide> initialize: function () {} <ide> }); <ide> <del> var extend = function(protoProps, staticProps) { <add> ns.Base.extend = function(protoProps, staticProps) { <ide> var parent = this; <ide> var child; <ide> <ide> return child; <ide> }; <ide> <del> ns.Base.extend = extend; <ide> }(SOSI));
Java
apache-2.0
cf5758169a6b4ac6903f2d945d6ed158f517d4c7
0
MobileTribe/pandroid,MobileTribe/pandroid,MobileTribe/pandroid
package com.leroymerlin.pandroid.net; import android.content.Context; import android.os.Handler; import android.os.Looper; import android.support.annotation.Nullable; import com.leroymerlin.pandroid.app.PandroidConfig; import com.leroymerlin.pandroid.future.ActionDelegate; import com.leroymerlin.pandroid.future.Cancellable; import com.leroymerlin.pandroid.future.CancellableActionDelegate; import com.leroymerlin.pandroid.log.LogWrapper; import com.leroymerlin.pandroid.net.http.Mock; import com.leroymerlin.pandroid.net.mock.ServiceMock; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.TreeMap; import okhttp3.Request; import retrofit2.Call; import retrofit2.CallAdapter; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; /** * Created by florian on 08/01/16. */ public final class PandroidCallAdapterFactory extends CallAdapter.Factory { private static final String TAG = "PandroidCallAdapterFactory"; private final Context context; private final LogWrapper logWrapper; private final boolean rxAndroidEnable; Handler handler; private boolean mockEnable; private PandroidErrorFormatter errorFormatter; public static PandroidCallAdapterFactory create(Context context, LogWrapper logWrapper) { return PandroidCallAdapterFactory.create(context, logWrapper, Looper.getMainLooper()); } public static PandroidCallAdapterFactory create(Context context, LogWrapper logWrapper, @Nullable Looper looper) { return new PandroidCallAdapterFactory(context, logWrapper, looper); } private PandroidCallAdapterFactory(Context context, LogWrapper logWrapper, Looper looper) { if (looper != null) handler = new Handler(looper); this.context = context; this.logWrapper = logWrapper; rxAndroidEnable = PandroidConfig.isLibraryEnable("rxandroid"); } public void setMockEnable(boolean mockEnable) { this.mockEnable = mockEnable; } public void setErrorFormatter(PandroidErrorFormatter errorFormatter) { this.errorFormatter = errorFormatter; } @Override public CallAdapter<?, PandroidCall> get(Type returnType, Annotation[] annotations, Retrofit retrofit) { if (returnType instanceof ParameterizedType && (((ParameterizedType) returnType).getRawType() == PandroidCall.class || ((ParameterizedType) returnType).getRawType() == RxPandroidCall.class || ((ParameterizedType) returnType).getRawType() == Call.class)) { Type[] actualTypeArguments = ((ParameterizedType) returnType).getActualTypeArguments(); return new ResponseCallAdapter(actualTypeArguments[0], annotations); } return null; } final class ResponseCallAdapter<R> implements CallAdapter<R, PandroidCall<?>> { private boolean needResponse; private Type responseType; private ServiceMock serviceMock; ResponseCallAdapter(Type responseType, Annotation[] annotations) { this.responseType = responseType; if (responseType instanceof ParameterizedType && (((ParameterizedType) responseType).getRawType()).equals(Response.class)) { Type[] actualTypeArguments = ((ParameterizedType) responseType).getActualTypeArguments(); this.responseType = actualTypeArguments[0]; this.needResponse = true; } for (Annotation annotation : annotations) { if (annotation instanceof Mock) { try { serviceMock = ((Mock) annotation).mockClass().newInstance(); serviceMock.setMockInfo((Mock) annotation); serviceMock.setReturnType(responseType); } catch (Exception e) { logWrapper.e(TAG, e); } } } } @Override public Type responseType() { return responseType; } @Override public PandroidCall<?> adapt(final Call<R> call) { Call<R> callWrapper = call; if (serviceMock != null && serviceMock.isEnable() && mockEnable) { callWrapper = new Call<R>() { public boolean isExecuted; @Override public Response<R> execute() { isExecuted = true; try { Thread.sleep(serviceMock.getResponseDelay()); } catch (InterruptedException e) { logWrapper.e(TAG, e); } isExecuted = false; return serviceMock.getMockResponse(call.request(), context); } @Override public void enqueue(final Callback<R> callback) { Runnable runnable = new Runnable() { @Override public void run() { callback.onResponse(call, (Response<R>) serviceMock.getMockResponse(call.request(), context)); } }; if (handler != null) { handler.postDelayed(runnable, serviceMock.getResponseDelay()); } else { runnable.run(); } } @Override public boolean isExecuted() { return isExecuted; } @Override public void cancel() { call.cancel(); } @Override public boolean isCanceled() { return call.isCanceled(); } @Override public Call<R> clone() { return call.clone(); } @Override public Request request() { return call.request(); } }; } PandroidCallImpl<R> pandroidCall = new PandroidCallImpl<>(callWrapper, needResponse); return rxAndroidEnable? new RxPandroidCall(pandroidCall): pandroidCall; } } private void post(Runnable runnable) { if (handler != null) { handler.post(runnable); } else { runnable.run(); } } private class PandroidCallImpl<R> implements PandroidCall<R> { private final Call<R> call; private final boolean needResponse; PandroidCallImpl(Call<R> call, boolean needResponse) { this.call = call; this.needResponse = needResponse; } @Override public void enqueue(final ActionDelegate delegate) { if (delegate instanceof Cancellable) ((CancellableActionDelegate) delegate).addCancelListener(new CancellableActionDelegate.CancelListener() { @Override public void onCancel() { call.cancel(); } }); final long startTime = System.currentTimeMillis(); call.enqueue( new Callback<R>() { @Override public void onResponse(Call<R> call, final Response<R> response) { if (needResponse) { post( new Runnable() { @Override public void run() { delegate.onSuccess(response); } } ); } else { if (response.isSuccessful()) { post( new Runnable() { @Override public void run() { delegate.onSuccess(response.body()); } } ); } else { byte[] bytes = new byte[0]; try { bytes = response.errorBody().bytes(); } catch (IOException ignore) { } onError(new NetworkException(response.raw().request().url().toString(), response.code(), (TreeMap) response.headers().toMultimap(), new Exception(response.message()), bytes, System.currentTimeMillis() - startTime)); } } } @Override public void onFailure(Call<R> call, final Throwable t) { if(t instanceof Exception) { onError(((Exception) t)); } else { onError(new Exception(t)); } } private void onError(final Exception e) { post(new Runnable() { @Override public void run() { delegate.onError(errorFormatter != null ? errorFormatter.format(e) : e); } }); } } ); } @Override public Response<R> execute() throws IOException { return call.execute(); } @Override public void enqueue(Callback<R> callback) { call.enqueue(callback); } @Override public boolean isExecuted() { return call.isExecuted(); } @Override public void cancel() { call.cancel(); } @Override public boolean isCanceled() { return call.isCanceled(); } @Override public PandroidCall<R> clone() { PandroidCallImpl<R> pandroidCall = new PandroidCallImpl<>(call.clone(), needResponse); return rxAndroidEnable ? new RxPandroidCall(pandroidCall) : pandroidCall; } @Override public Request request() { return call.request(); } } }
pandroid-library/src/main/java/com/leroymerlin/pandroid/net/PandroidCallAdapterFactory.java
package com.leroymerlin.pandroid.net; import android.content.Context; import android.os.Handler; import android.os.Looper; import android.support.annotation.Nullable; import com.leroymerlin.pandroid.app.PandroidConfig; import com.leroymerlin.pandroid.future.ActionDelegate; import com.leroymerlin.pandroid.future.Cancellable; import com.leroymerlin.pandroid.future.CancellableActionDelegate; import com.leroymerlin.pandroid.log.LogWrapper; import com.leroymerlin.pandroid.net.http.Mock; import com.leroymerlin.pandroid.net.mock.ServiceMock; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.TreeMap; import okhttp3.Request; import retrofit2.Call; import retrofit2.CallAdapter; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; /** * Created by florian on 08/01/16. */ public final class PandroidCallAdapterFactory extends CallAdapter.Factory { private static final String TAG = "PandroidCallAdapterFactory"; private final Context context; private final LogWrapper logWrapper; private final boolean rxAndroidEnable; Handler handler; private boolean mockEnable; private PandroidErrorFormatter errorFormatter; public static PandroidCallAdapterFactory create(Context context, LogWrapper logWrapper) { return PandroidCallAdapterFactory.create(context, logWrapper, Looper.getMainLooper()); } public static PandroidCallAdapterFactory create(Context context, LogWrapper logWrapper, @Nullable Looper looper) { return new PandroidCallAdapterFactory(context, logWrapper, looper); } private PandroidCallAdapterFactory(Context context, LogWrapper logWrapper, Looper looper) { if (looper != null) handler = new Handler(looper); this.context = context; this.logWrapper = logWrapper; rxAndroidEnable = PandroidConfig.isLibraryEnable("rxandroid"); } public void setMockEnable(boolean mockEnable) { this.mockEnable = mockEnable; } public void setErrorFormatter(PandroidErrorFormatter errorFormatter) { this.errorFormatter = errorFormatter; } @Override public CallAdapter<?, PandroidCall> get(Type returnType, Annotation[] annotations, Retrofit retrofit) { if (returnType instanceof ParameterizedType && (((ParameterizedType) returnType).getRawType() == PandroidCall.class || ((ParameterizedType) returnType).getRawType() == RxPandroidCall.class || ((ParameterizedType) returnType).getRawType() == Call.class)) { Type[] actualTypeArguments = ((ParameterizedType) returnType).getActualTypeArguments(); return new ResponseCallAdapter(actualTypeArguments[0], annotations); } return null; } final class ResponseCallAdapter<R> implements CallAdapter<R, PandroidCall<?>> { private boolean needResponse; private Type responseType; private ServiceMock serviceMock; ResponseCallAdapter(Type responseType, Annotation[] annotations) { this.responseType = responseType; if (responseType instanceof ParameterizedType && (((ParameterizedType) responseType).getRawType()).equals(Response.class)) { Type[] actualTypeArguments = ((ParameterizedType) responseType).getActualTypeArguments(); this.responseType = actualTypeArguments[0]; this.needResponse = true; } for (Annotation annotation : annotations) { if (annotation instanceof Mock) { try { serviceMock = ((Mock) annotation).mockClass().newInstance(); serviceMock.setMockInfo((Mock) annotation); serviceMock.setReturnType(responseType); } catch (Exception e) { logWrapper.e(TAG, e); } } } } @Override public Type responseType() { return responseType; } @Override public PandroidCall<?> adapt(final Call<R> call) { Call<R> callWrapper = call; if (serviceMock != null && serviceMock.isEnable() && mockEnable) { callWrapper = new Call<R>() { public boolean isExecuted; @Override public Response<R> execute() { isExecuted = true; try { Thread.sleep(serviceMock.getResponseDelay()); } catch (InterruptedException e) { logWrapper.e(TAG, e); } isExecuted = false; return serviceMock.getMockResponse(call.request(), context); } @Override public void enqueue(final Callback<R> callback) { Runnable runnable = new Runnable() { @Override public void run() { callback.onResponse(call, (Response<R>) serviceMock.getMockResponse(call.request(), context)); } }; if (handler != null) { handler.postDelayed(runnable, serviceMock.getResponseDelay()); } else { runnable.run(); } } @Override public boolean isExecuted() { return isExecuted; } @Override public void cancel() { call.cancel(); } @Override public boolean isCanceled() { return call.isCanceled(); } @Override public Call<R> clone() { return call.clone(); } @Override public Request request() { return call.request(); } }; } PandroidCallImpl<R> pandroidCall = new PandroidCallImpl<>(callWrapper, needResponse); return rxAndroidEnable? new RxPandroidCall(pandroidCall): pandroidCall; } } private void post(Runnable runnable) { if (handler != null) { handler.post(runnable); } else { runnable.run(); } } private class PandroidCallImpl<R> implements PandroidCall<R> { private final Call<R> call; private final boolean needResponse; PandroidCallImpl(Call<R> call, boolean needResponse) { this.call = call; this.needResponse = needResponse; } @Override public void enqueue(final ActionDelegate delegate) { if (delegate instanceof Cancellable) ((CancellableActionDelegate) delegate).addCancelListener(new CancellableActionDelegate.CancelListener() { @Override public void onCancel() { call.cancel(); } }); final long startTime = System.currentTimeMillis(); call.enqueue( new Callback<R>() { @Override public void onResponse(Call<R> call, final Response<R> response) { if (needResponse) { post( new Runnable() { @Override public void run() { delegate.onSuccess(response); } } ); } else { if (response.isSuccessful()) { post( new Runnable() { @Override public void run() { delegate.onSuccess(response.body()); } } ); } else { byte[] bytes = new byte[0]; try { bytes = response.errorBody().bytes(); } catch (IOException ignore) { } onError(new NetworkException(response.raw().request().url().toString(), response.code(), (TreeMap) response.headers().toMultimap(), new Exception(response.message()), bytes, System.currentTimeMillis() - startTime)); } } } @Override public void onFailure(Call<R> call, final Throwable t) { onError(new Exception(t)); } private void onError(final Exception e) { post(new Runnable() { @Override public void run() { delegate.onError(errorFormatter != null ? errorFormatter.format(e) : e); } }); } } ); } @Override public Response<R> execute() throws IOException { return call.execute(); } @Override public void enqueue(Callback<R> callback) { call.enqueue(callback); } @Override public boolean isExecuted() { return call.isExecuted(); } @Override public void cancel() { call.cancel(); } @Override public boolean isCanceled() { return call.isCanceled(); } @Override public PandroidCall<R> clone() { PandroidCallImpl<R> pandroidCall = new PandroidCallImpl<>(call.clone(), needResponse); return rxAndroidEnable ? new RxPandroidCall(pandroidCall) : pandroidCall; } @Override public Request request() { return call.request(); } } }
refactor (PandroidCall) : refactor exception in onFailure
pandroid-library/src/main/java/com/leroymerlin/pandroid/net/PandroidCallAdapterFactory.java
refactor (PandroidCall) : refactor exception in onFailure
<ide><path>android-library/src/main/java/com/leroymerlin/pandroid/net/PandroidCallAdapterFactory.java <ide> <ide> @Override <ide> public void onFailure(Call<R> call, final Throwable t) { <del> <del> onError(new Exception(t)); <add> if(t instanceof Exception) { <add> onError(((Exception) t)); <add> } else { <add> onError(new Exception(t)); <add> } <ide> } <ide> <ide> private void onError(final Exception e) {
JavaScript
mit
c49a563d1748f7363414414c031d9b556b9e1c22
0
callsea1/browser-video-call_nodejs
// silly chrome wants SSL to do screensharing var fs = require('fs'), express = require('express'), https = require('https'), http = require('http'), pg = require('pg'); var privateKey = fs.readFileSync('fakekeys/privatekey.pem').toString(), certificate = fs.readFileSync('fakekeys/certificate.pem').toString(); var app = express(); var roomlist = {}; // app.use(express.static(__dirname)); // Set the view directory to /views app.set("views", __dirname + "/views"); //assets app.use(express.static(__dirname + '/public')); app.use(express.cookieParser()); app.use(express.urlencoded()); // Let's get rid of defaut Jade and use HTML templating language app.engine('html', require('ejs').renderFile); app.set("view engine", "html"); app.get("/", function(request, response) { // The landing page JS will take care of clearing cookies. response.render('landing', { title: 'ejs' }); }); app.get("/room", function(request, response) { var data = request.body; var qs = Object.keys(request.query); if (qs[0]) { console.log("Room requested " + qs[0]); if (roomlist[qs[0]] == 2) { // Room requested, already two participants console.log("Requested room already has two participants."); response.cookie('flash','That room is full') .redirect('/'); } else { roomlist[qs[0]] = 2; console.log("New user joined room."); response.render('index', { title: 'ejs' }); } } else { console.log("No room requested."); console.log("Cookies: " + JSON.stringify(request.cookies)); if (request.cookies && request.cookies.auth) { console.log("User authorized to create a room."); response.render('index', { title: 'ejs' }); } else { console.log("User needs to authenticate first."); response.redirect('/'); } } // Should not get here. response.render('index', { title: 'ejs' }); }); app.post("/exist", function(request,response) { var data = request.body; console.log("Login attempted. " + JSON.stringify(data)); pg.connect(process.env.DATABASE_URL, function(err, client, done) { client.query('SELECT * FROM users where email=$1 and password=$2', [data.email,data.password], function(err, result) { console.log("Email is " + data.email); console.log("Result is " + JSON.stringify(result.rows)); done(); if(err) return console.error(err); if (result.rows.length > 0) { response.cookie('auth',data.email) .cookie('name',result.rows[0].name).redirect('/room'); } else response.cookie('flash','Login incorrect').redirect('/'); }); }); }); // HERE app.post("/newuser", function(request,response) { var data = request.body; console.log("Login attempted. " + JSON.stringify(data)); pg.connect(process.env.DATABASE_URL, function(err, client, done) { client.query('SELECT * FROM users where email=$1', [data.email], function(err, result) { console.log("Email is " + data.email); done(); if(err) return console.error(err); if (result.rows.length > 0) { response.cookie('auth',data.email) .cookie('flash','User already exists.').redirect('/'); } }); client.query('INSERT INTO users(name,email,password) values ($1,$2,$3)', [data.name,data.email,data.password], function(err, result) { done(); if(err) { console.error(err) response.cookie('auth',data.email) .cookie('flash','Database error').redirect('/'); } else { console.log("New user added. " + data.email); response.cookie('auth',data.email) .cookie('name',data.name).redirect('/room'); } }); }); }); // Connect to postgres console.log("Postresql URL is " + process.env.DATABASE_URL); pg.connect(process.env.DATABASE_URL, function(err, client, done) { // client.query('INSERT into users values (default,$1,$2)',['foo','[email protected]']); client.query('SELECT * FROM users', function(err, result) { done(); if(err) return console.error(err); console.log(result.rows); }); }); var open_port = Number(process.env.PORT || 5000); // var secure_port = Number(process.env.PORT || 5001); // https.createServer({key: privateKey, cert: certificate}, app).listen(secure_port); var server = http.createServer(app).listen(open_port); // Open web socket var WebSocketServer = require('ws').Server; var wss = new WebSocketServer({server: server}); console.log('websocket server created'); wss.on('connection', function(ws) { //var id = setInterval(function() { // ws.send(JSON.stringify(new Date()), function() { }); // }, 1000); var myRoomId = "none"; console.log('websocket connection open'); ws.on('message', function(data,flags) { data = JSON.parse(data); // Register a room switch (data.key) { case "room": ws.roomId = data.value; roomlist[ws.roomId] = 1; console.log("Room created: " + ws.roomId); ws.send(JSON.stringify("Room is " + ws.roomId),function () {}); console.log("Rooms are: " + JSON.stringify(roomlist)); break; case "login": } }); ws.on('close', function() { delete roomlist[ws.roomId]; console.log('websocket connection close'); console.log('room close is ' + ws.roomId); }); }); var status = 'Not reset yet.'; console.log('running on http://localhost:5000');
server.js
// silly chrome wants SSL to do screensharing var fs = require('fs'), express = require('express'), https = require('https'), http = require('http'), pg = require('pg'); var privateKey = fs.readFileSync('fakekeys/privatekey.pem').toString(), certificate = fs.readFileSync('fakekeys/certificate.pem').toString(); var app = express(); var roomlist = {}; // app.use(express.static(__dirname)); // Set the view directory to /views app.set("views", __dirname + "/views"); //assets app.use(express.static(__dirname + '/public')); app.use(express.cookieParser()); app.use(express.urlencoded()); // Let's get rid of defaut Jade and use HTML templating language app.engine('html', require('ejs').renderFile); app.set("view engine", "html"); app.get("/", function(request, response) { response.render('landing', { title: 'ejs' }); }); app.get("/room", function(request, response) { var data = request.body; var qs = Object.keys(request.query); if (qs[0]) { console.log("Room requested " + qs[0]); if (roomlist[qs[0]] == 2) { // Room requested, already two participants console.log("Requested room already has two participants."); response.cookie('flash','That room is full') .redirect('landing'); } else { roomlist[qs[0]] = 2; console.log("New user joined room."); response.render('index', { title: 'ejs' }); } } else { console.log("No room requested."); console.log("Cookies: " + JSON.stringify(request.cookies)); if (request.cookies && request.cookies.auth) { console.log("User authorized to create a room."); response.render('index', { title: 'ejs' }); } else { console.log("User needs to authenticate first."); response.redirect('/'); } } // Should not get here. response.render('index', { title: 'ejs' }); }); app.post("/exist", function(request,response) { var data = request.body; console.log("Login attempted. " + JSON.stringify(data)); pg.connect(process.env.DATABASE_URL, function(err, client, done) { client.query('SELECT * FROM users where email=$1 and password=$2', [data.email,data.password], function(err, result) { console.log("Email is " + data.email); console.log("Result is " + JSON.stringify(result.rows)); done(); if(err) return console.error(err); if (result.rows.length > 0) { response.cookie('auth',data.email) .cookie('name',result.rows[0].name).redirect('/room'); } else response.cookie('flash','Login incorrect').redirect('/'); }); }); }); // HERE app.post("/newuser", function(request,response) { var data = request.body; console.log("Login attempted. " + JSON.stringify(data)); pg.connect(process.env.DATABASE_URL, function(err, client, done) { client.query('SELECT * FROM users where email=$1', [data.email], function(err, result) { console.log("Email is " + data.email); done(); if(err) return console.error(err); if (result.rows.length > 0) { response.cookie('auth',data.email) .cookie('flash','User already exists.').redirect('/'); } }); client.query('INSERT INTO users(name,email,password) values ($1,$2,$3)', [data.name,data.email,data.password], function(err, result) { done(); if(err) { console.error(err) response.cookie('auth',data.email) .cookie('flash','Database error').redirect('/'); } else { console.log("New user added. " + data.email); response.cookie('auth',data.email) .cookie('name',data.name).redirect('/room'); } }); }); }); // Connect to postgres console.log("Postresql URL is " + process.env.DATABASE_URL); pg.connect(process.env.DATABASE_URL, function(err, client, done) { // client.query('INSERT into users values (default,$1,$2)',['foo','[email protected]']); client.query('SELECT * FROM users', function(err, result) { done(); if(err) return console.error(err); console.log(result.rows); }); }); var open_port = Number(process.env.PORT || 5000); // var secure_port = Number(process.env.PORT || 5001); // https.createServer({key: privateKey, cert: certificate}, app).listen(secure_port); var server = http.createServer(app).listen(open_port); // Open web socket var WebSocketServer = require('ws').Server; var wss = new WebSocketServer({server: server}); console.log('websocket server created'); wss.on('connection', function(ws) { //var id = setInterval(function() { // ws.send(JSON.stringify(new Date()), function() { }); // }, 1000); var myRoomId = "none"; console.log('websocket connection open'); ws.on('message', function(data,flags) { data = JSON.parse(data); // Register a room switch (data.key) { case "room": ws.roomId = data.value; roomlist[ws.roomId] = 1; console.log("Room created: " + ws.roomId); ws.send(JSON.stringify("Room is " + ws.roomId),function () {}); console.log("Rooms are: " + JSON.stringify(roomlist)); break; case "login": } }); ws.on('close', function() { roomlist[ws.roomId] = 1; console.log('websocket connection close'); console.log('room close is ' + ws.roomId); }); }); var status = 'Not reset yet.'; console.log('running on http://localhost:5000');
Fixed redirect location.
server.js
Fixed redirect location.
<ide><path>erver.js <ide> app.set("view engine", "html"); <ide> <ide> app.get("/", function(request, response) { <add> // The landing page JS will take care of clearing cookies. <ide> response.render('landing', { title: 'ejs' }); <ide> }); <ide> <ide> // Room requested, already two participants <ide> console.log("Requested room already has two participants."); <ide> response.cookie('flash','That room is full') <del> .redirect('landing'); <add> .redirect('/'); <ide> } else { <ide> roomlist[qs[0]] = 2; <ide> console.log("New user joined room."); <ide> <ide> }); <ide> ws.on('close', function() { <del> roomlist[ws.roomId] = 1; <add> delete roomlist[ws.roomId]; <ide> console.log('websocket connection close'); <ide> console.log('room close is ' + ws.roomId); <ide> });
JavaScript
mit
db9188f0614018f27ef316a136413cdb71087ec1
0
swachob/Project-Site,swachob/Project-Site
var $ = require('jquery'); // legacy loading for bootstrap window.jQuery = window.$ = $; require('bootstrap'); import _ from 'underscore'; import Backbone from 'backbone'; import Handlebars from 'handlebars'; import lscache from 'lscache'; import rawTemplate from 'templates/todoItem.html'; // Backbone Todo App var TodoModel; var TodoControllerView; var TodoView; var todoModel; var todoControllerView; // Model TodoModel = Backbone.Model.extend({ defaults: { todos: [] }, todoSchema: { id: 0, title: "", completed: false }, fetch: function(){ var data = lscache.get('todos'); data = this.applySchema(data); this.set('todos', data); }, save: function(){ var data = this.get('todos'); data = this.applySchema(data); lscache.set('todos', data); }, applySchema: function(todos){ var data = todos; var schema = this.todoSchema; data = (_.isArray(todos)) ? data : []; data = data.map(function(todo, index){ todo.id = index; return _defaults(todo, schema); }); return data; } }); todoModel = new TodoModel(); // View TodoControllerView = Backbone.View.extend({ el: 'body', model: todoModel, events: { }, initialize: function(){}, render: function(){ alert('backbone!'); } }); todoControllerView = new TodoControllerView(); module.exports = todoControllerView;
client/pages/todo-backbone.js
var $ = require('jquery'); // legacy loading for bootstrap window.jQuery = window.$ = $; require('bootstrap'); import _ from 'underscore'; import Backbone from 'backbone'; import Handlebars from 'handlebars'; import lscache from 'lscache'; import rawTemplate from 'templates/todoItem.html'; // Backbone Todo App var TodoModel; var TodoControllerView; var TodoView; var todoModel; var todoControllerView; // Model TodoModel = Backbone.Model.extend({ defaults: { }, fetch: function(){ // gets the data }, save: function(){ // saves the data } }); todoModel = new TodoModel(); // View TodoControllerView = Backbone.View.extend({ el: 'body', model: todoModel, events: { }, initialize: function(){}, render: function(){ alert('backbone!'); } }); todoControllerView = new TodoControllerView(); module.exports = todoControllerView;
adding structure
client/pages/todo-backbone.js
adding structure
<ide><path>lient/pages/todo-backbone.js <ide> <ide> TodoModel = Backbone.Model.extend({ <ide> defaults: { <add> todos: [] <add> }, <add> todoSchema: { <add> id: 0, <add> title: "", <add> completed: false <ide> }, <ide> fetch: function(){ <del> // gets the data <add> var data = lscache.get('todos'); <add> data = this.applySchema(data); <add> this.set('todos', data); <ide> }, <ide> save: function(){ <del> // saves the data <add> var data = this.get('todos'); <add> data = this.applySchema(data); <add> lscache.set('todos', data); <add> }, <add> applySchema: function(todos){ <add> var data = todos; <add> var schema = this.todoSchema; <add> data = (_.isArray(todos)) ? data : []; <add> data = data.map(function(todo, index){ <add> todo.id = index; <add> return _defaults(todo, schema); <add> }); <add> return data; <ide> } <ide> }); <ide>
JavaScript
mit
01b23aac3b14dab330942ce3f3c0fbb8bf41d2b4
0
baracudaengine/SailsUi,harrissoerja/sails,saronwei/sails,Josebaseba/sails,vip-git/sails,tjwebb/sails,togusafish/logikinc-_-sails,prssn/sails,pmq20/sails,jsisaev1/sails,tempbottle/sails,winlolo/sails,listepo/sails,leobudima/sails,vip-git/sails,metidia/sails,anweiss/sails,Karnith/sails-for-gulp,balderdashy/sails,ctartist621/sails,mphasize/sails,taogb/sails,JumpLink/sails,hokkoo/sails,dylannnn/sails,Hanifb/sails,yangchuoxian/sails,denismars/sails,janladaking/sails,Shyp/sails,alex-zhang/sails,wsaccaco/sails,leedm777/sails,jianpingw/sails,artBrown/sails,marnusw/sails,jakutis/sails,justsml/sails,corbanb/sails,AnyPresence/sails,saniko/soundcloud_mithril,antoniopol06/sails,jenalgit/sails,erkstruwe/sails,dbuentello/sails,sunnycmf/sails,hellowin/sails,apowers313/sails,rlugojr/sails,xjpro/sails-windows-associations,haavardw/sails,krishnaglick/sails,mauricionr/sails,hokkoo/sails,cazulu/sails,t2013anurag/sails,antodoms/sails,konstantinzolotarev/sails,youprofit/sails,adrianha/sails,scippio/sails,Benew/sails,jianpingw/sails,kevinburke/sails,curphey/sails,boarderdav/sails,rlugojr/sails,giano/sails,saniko/soundcloud_mithril,shaunstanislaus/sails,calling/sails,zand3rs/sails,alexferreira/sails,mnaughto/sails,yinhe007/sails,EdisonSu768/sails,giano/sails
module.exports = function (sails) { /** * Module dependencies. */ var _ = require('lodash'), express = require('express'); /** * Set up default global configuration for Sails */ return function defaultConfig (userConfig) { // If appPath not specified, use process.cwd() to get the app dir userConfig.appPath = userConfig.appPath || process.cwd(); // Paths for application modules and key files var paths = { app : userConfig.appPath, config : userConfig.appPath + '/config', tmp : userConfig.appPath + '/.tmp' }; _.extend(paths, { controllers : paths.app + '/api/controllers', models : paths.app + '/api/models', services : paths.app + '/api/services', policies : paths.app + '/api/policies', adapters : paths.app + '/api/adapters', hooks : paths.app + '/api/hooks', 'public' : paths.app + '/.tmp/public', templates : paths.app + '/assets/templates', dependencies : paths.app + '/dependencies', views : paths.app + '/views', layout : paths.app + '/views/layout.ejs' }); // Set up config defaults return { // Default hooks hooks: { request : require('../hooks/request'), orm : require('../hooks/orm'), views : require('../hooks/views'), controllers : require('../hooks/controllers'), sockets : require('../hooks/sockets'), pubsub : require('../hooks/pubsub'), policies : require('../hooks/policies'), csrf : require('../hooks/csrf'), cors : require('../hooks/cors'), // IMPORTANT -- must be AFTER csrf! i18n : require('../hooks/i18n'), http : require('../hooks/http') }, // Default 404 (not found) handler 404: function notFound (req, res) { res.send(404); }, // Default 500 (server error) handler 500: function (err, req, res) { res.send(err, 500); }, // Default 403 (forbidden) handler 403: function (err, req, res) { res.send(err, 403); }, // Default 400 (bad request) handler 400: function (err, req, res) { res.send(err, 400); }, // Controller config controllers: { // (Note: global controller.blueprints config may be overridden on a per-controller basis // by setting the 'blueprint' property in a controller) blueprints: { // Whether routes are automatically generated for controller actions actions: true, // e.g. '/:controller/find/:id' shortcuts: true, // e.g. 'get /:controller/:id?': 'foo.find' rest: true, // Optional mount path prefix for blueprint routes // e.g. '/api/v2' prefix: '', // If a blueprint REST route catches a request, // only match an `id` if it's an integer expectIntegerId: false, // Enable JSONP callbacks on REST blueprints jsonp: false, // Pluralize controller names in routes pluralize: false } }, // View hook config views: { // Engine for views (can be ejs, haml, etc.) engine: 'ejs', // Layout is on by default, in the top level of the view directory // true === use default // false === don't use a layout // string === path to layout layout: true }, // i18n i18n: { locales: ['en', 'es'], defaultLocale: 'en', localesDirectory: '/config/locales' }, // CSRF middleware protection, all non-GET requests must send '_csrf' parmeter // _csrf is a parameter for views, and is also available via GET at /csrfToken csrf: false, cors: { origin: '*', credentials: true, methods: 'GET, POST, PUT, DELETE, OPTIONS, HEAD', headers: 'content-type' }, // File upload settings fileUpload: { maxMB: 10 }, // Port to run this app on port: 1337, // Self-awareness: the host the server *thinks it is* host: 'localhost', // Name of application for layout title appName: 'Sails', // Environment to run this app in; one of: ["development", "production"] environment: 'development', // Paths for application modules and key files paths: paths, // Default model properties adapters: { 'default': 'disk', memory: { module: 'sails-memory' }, disk: { module: 'sails-disk' }, mongo: { module : 'sails-mongo', host : 'localhost', user : 'root' }, mysql: { module : 'sails-mysql', host : 'localhost', user : 'root' }, postgresql: { module : 'sails-postgresql', host : 'localhost', user : 'root' } }, // HTTP cache configuration cache: { maxAge: 31557600000 }, // Session store configuration session: { adapter: 'memory', key: "sails.sid" }, // Logging config log: { level: 'info' }, // Variables which will be made globally accessible globals: { _: true, async: true, sails: true, services: true, adapters: true, models: true }, // Custom options for express server express: { // Options to pass directly into the Express server // when it is instantiated // (or false to disable) serverOptions: false, // Custom express middleware function to use customMiddleware: false, // HTTP body parser middleware to use // (or false to disable) // bodyParser: express.bodyParser, // If bodyParser doesn't understand the HTTP body request data, // run it again with an artificial header, forcing it to try and parse // the request body as JSON // (this allows JSON to be used as your request data without the need to // specify a 'Content-type: application/json' header) retryBodyParserWithJSON: true, // Cookie parser middleware to use // (or false to disable) // cookieParser: express.cookieParser, // HTTP method override middleware // (or false to disable) // // This option allows artificial query params to be passed to trick // Express into thinking a different HTTP verb was used. // Useful when supporting an API for user-agents which don't allow // PUT or DELETE requests methodOverride: express.methodOverride }, sockets: { // Setup adapter to use for socket.io MQ (pubsub) store // (`undefined` indicates default memory store) // NOTE: Default memory store will not work for clustered deployments with multiple instances. adapter: undefined, // A array of allowed transport methods which the clients will try to use. // The flashsocket transport is disabled by default // You can enable flashsockets by adding 'flashsocket' to this list: transports: [ 'websocket', 'htmlfile', 'xhr-polling', 'jsonp-polling' ], // Match string representing the origins that are allowed to connect to the Socket.IO server origins: '*:*', // Should we use heartbeats to check the health of Socket.IO connections? heartbeats: true, // When client closes connection, the # of seconds to wait before attempting a reconnect. // This value is sent to the client after a successful handshake. 'close timeout': 60, // The # of seconds between heartbeats sent from the client to the server // This value is sent to the client after a successful handshake. 'heartbeat timeout': 60, // The max # of seconds to wait for an expcted heartbeat before declaring the pipe broken // This number should be less than the `heartbeat timeout` 'heartbeat interval': 25, // The maximum duration of one HTTP poll- // if it exceeds this limit it will be closed. 'polling duration': 20, // Enable the flash policy server if the flashsocket transport is enabled 'flash policy server': false, // By default the Socket.IO client will check port 10843 on your server // to see if flashsocket connections are allowed. // The Adobe Flash Player normally uses 843 as default port, // but Socket.io defaults to a non root port (10843) by default // // If you are using a hosting provider that doesn't allow you to start servers // other than on port 80 or the provided port, and you still want to support flashsockets // you can set the `flash policy port` to -1 'flash policy port': 10843, // Used by the HTTP transports. The Socket.IO server buffers HTTP request bodies up to this limit. // This limit is not applied to websocket or flashsockets. 'destroy buffer size': '10E7', // Do we need to destroy non-socket.io upgrade requests? 'destroy upgrade': true, // Does Socket.IO need to serve the static resources like socket.io.js and WebSocketMain.swf etc. 'browser client': true, // Cache the Socket.IO file generation in the memory of the process // to speed up the serving of the static files. 'browser client cache': true, // Does Socket.IO need to send a minified build of the static client script? 'browser client minification': false, // Does Socket.IO need to send an ETag header for the static requests? 'browser client etag': false, // Adds a Cache-Control: private, x-gzip-ok="", max-age=31536000 header to static requests, // but only if the file is requested with a version number like /socket.io/socket.io.v0.9.9.js. 'browser client expires': 315360000, // Does Socket.IO need to GZIP the static files? // This process is only done once and the computed output is stored in memory. // So we don't have to spawn a gzip process for each request. 'browser client gzip': false, // A function that should serve all static handling, including socket.io.js et al. 'browser client handler': false, // Meant to be used when running socket.io behind a proxy. // Should be set to true when you want the location handshake to match the protocol of the origin. // This fixes issues with terminating the SSL in front of Node // and forcing location to think it's wss instead of ws. 'match origin protocol' : false, // Global authorization for Socket.IO access, // this is called when the initial handshake is performed with the server. // // By default, Sails verifies that a valid cookie was sent with the upgrade request // However, in the case of cross-domain requests, no cookies are sent for some transports, // so sockets will fail to connect. You might also just want to allow anyone to connect w/o a cookie! // // To bypass this cookie check, you can set `authorization: false`, // which will silently create an anonymous cookie+session for the user // // `authorization: true` indicates that Sails should use the built-in logic // // You can also use your own custom logic with: // `authorization: function (data, accept) { ... }` authorization: true, // Default onConnect behavior is a noop onConnect: function () {}, // Direct access to the socket.io MQ store config // The 'adapter' property is the preferred method // (`undefined` indicates that Sails should defer to the 'adapter' config) store: undefined, // A logger instance that is used to output log information. // (`undefined` indicates deferment to the main Sails log config) logger: undefined, // The amount of detail that the server should output to the logger. // (`undefined` indicates deferment to the main Sails log config) 'log level': undefined, // Whether to color the log type when output to the logger. // (`undefined` indicates deferment to the main Sails log config) 'log colors': undefined, // A Static instance that is used to serve the socket.io client and its dependencies. // (`undefined` indicates use default) 'static': undefined, // The entry point where Socket.IO starts looking for incoming connections. // This should be the same between the client and the server. resource: '/socket.io' }, // SSL cert settings go here ssl: {} }; }; };
lib/configuration/defaults.js
module.exports = function (sails) { /** * Module dependencies. */ var _ = require('lodash'), express = require('express'); /** * Set up default global configuration for Sails */ return function defaultConfig (userConfig) { // If appPath not specified, use process.cwd() to get the app dir userConfig.appPath = userConfig.appPath || process.cwd(); // Paths for application modules and key files var paths = { app : userConfig.appPath, config : userConfig.appPath + '/config', tmp : userConfig.appPath + '/.tmp' }; _.extend(paths, { controllers : paths.app + '/api/controllers', models : paths.app + '/api/models', services : paths.app + '/api/services', policies : paths.app + '/api/policies', adapters : paths.app + '/api/adapters', hooks : paths.app + '/api/hooks', 'public' : paths.app + '/.tmp/public', templates : paths.app + '/assets/templates', dependencies : paths.app + '/dependencies', views : paths.app + '/views', layout : paths.app + '/views/layout.ejs' }); // Set up config defaults return { // Default hooks hooks: { request : require('../hooks/request'), orm : require('../hooks/orm'), views : require('../hooks/views'), controllers : require('../hooks/controllers'), sockets : require('../hooks/sockets'), pubsub : require('../hooks/pubsub'), policies : require('../hooks/policies'), csrf : require('../hooks/csrf'), cors : require('../hooks/cors'), // IMPORTANT -- must be AFTER csrf! i18n : require('../hooks/i18n'), http : require('../hooks/http') }, // Default 404 (not found) handler 404: function notFound (req, res) { res.send(404); }, // Default 500 (server error) handler 500: function (err, req, res) { res.send(err, 500); }, // Default 403 (forbidden) handler 403: function (err, req, res) { res.send(err, 403); }, // Default 400 (bad request) handler 400: function (err, req, res) { res.send(err, 400); }, // Controller config controllers: { // (Note: global controller.blueprints config may be overridden on a per-controller basis // by setting the 'blueprint' property in a controller) blueprints: { // Whether routes are automatically generated for controller actions actions: true, // e.g. '/:controller/find/:id' shortcuts: true, // e.g. 'get /:controller/:id?': 'foo.find' rest: true, // Optional mount path prefix for blueprint routes // e.g. '/api/v2' prefix: '', // If a blueprint REST route catches a request, // only match an `id` if it's an integer expectIntegerId: false } }, // View hook config views: { // Engine for views (can be ejs, haml, etc.) engine: 'ejs', // Layout is on by default, in the top level of the view directory // true === use default // false === don't use a layout // string === path to layout layout: true }, // i18n i18n: { locales: ['en', 'es'], defaultLocale: 'en', localesDirectory: '/config/locales' }, // CSRF middleware protection, all non-GET requests must send '_csrf' parmeter // _csrf is a parameter for views, and is also available via GET at /csrfToken csrf: false, cors: { origin: '*', credentials: true, methods: 'GET, POST, PUT, DELETE, OPTIONS, HEAD', headers: 'content-type' }, // File upload settings fileUpload: { maxMB: 10 }, // Port to run this app on port: 1337, // Self-awareness: the host the server *thinks it is* host: 'localhost', // Name of application for layout title appName: 'Sails', // Environment to run this app in; one of: ["development", "production"] environment: 'development', // Paths for application modules and key files paths: paths, // Default model properties adapters: { 'default': 'disk', memory: { module: 'sails-memory' }, disk: { module: 'sails-disk' }, mongo: { module : 'sails-mongo', host : 'localhost', user : 'root' }, mysql: { module : 'sails-mysql', host : 'localhost', user : 'root' }, postgresql: { module : 'sails-postgresql', host : 'localhost', user : 'root' } }, // HTTP cache configuration cache: { maxAge: 31557600000 }, // Session store configuration session: { adapter: 'memory', key: "sails.sid" }, // Logging config log: { level: 'info' }, // Variables which will be made globally accessible globals: { _: true, async: true, sails: true, services: true, adapters: true, models: true }, // Custom options for express server express: { // Options to pass directly into the Express server // when it is instantiated // (or false to disable) serverOptions: false, // Custom express middleware function to use customMiddleware: false, // HTTP body parser middleware to use // (or false to disable) // bodyParser: express.bodyParser, // If bodyParser doesn't understand the HTTP body request data, // run it again with an artificial header, forcing it to try and parse // the request body as JSON // (this allows JSON to be used as your request data without the need to // specify a 'Content-type: application/json' header) retryBodyParserWithJSON: true, // Cookie parser middleware to use // (or false to disable) // cookieParser: express.cookieParser, // HTTP method override middleware // (or false to disable) // // This option allows artificial query params to be passed to trick // Express into thinking a different HTTP verb was used. // Useful when supporting an API for user-agents which don't allow // PUT or DELETE requests methodOverride: express.methodOverride }, sockets: { // Setup adapter to use for socket.io MQ (pubsub) store // (`undefined` indicates default memory store) // NOTE: Default memory store will not work for clustered deployments with multiple instances. adapter: undefined, // A array of allowed transport methods which the clients will try to use. // The flashsocket transport is disabled by default // You can enable flashsockets by adding 'flashsocket' to this list: transports: [ 'websocket', 'htmlfile', 'xhr-polling', 'jsonp-polling' ], // Match string representing the origins that are allowed to connect to the Socket.IO server origins: '*:*', // Should we use heartbeats to check the health of Socket.IO connections? heartbeats: true, // When client closes connection, the # of seconds to wait before attempting a reconnect. // This value is sent to the client after a successful handshake. 'close timeout': 60, // The # of seconds between heartbeats sent from the client to the server // This value is sent to the client after a successful handshake. 'heartbeat timeout': 60, // The max # of seconds to wait for an expcted heartbeat before declaring the pipe broken // This number should be less than the `heartbeat timeout` 'heartbeat interval': 25, // The maximum duration of one HTTP poll- // if it exceeds this limit it will be closed. 'polling duration': 20, // Enable the flash policy server if the flashsocket transport is enabled 'flash policy server': false, // By default the Socket.IO client will check port 10843 on your server // to see if flashsocket connections are allowed. // The Adobe Flash Player normally uses 843 as default port, // but Socket.io defaults to a non root port (10843) by default // // If you are using a hosting provider that doesn't allow you to start servers // other than on port 80 or the provided port, and you still want to support flashsockets // you can set the `flash policy port` to -1 'flash policy port': 10843, // Used by the HTTP transports. The Socket.IO server buffers HTTP request bodies up to this limit. // This limit is not applied to websocket or flashsockets. 'destroy buffer size': '10E7', // Do we need to destroy non-socket.io upgrade requests? 'destroy upgrade': true, // Does Socket.IO need to serve the static resources like socket.io.js and WebSocketMain.swf etc. 'browser client': true, // Cache the Socket.IO file generation in the memory of the process // to speed up the serving of the static files. 'browser client cache': true, // Does Socket.IO need to send a minified build of the static client script? 'browser client minification': false, // Does Socket.IO need to send an ETag header for the static requests? 'browser client etag': false, // Adds a Cache-Control: private, x-gzip-ok="", max-age=31536000 header to static requests, // but only if the file is requested with a version number like /socket.io/socket.io.v0.9.9.js. 'browser client expires': 315360000, // Does Socket.IO need to GZIP the static files? // This process is only done once and the computed output is stored in memory. // So we don't have to spawn a gzip process for each request. 'browser client gzip': false, // A function that should serve all static handling, including socket.io.js et al. 'browser client handler': false, // Meant to be used when running socket.io behind a proxy. // Should be set to true when you want the location handshake to match the protocol of the origin. // This fixes issues with terminating the SSL in front of Node // and forcing location to think it's wss instead of ws. 'match origin protocol' : false, // Global authorization for Socket.IO access, // this is called when the initial handshake is performed with the server. // // By default, Sails verifies that a valid cookie was sent with the upgrade request // However, in the case of cross-domain requests, no cookies are sent for some transports, // so sockets will fail to connect. You might also just want to allow anyone to connect w/o a cookie! // // To bypass this cookie check, you can set `authorization: false`, // which will silently create an anonymous cookie+session for the user // // `authorization: true` indicates that Sails should use the built-in logic // // You can also use your own custom logic with: // `authorization: function (data, accept) { ... }` authorization: true, // Default onConnect behavior is a noop onConnect: function () {}, // Direct access to the socket.io MQ store config // The 'adapter' property is the preferred method // (`undefined` indicates that Sails should defer to the 'adapter' config) store: undefined, // A logger instance that is used to output log information. // (`undefined` indicates deferment to the main Sails log config) logger: undefined, // The amount of detail that the server should output to the logger. // (`undefined` indicates deferment to the main Sails log config) 'log level': undefined, // Whether to color the log type when output to the logger. // (`undefined` indicates deferment to the main Sails log config) 'log colors': undefined, // A Static instance that is used to serve the socket.io client and its dependencies. // (`undefined` indicates use default) 'static': undefined, // The entry point where Socket.IO starts looking for incoming connections. // This should be the same between the client and the server. resource: '/socket.io' }, // SSL cert settings go here ssl: {} }; }; };
Add pluralize (and jsonp) global blueprint config defaults
lib/configuration/defaults.js
Add pluralize (and jsonp) global blueprint config defaults
<ide><path>ib/configuration/defaults.js <ide> <ide> // If a blueprint REST route catches a request, <ide> // only match an `id` if it's an integer <del> expectIntegerId: false <add> expectIntegerId: false, <add> <add> // Enable JSONP callbacks on REST blueprints <add> jsonp: false, <add> <add> // Pluralize controller names in routes <add> pluralize: false <ide> } <ide> }, <ide>
Java
apache-2.0
0fe4bcc4c77c4aab32f509268d6caed8b01fafb4
0
commons-app/apps-android-commons,nicolas-raoul/apps-android-commons,sandarumk/apps-android-commons,psh/apps-android-commons,commons-app/apps-android-commons,psh/apps-android-commons,maskaravivek/apps-android-commons,dbrant/apps-android-commons,domdomegg/apps-android-commons,maskaravivek/apps-android-commons,misaochan/apps-android-commons,wikimedia/apps-android-commons,misaochan/apps-android-commons,commons-app/apps-android-commons,misaochan/apps-android-commons,RSBat/apps-android-commons,sandarumk/apps-android-commons,whym/apps-android-commons,akaita/apps-android-commons,commons-app/apps-android-commons,nicolas-raoul/apps-android-commons,dbrant/apps-android-commons,neslihanturan/apps-android-commons,neslihanturan/apps-android-commons,domdomegg/apps-android-commons,maskaravivek/apps-android-commons,domdomegg/apps-android-commons,domdomegg/apps-android-commons,misaochan/apps-android-commons,whym/apps-android-commons,maskaravivek/apps-android-commons,neslihanturan/apps-android-commons,whym/apps-android-commons,nicolas-raoul/apps-android-commons,nicolas-raoul/apps-android-commons,domdomegg/apps-android-commons,dbrant/apps-android-commons,psh/apps-android-commons,RSBat/apps-android-commons,RSBat/apps-android-commons,tobias47n9e/apps-android-commons,wikimedia/apps-android-commons,psh/apps-android-commons,akaita/apps-android-commons,akaita/apps-android-commons,misaochan/apps-android-commons,neslihanturan/apps-android-commons,sandarumk/apps-android-commons,whym/apps-android-commons,tobias47n9e/apps-android-commons,commons-app/apps-android-commons,neslihanturan/apps-android-commons,dbrant/apps-android-commons,tobias47n9e/apps-android-commons,wikimedia/apps-android-commons,misaochan/apps-android-commons,psh/apps-android-commons,maskaravivek/apps-android-commons
package fr.free.nrw.commons.caching; import android.util.Log; import com.github.varunpant.quadtree.Point; import com.github.varunpant.quadtree.QuadTree; import java.util.ArrayList; import java.util.List; import fr.free.nrw.commons.upload.MwVolleyApi; public class CacheController { private double x, y; private QuadTree quadTree; private Point[] pointsFound; private double xMinus, xPlus, yMinus, yPlus; private static final String TAG = CacheController.class.getName(); private static final int EARTH_RADIUS = 6378137; public CacheController() { quadTree = new QuadTree(-180, -90, +180, +90); } public void setQtPoint(double decLongitude, double decLatitude) { x = decLongitude; y = decLatitude; Log.d(TAG, "New QuadTree created"); Log.d(TAG, "X (longitude) value: " + x + ", Y (latitude) value: " + y); } public void cacheCategory() { List<String> pointCatList = new ArrayList<String>(); if (MwVolleyApi.GpsCatExists.getGpsCatExists() == true) { pointCatList.addAll(MwVolleyApi.getGpsCat()); Log.d(TAG, "Categories being cached: " + pointCatList); } else { Log.d(TAG, "No categories found, so no categories cached"); } quadTree.set(x, y, pointCatList); } public List findCategory() { //Convert decLatitude and decLongitude to a coordinate offset range convertCoordRange(); pointsFound = quadTree.searchWithin(xMinus, yMinus, xPlus, yPlus); List<String> displayCatList = new ArrayList<String>(); Log.d(TAG, "Points found in quadtree: " + pointsFound); if (pointsFound.length != 0) { Log.d(TAG, "Entering for loop"); for (Point point : pointsFound) { Log.d(TAG, "Nearby point: " + point.toString()); displayCatList = (List<String>)point.getValue(); Log.d(TAG, "Nearby cat: " + point.getValue()); } Log.d(TAG, "Categories found in cache: " + displayCatList.toString()); } else { Log.d(TAG, "No categories found in cache"); } return displayCatList; } //Based on algorithm at http://gis.stackexchange.com/questions/2951/algorithm-for-offsetting-a-latitude-longitude-by-some-amount-of-meters public void convertCoordRange() { //Position, decimal degrees double lat = y; double lon = x; //offsets in meters double offset = 100; //Coordinate offsets in radians double dLat = offset/EARTH_RADIUS; double dLon = offset/(EARTH_RADIUS*Math.cos(Math.PI*lat/180)); //OffsetPosition, decimal degrees yPlus = lat + dLat * 180/Math.PI; yMinus = lat - dLat * 180/Math.PI; xPlus = lon + dLon * 180/Math.PI; xMinus = lon - dLon * 180/Math.PI; Log.d(TAG, "Search within: xMinus=" + xMinus + ", yMinus=" + yMinus + ", xPlus=" + xPlus + ", yPlus=" + yPlus); } }
commons/src/main/java/fr/free/nrw/commons/caching/CacheController.java
package fr.free.nrw.commons.caching; import android.util.Log; import com.github.varunpant.quadtree.Point; import com.github.varunpant.quadtree.QuadTree; import java.util.ArrayList; import java.util.List; import fr.free.nrw.commons.upload.MwVolleyApi; public class CacheController { private double x, y; private QuadTree quadTree; private Point[] pointsFound; private double xMinus, xPlus, yMinus, yPlus; private static final String TAG = CacheController.class.getName(); private static final int EARTH_RADIUS = 6378137; public CacheController() { quadTree = new QuadTree(-180, -90, +180, +90); } public void setQtPoint(double decLongitude, double decLatitude) { x = decLongitude; y = decLatitude; Log.d(TAG, "New QuadTree created"); Log.d(TAG, "X (longitude) value: " + x + ", Y (latitude) value: " + y); } public void cacheCategory() { List<String> pointCatList = new ArrayList<String>(); if (MwVolleyApi.GpsCatExists.getGpsCatExists() == true) { pointCatList.addAll(MwVolleyApi.getGpsCat()); Log.d(TAG, "Categories being cached: " + pointCatList); } else { Log.d(TAG, "No categories found, so no categories cached"); } quadTree.set(x, y, pointCatList); } public List findCategory() { //Convert decLatitude and decLongitude to a coordinate offset range convertCoordRange(); pointsFound = quadTree.searchWithin(xMinus, yMinus, xPlus, yPlus); List<String> displayCatList = new ArrayList<String>(); Log.d(TAG, "Points found in quadtree: " + pointsFound); if (pointsFound.length != 0) { Log.d(TAG, "Entering for loop"); for (Point point : pointsFound) { Log.d(TAG, "Nearby point: " + point.toString()); displayCatList = (List<String>)point.getValue(); Log.d(TAG, "Nearby cat: " + point.getValue()); } Log.d(TAG, "Categories found in cache: " + displayCatList.toString()); } else { Log.d(TAG, "No categories found in cache"); } return displayCatList; } public void convertCoordRange() { //Position, decimal degrees double lat = y; double lon = x; //offsets in meters double offset = 100; //Coordinate offsets in radians double dLat = offset/EARTH_RADIUS; double dLon = offset/(EARTH_RADIUS*Math.cos(Math.PI*lat/180)); //OffsetPosition, decimal degrees yPlus = lat + dLat * 180/Math.PI; yMinus = lat - dLat * 180/Math.PI; xPlus = lon + dLon * 180/Math.PI; xMinus = lon - dLon * 180/Math.PI; Log.d(TAG, "Search within: xMinus=" + xMinus + ", yMinus=" + yMinus + ", xPlus=" + xPlus + ", yPlus=" + yPlus); } }
Added algorithm link for searchWithin()
commons/src/main/java/fr/free/nrw/commons/caching/CacheController.java
Added algorithm link for searchWithin()
<ide><path>ommons/src/main/java/fr/free/nrw/commons/caching/CacheController.java <ide> return displayCatList; <ide> } <ide> <add> //Based on algorithm at http://gis.stackexchange.com/questions/2951/algorithm-for-offsetting-a-latitude-longitude-by-some-amount-of-meters <ide> public void convertCoordRange() { <ide> //Position, decimal degrees <ide> double lat = y;
Java
apache-2.0
7cb4c3c6d5a3ea6789b756aff6615392bca6b28e
0
natabeck/cloud-slang,CloudSlang/cloud-slang,CloudSlang/cloud-slang,CloudSlang/cloud-slang,narry/cloud-slang,shajyhia/score-language,narry/cloud-slang,jrosadohp/cloud-slang,shajyhia/score-language,CloudSlang/cloud-slang,jrosadohp/cloud-slang,natabeck/cloud-slang
/******************************************************************************* * (c) Copyright 2014 Hewlett-Packard Development Company, L.P. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License v2.0 which accompany this distribution. * * The Apache License is available at * http://www.apache.org/licenses/LICENSE-2.0 * *******************************************************************************/ package org.openscore.lang.compiler.scorecompiler; import org.openscore.lang.compiler.SlangTextualKeys; import org.openscore.lang.entities.ForLoopStatement; import org.openscore.lang.entities.ResultNavigation; import org.openscore.lang.entities.ScoreLangConstants; import org.openscore.lang.entities.bindings.Input; import org.openscore.lang.entities.bindings.Output; import org.openscore.lang.entities.bindings.Result; import junit.framework.Assert; import org.openscore.api.ExecutionStep; import org.junit.Before; import org.junit.Test; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; public class ExecutionStepFactoryTest { private ExecutionStepFactory factory; @Before public void init() { factory = new ExecutionStepFactory(); } @Test public void testCreateStartStep() throws Exception { ExecutionStep startStep = factory.createStartStep(1L, new HashMap<String, Serializable>(), new ArrayList<Input>(),"coolStep"); Assert.assertNotNull("step should not be null", startStep); Assert.assertEquals("coolStep",startStep.getActionData().get(ScoreLangConstants.NODE_NAME_KEY)); } @Test public void testCreateStartStepPutInputsUnderTheRightKey() throws Exception { ArrayList<Input> execInputs = new ArrayList<>(); ExecutionStep startStep = factory.createStartStep(1L, new HashMap<String, Serializable>(), execInputs,""); Assert.assertNotNull("inputs key is null", startStep.getActionData().get(ScoreLangConstants.EXECUTABLE_INPUTS_KEY)); Assert.assertSame("inputs are not set under their key", execInputs, startStep.getActionData().get(ScoreLangConstants.EXECUTABLE_INPUTS_KEY)); } @Test public void testCreateStartStepPutForUnderTheRightKey() throws Exception { ForLoopStatement statement = new ForLoopStatement("1", "2"); HashMap<String, Serializable> preTaskData = new HashMap<>(); preTaskData.put(SlangTextualKeys.FOR_KEY, statement); ExecutionStep startStep = factory.createBeginTaskStep(1L, new ArrayList<Input>(), preTaskData, "", ""); ForLoopStatement actualStatement = (ForLoopStatement) startStep.getActionData() .get(ScoreLangConstants.LOOP_KEY); Assert.assertNotNull("for key is null", actualStatement); Assert.assertSame("inputs are not set under their key", statement, actualStatement); } @Test public void testCreateFinishTakStep(){ ExecutionStep finishTaskStep = factory.createFinishTaskStep( 1L, new HashMap<String, Serializable>(), new HashMap<String, ResultNavigation>(), "taskName"); Assert.assertTrue(finishTaskStep.getActionData().containsKey(ScoreLangConstants.PREVIOUS_STEP_ID_KEY)); Assert.assertTrue(finishTaskStep.getActionData().containsKey(ScoreLangConstants.BREAK_LOOP_KEY)); } @Test(expected = IllegalArgumentException.class) public void testCreateStartStepWithNullData() throws Exception { factory.createStartStep(1L, null, new ArrayList<Input>(),""); } @Test(expected = IllegalArgumentException.class) public void testCreateStartStepWithNullInputs() throws Exception { factory.createStartStep(1L, new HashMap<String, Serializable>(), null,""); } @Test (expected = RuntimeException.class) public void testCreateActionStepWithEmptyData() throws Exception { factory.createActionStep(1L, new HashMap<String, Serializable>()); } @Test public void testCreateJavaActionStep() throws Exception { HashMap<String, Serializable> actionRawData = new HashMap<>(); HashMap<String, String> javaActionData = new HashMap<>(); javaActionData.put("key", "value"); actionRawData.put(SlangTextualKeys.JAVA_ACTION, javaActionData); ExecutionStep actionStep = factory.createActionStep(1L, actionRawData); Assert.assertNotNull("step should not be null", actionStep); Assert.assertEquals(actionStep.getActionData().get("key"), "value"); } @Test public void testCreatePythonActionStep() throws Exception { HashMap<String, Serializable> actionRawData = new HashMap<>(); actionRawData.put(ScoreLangConstants.PYTHON_SCRIPT_KEY, "print 'Hi there'"); ExecutionStep actionStep = factory.createActionStep(1L, actionRawData); Assert.assertNotNull("step should not be null", actionStep); Assert.assertEquals(actionStep.getActionData().get(ScoreLangConstants.PYTHON_SCRIPT_KEY), "print 'Hi there'"); } @Test(expected = IllegalArgumentException.class) public void testCreateActionStepWithNullData() throws Exception { factory.createActionStep(1L, null); } @Test public void testCreateEndStep() throws Exception { ExecutionStep endStep = factory.createEndStep(1L, new HashMap<String, Serializable>(), new ArrayList<Output>(), new ArrayList<Result>(),""); Assert.assertNotNull("step should not be null", endStep); } @Test public void testCreateEndStepPutOutputsUnderTheRightKey() throws Exception { ArrayList<Output> outputs = new ArrayList<>(); ExecutionStep endStep = factory.createEndStep(1L, new HashMap<String, Serializable>(), outputs, new ArrayList<Result>(),""); Assert.assertNotNull("outputs key is null", endStep.getActionData().get(ScoreLangConstants.EXECUTABLE_OUTPUTS_KEY)); Assert.assertSame("outputs are not set under their key", outputs, endStep.getActionData().get(ScoreLangConstants.EXECUTABLE_OUTPUTS_KEY)); } @Test public void testCreateEndStepPutResultsUnderTheRightKey() throws Exception { ArrayList<Result> results = new ArrayList<>(); ExecutionStep endStep = factory.createEndStep(1L, new HashMap<String, Serializable>(), new ArrayList<Output>(), results,""); Assert.assertNotNull("results key is null", endStep.getActionData().get(ScoreLangConstants.EXECUTABLE_RESULTS_KEY)); Assert.assertSame("results are not set under their key", results, endStep.getActionData().get(ScoreLangConstants.EXECUTABLE_RESULTS_KEY)); } @Test(expected = IllegalArgumentException.class) public void testCreateEndStepWithNullData() throws Exception { factory.createEndStep(1L, null, new ArrayList<Output>(), new ArrayList<Result>(),""); } @Test(expected = IllegalArgumentException.class) public void testCreateEndStepWithNullOutputs() throws Exception { factory.createEndStep(1L, new HashMap<String, Serializable>(), null, new ArrayList<Result>(),""); } @Test(expected = IllegalArgumentException.class) public void testCreateEndStepWithNullResults() throws Exception { factory.createEndStep(1L, new HashMap<String, Serializable>(), new ArrayList<Output>(), null,""); } @Test public void testStepName() throws Exception { ArrayList<Result> results = new ArrayList<>(); ExecutionStep endStep = factory.createEndStep(1L, new HashMap<String, Serializable>(), new ArrayList<Output>(), results,"stepX"); Assert.assertNotNull("results key is null", endStep.getActionData().get(ScoreLangConstants.NODE_NAME_KEY)); Assert.assertEquals("stepX", endStep.getActionData().get(ScoreLangConstants.NODE_NAME_KEY)); } }
score-lang-compiler/src/test/java/org/openscore/lang/compiler/scorecompiler/ExecutionStepFactoryTest.java
/******************************************************************************* * (c) Copyright 2014 Hewlett-Packard Development Company, L.P. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License v2.0 which accompany this distribution. * * The Apache License is available at * http://www.apache.org/licenses/LICENSE-2.0 * *******************************************************************************/ package org.openscore.lang.compiler.scorecompiler; import org.openscore.lang.compiler.SlangTextualKeys; import org.openscore.lang.entities.ForLoopStatement; import org.openscore.lang.entities.ResultNavigation; import org.openscore.lang.entities.ScoreLangConstants; import org.openscore.lang.entities.bindings.Input; import org.openscore.lang.entities.bindings.Output; import org.openscore.lang.entities.bindings.Result; import junit.framework.Assert; import org.openscore.api.ExecutionStep; import org.junit.Before; import org.junit.Test; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; public class ExecutionStepFactoryTest { private ExecutionStepFactory factory; @Before public void init() { factory = new ExecutionStepFactory(); } @Test public void testCreateStartStep() throws Exception { ExecutionStep startStep = factory.createStartStep(1L, new HashMap<String, Serializable>(), new ArrayList<Input>(),"coolStep"); Assert.assertNotNull("step should not be null", startStep); Assert.assertEquals("coolStep",startStep.getActionData().get(ScoreLangConstants.NODE_NAME_KEY)); } @Test public void testCreateStartStepPutInputsUnderTheRightKey() throws Exception { ArrayList<Input> execInputs = new ArrayList<>(); ExecutionStep startStep = factory.createStartStep(1L, new HashMap<String, Serializable>(), execInputs,""); Assert.assertNotNull("inputs key is null", startStep.getActionData().get(ScoreLangConstants.EXECUTABLE_INPUTS_KEY)); Assert.assertSame("inputs are not set under their key", execInputs, startStep.getActionData().get(ScoreLangConstants.EXECUTABLE_INPUTS_KEY)); } @Test public void testCreateStartStepPutForUnderTheRightKey() throws Exception { ForLoopStatement statement = new ForLoopStatement("1", "2"); HashMap<String, Serializable> preTaskData = new HashMap<>(); preTaskData.put(SlangTextualKeys.FOR_KEY, statement); ExecutionStep startStep = factory.createBeginTaskStep(1L, preTaskData, "", ""); ForLoopStatement actualStatement = (ForLoopStatement) startStep.getActionData() .get(ScoreLangConstants.LOOP_KEY); Assert.assertNotNull("for key is null", actualStatement); Assert.assertSame("inputs are not set under their key", statement, actualStatement); } @Test public void testCreateFinishTakStep(){ ExecutionStep finishTaskStep = factory.createFinishTaskStep( 1L, new HashMap<String, Serializable>(), new HashMap<String, ResultNavigation>(), "taskName"); Assert.assertTrue(finishTaskStep.getActionData().containsKey(ScoreLangConstants.PREVIOUS_STEP_ID_KEY)); Assert.assertTrue(finishTaskStep.getActionData().containsKey(ScoreLangConstants.BREAK_LOOP_KEY)); } @Test(expected = IllegalArgumentException.class) public void testCreateStartStepWithNullData() throws Exception { factory.createStartStep(1L, null, new ArrayList<Input>(),""); } @Test(expected = IllegalArgumentException.class) public void testCreateStartStepWithNullInputs() throws Exception { factory.createStartStep(1L, new HashMap<String, Serializable>(), null,""); } @Test (expected = RuntimeException.class) public void testCreateActionStepWithEmptyData() throws Exception { factory.createActionStep(1L, new HashMap<String, Serializable>()); } @Test public void testCreateJavaActionStep() throws Exception { HashMap<String, Serializable> actionRawData = new HashMap<>(); HashMap<String, String> javaActionData = new HashMap<>(); javaActionData.put("key", "value"); actionRawData.put(SlangTextualKeys.JAVA_ACTION, javaActionData); ExecutionStep actionStep = factory.createActionStep(1L, actionRawData); Assert.assertNotNull("step should not be null", actionStep); Assert.assertEquals(actionStep.getActionData().get("key"), "value"); } @Test public void testCreatePythonActionStep() throws Exception { HashMap<String, Serializable> actionRawData = new HashMap<>(); actionRawData.put(ScoreLangConstants.PYTHON_SCRIPT_KEY, "print 'Hi there'"); ExecutionStep actionStep = factory.createActionStep(1L, actionRawData); Assert.assertNotNull("step should not be null", actionStep); Assert.assertEquals(actionStep.getActionData().get(ScoreLangConstants.PYTHON_SCRIPT_KEY), "print 'Hi there'"); } @Test(expected = IllegalArgumentException.class) public void testCreateActionStepWithNullData() throws Exception { factory.createActionStep(1L, null); } @Test public void testCreateEndStep() throws Exception { ExecutionStep endStep = factory.createEndStep(1L, new HashMap<String, Serializable>(), new ArrayList<Output>(), new ArrayList<Result>(),""); Assert.assertNotNull("step should not be null", endStep); } @Test public void testCreateEndStepPutOutputsUnderTheRightKey() throws Exception { ArrayList<Output> outputs = new ArrayList<>(); ExecutionStep endStep = factory.createEndStep(1L, new HashMap<String, Serializable>(), outputs, new ArrayList<Result>(),""); Assert.assertNotNull("outputs key is null", endStep.getActionData().get(ScoreLangConstants.EXECUTABLE_OUTPUTS_KEY)); Assert.assertSame("outputs are not set under their key", outputs, endStep.getActionData().get(ScoreLangConstants.EXECUTABLE_OUTPUTS_KEY)); } @Test public void testCreateEndStepPutResultsUnderTheRightKey() throws Exception { ArrayList<Result> results = new ArrayList<>(); ExecutionStep endStep = factory.createEndStep(1L, new HashMap<String, Serializable>(), new ArrayList<Output>(), results,""); Assert.assertNotNull("results key is null", endStep.getActionData().get(ScoreLangConstants.EXECUTABLE_RESULTS_KEY)); Assert.assertSame("results are not set under their key", results, endStep.getActionData().get(ScoreLangConstants.EXECUTABLE_RESULTS_KEY)); } @Test(expected = IllegalArgumentException.class) public void testCreateEndStepWithNullData() throws Exception { factory.createEndStep(1L, null, new ArrayList<Output>(), new ArrayList<Result>(),""); } @Test(expected = IllegalArgumentException.class) public void testCreateEndStepWithNullOutputs() throws Exception { factory.createEndStep(1L, new HashMap<String, Serializable>(), null, new ArrayList<Result>(),""); } @Test(expected = IllegalArgumentException.class) public void testCreateEndStepWithNullResults() throws Exception { factory.createEndStep(1L, new HashMap<String, Serializable>(), new ArrayList<Output>(), null,""); } @Test public void testStepName() throws Exception { ArrayList<Result> results = new ArrayList<>(); ExecutionStep endStep = factory.createEndStep(1L, new HashMap<String, Serializable>(), new ArrayList<Output>(), results,"stepX"); Assert.assertNotNull("results key is null", endStep.getActionData().get(ScoreLangConstants.NODE_NAME_KEY)); Assert.assertEquals("stepX", endStep.getActionData().get(ScoreLangConstants.NODE_NAME_KEY)); } }
update test Signed-off-by: Bonczidai Levente <[email protected]>
score-lang-compiler/src/test/java/org/openscore/lang/compiler/scorecompiler/ExecutionStepFactoryTest.java
update test
<ide><path>core-lang-compiler/src/test/java/org/openscore/lang/compiler/scorecompiler/ExecutionStepFactoryTest.java <ide> ForLoopStatement statement = new ForLoopStatement("1", "2"); <ide> HashMap<String, Serializable> preTaskData = new HashMap<>(); <ide> preTaskData.put(SlangTextualKeys.FOR_KEY, statement); <del> ExecutionStep startStep = factory.createBeginTaskStep(1L, preTaskData, "", ""); <add> ExecutionStep startStep = factory.createBeginTaskStep(1L, new ArrayList<Input>(), preTaskData, "", ""); <ide> ForLoopStatement actualStatement = (ForLoopStatement) startStep.getActionData() <ide> .get(ScoreLangConstants.LOOP_KEY); <ide> Assert.assertNotNull("for key is null", actualStatement);