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
3497540f288793af07367064fc6fea141c1a1ae0
0
nodeca/pica,nodeca/pica,nodeca/pica
// Algorythm should not change. Use fixtures to check. // 'use strict'; const fs = require('fs'); const path = require('path'); const pica = require('../'); const pixelmatch = require('pixelmatch'); const ppm = require('./ppm'); const FIXTURES_DIRECTORY = path.join(__dirname, 'fixtures'); const OUTPUT_DIRECTORY = path.join(__dirname, '..'); describe('Fixture resize', function () { it('.resizeCanvas() should be correct for the given fixture', function () { const Canvas = require('canvas'); const Image = Canvas.Image; // // Shim browser method // global.document = global.document || {}; global.document.createElement = global.document.createElement || function (name) { if (name === 'canvas') return new Canvas(); throw new Error('createElement(' + name + ') not shimmed'); }; this.timeout(3000); let srcImage = new Image(); srcImage.src = fs.readFileSync(path.join(FIXTURES_DIRECTORY, 'original.jpg')); let srcCanvas = new Canvas(); srcCanvas.width = srcImage.width; srcCanvas.height = srcImage.height; let srcCtx = srcCanvas.getContext('2d'); srcCtx.drawImage(srcImage, 0, 0); let fixtureImage = new Image(); fixtureImage.src = fs.readFileSync(path.join(FIXTURES_DIRECTORY, 'resized.png')); let fixtureCanvas = new Canvas(); fixtureCanvas.width = fixtureImage.width; fixtureCanvas.height = fixtureImage.height; let fixtureCtx = fixtureCanvas.getContext('2d'); fixtureCtx.drawImage(fixtureImage, 0, 0); let fixtureImageData = fixtureCtx.getImageData(0, 0, fixtureCanvas.width, fixtureCanvas.height); let destCanvas = new Canvas(); destCanvas.width = fixtureImage.width; destCanvas.height = fixtureImage.height; let destCtx = destCanvas.getContext('2d'); let diffCanvas = new Canvas(); diffCanvas.width = fixtureImage.width; diffCanvas.height = fixtureImage.height; let diffCtx = diffCanvas.getContext('2d'); let diffImageData = diffCtx.createImageData(diffCanvas.width, diffCanvas.height); return pica({ features: [ 'js' ] }) .resize(srcCanvas, destCanvas, { quality: 3, unsharpAmount: 0 }) .then(() => { let destImageData = destCtx.getImageData(0, 0, destCanvas.width, destCanvas.height); let numDiffPixels = pixelmatch( destImageData.data, fixtureImageData.data, diffImageData.data, fixtureCanvas.width, fixtureCanvas.height, { threshold: 0, includeAA: true } ); if (numDiffPixels > 0) { diffCtx.putImageData(diffImageData, 0, 0); diffCanvas .pngStream() .pipe(fs.createWriteStream(path.join(OUTPUT_DIRECTORY, 'fixture-test-diff.png'))); destCanvas .pngStream() .pipe(fs.createWriteStream(path.join(OUTPUT_DIRECTORY, 'fixture-test-output.png'))); fixtureCanvas .pngStream() .pipe(fs.createWriteStream(path.join(OUTPUT_DIRECTORY, 'fixture-test-expected.png'))); throw new Error(`Images mismatch in ${numDiffPixels} pixels`); } }); }); it('.resizeBuffer() should be correct for the given fixture', function () { let src = ppm.decode(fs.readFileSync(path.join(FIXTURES_DIRECTORY, 'original.ppm'))); let fixture = ppm.decode(fs.readFileSync(path.join(FIXTURES_DIRECTORY, 'resized.ppm'))); let dest = new Uint8Array(fixture.buffer.length); let diff = new Uint8Array(fixture.buffer.length); return pica({ features: [ 'js' ] }) .resizeBuffer({ src: src.buffer, width: src.width, height: src.height, dest: dest, toWidth: fixture.width, toHeight: fixture.height }) .then(() => { let numDiffPixels = pixelmatch( dest, fixture.buffer, diff, fixture.width, fixture.height, { threshold: 0, includeAA: true } ); if (numDiffPixels > 0) { fs.writeFileSync( path.join(OUTPUT_DIRECTORY, 'fixture-test-diff.ppm'), Buffer.from(ppm.encode(diff, fixture.width, fixture.height)) ); fs.writeFileSync( path.join(OUTPUT_DIRECTORY, 'fixture-test-output.ppm'), Buffer.from(ppm.encode(dest, fixture.width, fixture.height)) ); fs.writeFileSync( path.join(OUTPUT_DIRECTORY, 'fixture-test-expected.ppm'), Buffer.from(ppm.encode(fixture.buffer, fixture.width, fixture.height)) ); throw new Error(`Images mismatch in ${numDiffPixels} pixels`); } }); }); });
test/fixture_resize.js
// Algorythm should not change. Use fixtures to check. // 'use strict'; const Canvas = require('canvas'); const Image = Canvas.Image; const fs = require('fs'); const path = require('path'); const pica = require('../'); const pixelmatch = require('pixelmatch'); const ppm = require('./ppm'); const FIXTURES_DIRECTORY = path.join(__dirname, 'fixtures'); const OUTPUT_DIRECTORY = path.join(__dirname, '..'); // // Shim browser method // global.document = global.document || {}; global.document.createElement = global.document.createElement || function (name) { if (name === 'canvas') return new Canvas(); throw new Error('createElement(' + name + ') not shimmed'); }; describe('Fixture resize', function () { it('.resizeCanvas() should be correct for the given fixture', function () { this.timeout(3000); let srcImage = new Image(); srcImage.src = fs.readFileSync(path.join(FIXTURES_DIRECTORY, 'original.jpg')); let srcCanvas = new Canvas(); srcCanvas.width = srcImage.width; srcCanvas.height = srcImage.height; let srcCtx = srcCanvas.getContext('2d'); srcCtx.drawImage(srcImage, 0, 0); let fixtureImage = new Image(); fixtureImage.src = fs.readFileSync(path.join(FIXTURES_DIRECTORY, 'resized.png')); let fixtureCanvas = new Canvas(); fixtureCanvas.width = fixtureImage.width; fixtureCanvas.height = fixtureImage.height; let fixtureCtx = fixtureCanvas.getContext('2d'); fixtureCtx.drawImage(fixtureImage, 0, 0); let fixtureImageData = fixtureCtx.getImageData(0, 0, fixtureCanvas.width, fixtureCanvas.height); let destCanvas = new Canvas(); destCanvas.width = fixtureImage.width; destCanvas.height = fixtureImage.height; let destCtx = destCanvas.getContext('2d'); let diffCanvas = new Canvas(); diffCanvas.width = fixtureImage.width; diffCanvas.height = fixtureImage.height; let diffCtx = diffCanvas.getContext('2d'); let diffImageData = diffCtx.createImageData(diffCanvas.width, diffCanvas.height); return pica({ features: [ 'js' ] }) .resize(srcCanvas, destCanvas, { quality: 3, unsharpAmount: 0 }) .then(() => { let destImageData = destCtx.getImageData(0, 0, destCanvas.width, destCanvas.height); let numDiffPixels = pixelmatch( destImageData.data, fixtureImageData.data, diffImageData.data, fixtureCanvas.width, fixtureCanvas.height, { threshold: 0, includeAA: true } ); if (numDiffPixels > 0) { diffCtx.putImageData(diffImageData, 0, 0); diffCanvas .pngStream() .pipe(fs.createWriteStream(path.join(OUTPUT_DIRECTORY, 'fixture-test-diff.png'))); destCanvas .pngStream() .pipe(fs.createWriteStream(path.join(OUTPUT_DIRECTORY, 'fixture-test-output.png'))); fixtureCanvas .pngStream() .pipe(fs.createWriteStream(path.join(OUTPUT_DIRECTORY, 'fixture-test-expected.png'))); throw new Error(`Images mismatch in ${numDiffPixels} pixels`); } }); }); it('.resizeBuffer() should be correct for the given fixture', function () { let src = ppm.decode(fs.readFileSync(path.join(FIXTURES_DIRECTORY, 'original.ppm'))); let fixture = ppm.decode(fs.readFileSync(path.join(FIXTURES_DIRECTORY, 'resized.ppm'))); let dest = new Uint8Array(fixture.buffer.length); let diff = new Uint8Array(fixture.buffer.length); return pica({ features: [ 'js' ] }) .resizeBuffer({ src: src.buffer, width: src.width, height: src.height, dest: dest, toWidth: fixture.width, toHeight: fixture.height }) .then(() => { let numDiffPixels = pixelmatch( dest, fixture.buffer, diff, fixture.width, fixture.height, { threshold: 0, includeAA: true } ); if (numDiffPixels > 0) { fs.writeFileSync( path.join(OUTPUT_DIRECTORY, 'fixture-test-diff.ppm'), Buffer.from(ppm.encode(diff, fixture.width, fixture.height)) ); fs.writeFileSync( path.join(OUTPUT_DIRECTORY, 'fixture-test-output.ppm'), Buffer.from(ppm.encode(dest, fixture.width, fixture.height)) ); fs.writeFileSync( path.join(OUTPUT_DIRECTORY, 'fixture-test-expected.ppm'), Buffer.from(ppm.encode(fixture.buffer, fixture.width, fixture.height)) ); throw new Error(`Images mismatch in ${numDiffPixels} pixels`); } }); }); });
Make node_canvas use more local
test/fixture_resize.js
Make node_canvas use more local
<ide><path>est/fixture_resize.js <ide> // <ide> 'use strict'; <ide> <del>const Canvas = require('canvas'); <del>const Image = Canvas.Image; <ide> const fs = require('fs'); <ide> const path = require('path'); <ide> const pica = require('../'); <ide> const FIXTURES_DIRECTORY = path.join(__dirname, 'fixtures'); <ide> const OUTPUT_DIRECTORY = path.join(__dirname, '..'); <ide> <del>// <del>// Shim browser method <del>// <del>global.document = global.document || {}; <del>global.document.createElement = global.document.createElement || function (name) { <del> if (name === 'canvas') return new Canvas(); <del> throw new Error('createElement(' + name + ') not shimmed'); <del>}; <del> <ide> <ide> describe('Fixture resize', function () { <ide> <ide> it('.resizeCanvas() should be correct for the given fixture', function () { <add> const Canvas = require('canvas'); <add> const Image = Canvas.Image; <add> // <add> // Shim browser method <add> // <add> global.document = global.document || {}; <add> global.document.createElement = global.document.createElement || function (name) { <add> if (name === 'canvas') return new Canvas(); <add> throw new Error('createElement(' + name + ') not shimmed'); <add> }; <add> <add> <ide> this.timeout(3000); <ide> <ide> let srcImage = new Image();
JavaScript
apache-2.0
d2f3f2488a82811a50fa4f118772bf2be5697fa8
0
bslatkin/8-bits,bslatkin/8-bits,bslatkin/8-bits,bslatkin/8-bits
// Copyright 2012 Brett Slatkin // // 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 Common utility functions. */ goog.provide('bits.util'); /** * Pattern used to match links. * @type {string} * @private * @const */ bits.util.LINK_PATTERN_ = '(http(s?):\\/\\/[^ \'"\\)\\(]+)'; /** * Regular expression used to match links. * @type {RegExp} * @private * @const */ bits.util.LINK_MATCH_RE_ = new RegExp('^' + bits.util.LINK_PATTERN_ + '$'); /** * Regular expression used to replace links. * @type {RegExp} * @private * @const */ bits.util.LINK_SUB_RE_ = new RegExp(bits.util.LINK_PATTERN_, 'g'); /** * Determines if the given string contains only a link. * @param {string} text Text that is a link * @return {boolean} True if the string is a link, false otherwise. */ bits.util.matchLink = function(text) { return text.match(bits.util.LINK_MATCH_RE_); }; /** * Replaces the links in the given text with a substitution string. * @param {string} text Text that may contain links. * @param {string} sub What to use as a replacement. May use '$1' to refer * to the link that was matched. * @return {string} The rewritten string. */ bits.util.rewriteLink = function(text, sub) { if (!text) { return text; } // TODO: Support obvious links that start with www or have 'w.xyz/' in them. return text.replace(bits.util.LINK_SUB_RE_, sub); };
frontend/js/bits/util.js
// Copyright 2012 Brett Slatkin // // 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 Common utility functions. */ goog.provide('bits.util'); /** * Pattern used to match links. * @type {string} * @private * @const */ bits.util.LINK_PATTERN_ = '(http(s?):\\/\\/[^ \'"\\)\\(]+)'; /** * Regular expression used to match links. * @type {RegExp} * @private * @const */ bits.util.LINK_MATCH_RE_ = new RegExp('^' + bits.util.LINK_PATTERN_ + '$'); /** * Regular expression used to replace links. * @type {RegExp} * @private * @const */ bits.util.LINK_SUB_RE_ = new RegExp(bits.util.LINK_PATTERN_, 'g'); /** * Determines if the given string contains only a link. * @param {string} text Text that is a link * @return {boolean} True if the string is a link, false otherwise. */ bits.util.matchLink = function(text) { return text.match(bits.util.LINK_MATCH_RE_); }; /** * Replaces the links in the given text with a substitution string. * @param {string} text Text that may contain links. * @param {string} sub What to use as a replacement. May use '$1' to refer * to the link that was matched. * @return {string} The rewritten string. */ bits.util.rewriteLink = function(text, sub) { // TODO: Support obvious links that start with www or have 'w.xyz/' in them. return text.replace(bits.util.LINK_SUB_RE_, sub); };
fixed issue in replacement
frontend/js/bits/util.js
fixed issue in replacement
<ide><path>rontend/js/bits/util.js <ide> * @return {string} The rewritten string. <ide> */ <ide> bits.util.rewriteLink = function(text, sub) { <add> if (!text) { <add> return text; <add> } <ide> // TODO: Support obvious links that start with www or have 'w.xyz/' in them. <ide> return text.replace(bits.util.LINK_SUB_RE_, sub); <ide> };
JavaScript
agpl-3.0
70e757bf60c3bc5a758de07efe9b4cd958fa61e4
0
tocco/tocco-client,tocco/tocco-client,tocco/tocco-client
import {put, call} from 'redux-saga/effects' import {download, validation} from 'tocco-util' import {v4 as uuid} from 'uuid' import errorLogging from '../../../errorLogging' import rest from '../../../rest' import notification from '../../../notification' export default function* (definition, selection, parent, params) { const runAsync = definition.runInBackgroundTask const invokeFnc = runAsync ? invokeActionAsync : invokeActionSync return yield call(invokeFnc, definition, selection, parent, params) } export function* invokeActionAsync(definition, selection, parent, params) { const response = yield call(rest.requestSaga, definition.endpoint, { method: 'POST', body: { entity: selection.entityName, selection, parent, params: { background: true }, ...params, formProperties: definition.properties }, acceptedErrorCodes: ['VALIDATION_FAILED'], headers: { 'X-Enable-Notifications': true } }) if (response.body && response.body.success === false) { yield put(notification.toaster({ type: 'error', title: 'client.common.unexpectedError', body: response.body.message || 'client.component.actions.errorText' })) } } export function* invokeActionSync(definition, selection, parent, params) { const randomId = uuid() const title = definition.progressMsg || 'client.component.actions.defaultProgressMessage' yield put(notification.blockingInfo(randomId, title)) const response = yield call(invokeRequest, definition, selection, parent, params) yield put(notification.removeBlockingInfo(randomId)) return { ...response, remoteEvents: [ ...(response && response.success ? [{ type: 'entity-update-event', payload: { parent, entities: [{entityName: selection.entityName}] } }] : [] ) ] } } export function* invokeRequest(definition, selection, parent, params) { try { const response = yield call(rest.requestSaga, definition.endpoint, { method: 'POST', body: { entity: selection.entityName, selection, parent, ...params, formProperties: definition.properties }, acceptedErrorCodes: ['VALIDATION_FAILED'] }) if (response.body && response.body.errorCode === 'VALIDATION_FAILED') { yield put( notification.toaster( 'error', 'client.component.actions.validationError', validation.getErrorCompact(response.body.errors), 'exclamation') ) } else if (response.body && response.body.params.downloadUrl) { const fileResponse = yield call(rest.requestBytesSaga, response.body.params.downloadUrl, { method: 'POST', body: { entity: selection.entityName, selection, parent, ...params, formProperties: definition.properties } }) yield call(download.downloadReadableStream, fileResponse.body, response.body.params.filename) } else { const success = response.body.success === true const type = success ? 'success' : 'warning' const title = response.body.message || 'client.component.actions.successDefault' yield put(notification.toaster({type, title})) } return response.body } catch (error) { if (!(error instanceof rest.ClientQuestionCancelledException)) { yield put(errorLogging.logError( 'client.common.unexpectedError', 'client.component.actions.errorText', error )) } } }
packages/app-extensions/src/actions/modules/actionHandlers/simpleAction.js
import {put, call} from 'redux-saga/effects' import {download, validation} from 'tocco-util' import {v4 as uuid} from 'uuid' import errorLogging from '../../../errorLogging' import rest from '../../../rest' import notification from '../../../notification' export default function* (definition, selection, parent, params) { const runAsync = definition.runInBackgroundTask const invokeFnc = runAsync ? invokeActionAsync : invokeActionSync return yield call(invokeFnc, definition, selection, parent, params) } export function* invokeActionAsync(definition, selection, parent, params) { const response = yield call(rest.requestSaga, definition.endpoint, { method: 'POST', body: { entity: selection.entityName, selection, parent, params: { background: true, ...params }, formProperties: definition.properties }, acceptedErrorCodes: ['VALIDATION_FAILED'], headers: { 'X-Enable-Notifications': true } }) if (response.body && response.body.success === false) { yield put(notification.toaster({ type: 'error', title: 'client.common.unexpectedError', body: response.body.message || 'client.component.actions.errorText' })) } } export function* invokeActionSync(definition, selection, parent, params) { const randomId = uuid() const title = definition.progressMsg || 'client.component.actions.defaultProgressMessage' yield put(notification.blockingInfo(randomId, title)) const response = yield call(invokeRequest, definition, selection, parent, params) yield put(notification.removeBlockingInfo(randomId)) return { ...response, remoteEvents: [ ...(response && response.success ? [{ type: 'entity-update-event', payload: { parent, entities: [{entityName: selection.entityName}] } }] : [] ) ] } } export function* invokeRequest(definition, selection, parent, params) { try { const response = yield call(rest.requestSaga, definition.endpoint, { method: 'POST', body: { entity: selection.entityName, selection, parent, ...params, formProperties: definition.properties }, acceptedErrorCodes: ['VALIDATION_FAILED'] }) if (response.body && response.body.errorCode === 'VALIDATION_FAILED') { yield put( notification.toaster( 'error', 'client.component.actions.validationError', validation.getErrorCompact(response.body.errors), 'exclamation') ) } else if (response.body && response.body.params.downloadUrl) { const fileResponse = yield call(rest.requestBytesSaga, response.body.params.downloadUrl, { method: 'POST', body: { entity: selection.entityName, selection, parent, ...params, formProperties: definition.properties } }) yield call(download.downloadReadableStream, fileResponse.body, response.body.params.filename) } else { const success = response.body.success === true const type = success ? 'success' : 'warning' const title = response.body.message || 'client.component.actions.successDefault' yield put(notification.toaster({type, title})) } return response.body } catch (error) { if (!(error instanceof rest.ClientQuestionCancelledException)) { yield put(errorLogging.logError( 'client.common.unexpectedError', 'client.component.actions.errorText', error )) } } }
fix(app-extensions): fix invokeActionAsync send params similarly as in the sync case Refs: TOCDEV-3418
packages/app-extensions/src/actions/modules/actionHandlers/simpleAction.js
fix(app-extensions): fix invokeActionAsync
<ide><path>ackages/app-extensions/src/actions/modules/actionHandlers/simpleAction.js <ide> selection, <ide> parent, <ide> params: { <del> background: true, <del> ...params <add> background: true <ide> }, <add> ...params, <ide> formProperties: definition.properties <ide> }, <ide> acceptedErrorCodes: ['VALIDATION_FAILED'],
Java
apache-2.0
79a9c43fceeea1ccb398c06c5834bc782876fbe5
0
mccraigmccraig/opennlp,mccraigmccraig/opennlp
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreemnets. 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 opennlp.tools.chunker; import opennlp.model.AbstractModel; import opennlp.tools.util.BaseModel; import opennlp.tools.util.InvalidFormatException; /** * The {@link ChunkerModel} is the model used * by a learnable {@link Chunker}. * * @see ChunkerME */ public class ChunkerModel extends BaseModel { private static final String CHUNKER_MODEL_ENTRY_NAME = "chunker.model"; public ChunkerModel(String languageCode, AbstractModel chunkerModel) { super(languageCode); if (chunkerModel == null) throw new IllegalArgumentException("chunkerModel must not be null!"); artifactMap.put(CHUNKER_MODEL_ENTRY_NAME, chunkerModel); } @Override protected void validateArtifactMap() throws InvalidFormatException { super.validateArtifactMap(); if (!(artifactMap.get(CHUNKER_MODEL_ENTRY_NAME) instanceof AbstractModel)) { throw new InvalidFormatException("Token model is incomplete!"); } } public AbstractModel getChunkerModel() { return (AbstractModel) artifactMap.get(CHUNKER_MODEL_ENTRY_NAME); } }
src/java/opennlp/tools/chunker/ChunkerModel.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreemnets. 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 opennlp.tools.chunker; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import opennlp.maxent.io.BinaryGISModelReader; import opennlp.model.AbstractModel; import opennlp.model.MaxentModel; import opennlp.tools.util.InvalidFormatException; import opennlp.tools.util.ModelUtil; /** * The {@link ChunkerModel} is the model used * by a learnable {@link Chunker}. * * @see ChunkerME */ public class ChunkerModel { private static final String CHUNKER_MODEL_ENTRY_NAME = "chunker.bin"; private AbstractModel chunkerModel; public ChunkerModel(AbstractModel chunkerModel) { this.chunkerModel = chunkerModel; } public MaxentModel getMaxentChunkerModel() { return chunkerModel; } /** * . * * After the serialization is finished the provided * {@link OutputStream} is closed. * * @param out * @throws IOException */ public void serialize(OutputStream out) throws IOException { ZipOutputStream zip = new ZipOutputStream(out); zip.putNextEntry(new ZipEntry(CHUNKER_MODEL_ENTRY_NAME)); ModelUtil.writeModel(chunkerModel, zip); zip.closeEntry(); zip.close(); } /** * . * * The {@link InputStream} in remains open after the model is read. * * @param in * @return * @throws IOException * @throws InvalidFormatException */ public static ChunkerModel create(InputStream in) throws IOException, InvalidFormatException { ZipInputStream zip = new ZipInputStream(in); ZipEntry chunkerModelEntry = zip.getNextEntry(); if (chunkerModelEntry == null || !CHUNKER_MODEL_ENTRY_NAME.equals(chunkerModelEntry.getName())) throw new InvalidFormatException("Could not find maxent chunker model!"); AbstractModel chunkerModel = new BinaryGISModelReader( new DataInputStream(zip)).getModel(); return new ChunkerModel(chunkerModel); } }
Chunker now uses BaseModel
src/java/opennlp/tools/chunker/ChunkerModel.java
Chunker now uses BaseModel
<ide><path>rc/java/opennlp/tools/chunker/ChunkerModel.java <ide> <ide> package opennlp.tools.chunker; <ide> <del>import java.io.DataInputStream; <del>import java.io.IOException; <del>import java.io.InputStream; <del>import java.io.OutputStream; <del>import java.util.zip.ZipEntry; <del>import java.util.zip.ZipInputStream; <del>import java.util.zip.ZipOutputStream; <del> <del>import opennlp.maxent.io.BinaryGISModelReader; <ide> import opennlp.model.AbstractModel; <del>import opennlp.model.MaxentModel; <add>import opennlp.tools.util.BaseModel; <ide> import opennlp.tools.util.InvalidFormatException; <del>import opennlp.tools.util.ModelUtil; <ide> <ide> /** <ide> * The {@link ChunkerModel} is the model used <ide> * <ide> * @see ChunkerME <ide> */ <del>public class ChunkerModel { <add>public class ChunkerModel extends BaseModel { <ide> <del> private static final String CHUNKER_MODEL_ENTRY_NAME = "chunker.bin"; <add> private static final String CHUNKER_MODEL_ENTRY_NAME = "chunker.model"; <ide> <del> private AbstractModel chunkerModel; <del> <del> public ChunkerModel(AbstractModel chunkerModel) { <del> this.chunkerModel = chunkerModel; <add> public ChunkerModel(String languageCode, AbstractModel chunkerModel) { <add> <add> super(languageCode); <add> <add> if (chunkerModel == null) <add> throw new IllegalArgumentException("chunkerModel must not be null!"); <add> <add> artifactMap.put(CHUNKER_MODEL_ENTRY_NAME, chunkerModel); <ide> } <ide> <del> public MaxentModel getMaxentChunkerModel() { <del> return chunkerModel; <add> @Override <add> protected void validateArtifactMap() throws InvalidFormatException { <add> super.validateArtifactMap(); <add> <add> if (!(artifactMap.get(CHUNKER_MODEL_ENTRY_NAME) instanceof AbstractModel)) { <add> throw new InvalidFormatException("Token model is incomplete!"); <add> } <ide> } <ide> <del> /** <del> * . <del> * <del> * After the serialization is finished the provided <del> * {@link OutputStream} is closed. <del> * <del> * @param out <del> * @throws IOException <del> */ <del> public void serialize(OutputStream out) throws IOException { <del> ZipOutputStream zip = new ZipOutputStream(out); <del> <del> zip.putNextEntry(new ZipEntry(CHUNKER_MODEL_ENTRY_NAME)); <del> ModelUtil.writeModel(chunkerModel, zip); <del> zip.closeEntry(); <del> <del> zip.close(); <del> } <del> <del> /** <del> * . <del> * <del> * The {@link InputStream} in remains open after the model is read. <del> * <del> * @param in <del> * @return <del> * @throws IOException <del> * @throws InvalidFormatException <del> */ <del> public static ChunkerModel create(InputStream in) throws IOException, InvalidFormatException { <del> ZipInputStream zip = new ZipInputStream(in); <del> <del> ZipEntry chunkerModelEntry = zip.getNextEntry(); <del> <del> if (chunkerModelEntry == null || <del> !CHUNKER_MODEL_ENTRY_NAME.equals(chunkerModelEntry.getName())) <del> throw new InvalidFormatException("Could not find maxent chunker model!"); <del> <del> AbstractModel chunkerModel = new BinaryGISModelReader( <del> new DataInputStream(zip)).getModel(); <del> <del> return new ChunkerModel(chunkerModel); <add> public AbstractModel getChunkerModel() { <add> return (AbstractModel) artifactMap.get(CHUNKER_MODEL_ENTRY_NAME); <ide> } <ide> }
Java
apache-2.0
error: pathspec 'sli/api/src/main/java/org/slc/sli/api/security/context/resolver/TeacherToStudentSchoolAssociation.java' did not match any file(s) known to git
d978312b8b45a59ec9fc3f57198cb22f5133172a
1
inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service
package org.slc.sli.api.security.context.resolver; import java.util.Arrays; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.slc.sli.api.security.context.AssociativeContextHelper; import org.slc.sli.common.constants.EntityNames; import org.slc.sli.common.constants.ResourceNames; import org.slc.sli.domain.Entity; /** * Resolves which StudentParentAssociation a given teacher is allowed to see. */ @Component public class TeacherToStudentSchoolAssociation implements EntityContextResolver { @Autowired private AssociativeContextHelper helper; @Override public boolean canResolve(String fromEntityType, String toEntityType) { return EntityNames.TEACHER.equals(fromEntityType) && EntityNames.STUDENT_SCHOOL_ASSOCIATION.equals(toEntityType); } @Override public List<String> findAccessible(Entity principal) { List<String> studentIds = helper.findAccessible(principal, Arrays.asList( ResourceNames.TEACHER_SECTION_ASSOCIATIONS, ResourceNames.STUDENT_SECTION_ASSOCIATIONS)); return helper.findEntitiesContainingReference(EntityNames.STUDENT_SCHOOL_ASSOCIATION, "studentId", studentIds); } }
sli/api/src/main/java/org/slc/sli/api/security/context/resolver/TeacherToStudentSchoolAssociation.java
Added Teacher StudentSchoolAssoc resolver
sli/api/src/main/java/org/slc/sli/api/security/context/resolver/TeacherToStudentSchoolAssociation.java
Added Teacher StudentSchoolAssoc resolver
<ide><path>li/api/src/main/java/org/slc/sli/api/security/context/resolver/TeacherToStudentSchoolAssociation.java <add>package org.slc.sli.api.security.context.resolver; <add> <add>import java.util.Arrays; <add>import java.util.List; <add> <add>import org.springframework.beans.factory.annotation.Autowired; <add>import org.springframework.stereotype.Component; <add> <add>import org.slc.sli.api.security.context.AssociativeContextHelper; <add>import org.slc.sli.common.constants.EntityNames; <add>import org.slc.sli.common.constants.ResourceNames; <add>import org.slc.sli.domain.Entity; <add> <add>/** <add> * Resolves which StudentParentAssociation a given teacher is allowed to see. <add> */ <add>@Component <add>public class TeacherToStudentSchoolAssociation implements EntityContextResolver { <add> <add> @Autowired <add> private AssociativeContextHelper helper; <add> <add> @Override <add> public boolean canResolve(String fromEntityType, String toEntityType) { <add> return EntityNames.TEACHER.equals(fromEntityType) && EntityNames.STUDENT_SCHOOL_ASSOCIATION.equals(toEntityType); <add> } <add> <add> @Override <add> public List<String> findAccessible(Entity principal) { <add> List<String> studentIds = helper.findAccessible(principal, Arrays.asList( <add> ResourceNames.TEACHER_SECTION_ASSOCIATIONS, ResourceNames.STUDENT_SECTION_ASSOCIATIONS)); <add> <add> return helper.findEntitiesContainingReference(EntityNames.STUDENT_SCHOOL_ASSOCIATION, "studentId", studentIds); <add> } <add> <add>}
Java
apache-2.0
7c0b72432ad6777b91099bfd0ba45a5561131e67
0
Routelandia/routelandia-android,Routelandia/routelandia-android
/* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package edu.pdx.its.portal.routelandia; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.concurrent.ExecutionException; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.Button; import android.widget.NumberPicker; import android.widget.Spinner; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; import com.google.android.gms.maps.model.LatLng; import edu.pdx.its.portal.routelandia.entities.APIException; import edu.pdx.its.portal.routelandia.entities.TrafficStat; public class DatePickUp extends Activity { private static final String TAG = "Activity: DatePickup"; private TextView tvDisplayDay; private TimePicker thisTimePicker; private Button btnDepartureDate; private int hour; private int minute; private int am_pm; protected String dayofweek; static final int TIME_DIALOG_ID = 100; private Spinner weekDaySpinner; public String weekDay;// = "Sunday"; protected LatLng startPoint; protected LatLng endPoint; protected String departureTime; protected ArrayList<TrafficStat> trafficStatList; private int TIME_PICKER_INTERVAL = 15; /** * Perform initialization of all fragments and loaders. * * @param savedInstanceState Bundle from Google SDK */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_date_pick_up); setCurrentTimeOnView(); addListenerOnWeekDaySpinnerSelection(); addListenerOnTime(); if(getIntent().getExtras() != null) { startPoint = new LatLng(getIntent().getExtras().getDouble("lat of first point"), getIntent().getExtras().getDouble("lng of first point")); endPoint = new LatLng(getIntent().getExtras().getDouble("lat of second point"), getIntent().getExtras().getDouble("lng of second point")); } addListenerOnButton(); } private void addListenerOnWeekDaySpinnerSelection() { weekDaySpinner = (Spinner) findViewById(R.id.spinner); DayPickSelectedListener dayPickSelectedListener = new DayPickSelectedListener(); weekDaySpinner.setOnItemSelectedListener(dayPickSelectedListener); //return dayPickSelectedListener.getWeekDay(); } private void addListenerOnTime(){ thisTimePicker = (TimePicker) findViewById(R.id.timePicker); TimePickSelectedListener timePickSelectedListener = new TimePickSelectedListener(); thisTimePicker.setOnTimeChangedListener(timePickSelectedListener); //return timePickSelectedListener.getDepartureTime(); } //Display current time public void setCurrentTimeOnView() { tvDisplayDay = (TextView) findViewById(R.id.tvTime); thisTimePicker = (TimePicker) findViewById(R.id.timePicker); final Calendar c = Calendar.getInstance(); hour = c.get(Calendar.HOUR_OF_DAY); minute = c.get(Calendar.MINUTE); am_pm = c.get(Calendar.AM_PM); dayofweek = getDayOfWeekInStr(c.get(Calendar.DAY_OF_WEEK)); departureTime = (new StringBuilder().append(hour).append(":").append(minute)).toString(); tvDisplayDay.setText( new StringBuilder().append(hour) .append(":").append(minute)); thisTimePicker.setCurrentHour(hour); thisTimePicker.setCurrentMinute(minute); } public String getDayOfWeekInStr(int value) { String day = "Sunday"; switch (value) { case 0: day = "Sunday"; break; case 1: day = "Monday"; break; case 2: day = "Tuesday"; break; case 3: day = "Wednesday"; break; case 4: day = "Thursday"; break; case 5: day = "Friday"; break; case 6: day = "Saturday"; break; } return day; } public void addListenerOnButton() { btnDepartureDate = (Button) findViewById(R.id.btnDepartureDate); btnDepartureDate.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { try { trafficStatList = (ArrayList) TrafficStat.getStatsResultListFor(startPoint, endPoint, departureTime, weekDay); } catch (APIException e) { // TODO: RESTART ACTIVITY AFTER TELLING USER THAT THEY NEED TO DO SOMETHING!! // (Did they pick bad points? Going to have to read the e.getResultWrapper().getParsedResponse() JSON to see...) Intent intent = new Intent(DatePickUp.this,MapsActivity.class); Toast.makeText(DatePickUp.this, "please re pick 2 points", Toast.LENGTH_SHORT).show(); startActivity(intent); } if(trafficStatList == null){ Log.e(TAG, "No results returned from statistics query."); } else{ Intent intent = new Intent(getApplicationContext(),ListStat.class); intent.putParcelableArrayListExtra("travel info", trafficStatList); startActivity(intent); } } }); } private static String pad(int c) { if (c >= 10) return String.valueOf(c); else return "0" + String.valueOf(c); } // for jason use if needed private String getPmAm(int value) { String pmAm = ""; switch (value) { case 1: if (am_pm == 1) { pmAm = "pm"; } break; case 2: if (am_pm == 0) { pmAm = "am"; } break; } return pmAm; } protected class DayPickSelectedListener implements AdapterView.OnItemSelectedListener { //protected int week_day; public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { Toast.makeText(parent.getContext(), "Departure day: " + parent.getItemAtPosition(pos).toString(), Toast.LENGTH_SHORT).show(); String s = parent.getItemAtPosition(pos).toString(); if(s == null){ weekDay = dayofweek; }else { weekDay = s; } // Backend might prefer integer for days //week_day = getDayOfWeekInInt(s); } @Override public void onNothingSelected(AdapterView<?> arg0) { //TODO } public String getWeekDay() { return weekDay; } // Backend might prefer integer for days private int getDayOfWeekInInt(String value) { int day = 0; switch (value) { case "Sunday": day = 0; break; case "Monday": day = 1; break; case "Tuesday": day = 2; break; case "Wednesday": day = 3; break; case "Thursday": day = 4; break; case "Friday": day = 5; break; case "Saturday": day = 6; break; } return day; } } private class TimePickSelectedListener implements TimePicker.OnTimeChangedListener { @Override public void onTimeChanged(TimePicker timePicker, int hourOfDay, int minute) { setTimePickerInterval(timePicker); StringBuilder s = new StringBuilder().append(hourOfDay).append(":").append(minute); departureTime = s.toString(); } @SuppressLint("NewApi") private void setTimePickerInterval(TimePicker timePicker) { try { Class<?> classForid = Class.forName("com.android.internal.R$id"); Field field = classForid.getField("minute"); NumberPicker minutePicker = (NumberPicker) timePicker .findViewById(field.getInt(null)); minutePicker.setMinValue(0); minutePicker.setMaxValue(7); ArrayList<String> displayedValues = new ArrayList<>(); for (int i = 0; i < 60; i += TIME_PICKER_INTERVAL) { displayedValues.add(String.format("%02d", i)); } for (int i = 0; i < 60; i += TIME_PICKER_INTERVAL) { displayedValues.add(String.format("%02d", i)); } minutePicker.setDisplayedValues(displayedValues .toArray(new String[0])); } catch (Exception e) { e.printStackTrace(); } } } }
routelandia/src/main/java/edu/pdx/its/portal/routelandia/DatePickUp.java
/* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package edu.pdx.its.portal.routelandia; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.concurrent.ExecutionException; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.Button; import android.widget.NumberPicker; import android.widget.Spinner; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; import com.google.android.gms.maps.model.LatLng; import edu.pdx.its.portal.routelandia.entities.APIException; import edu.pdx.its.portal.routelandia.entities.TrafficStat; public class DatePickUp extends Activity { private static final String TAG = "Activity: DatePickup"; private TextView tvDisplayDay; private TimePicker thisTimePicker; private Button btnDepartureDate; private int hour; private int minute; private int am_pm; protected String dayofweek; static final int TIME_DIALOG_ID = 100; private Spinner weekDaySpinner; public String weekDay;// = "Sunday"; protected LatLng startPoint; protected LatLng endPoint; protected String departureTime; protected ArrayList<TrafficStat> trafficStatList; private int TIME_PICKER_INTERVAL = 15; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_date_pick_up); setCurrentTimeOnView(); addListenerOnWeekDaySpinnerSelection(); addListenerOnTime(); if(getIntent().getExtras() != null) { startPoint = new LatLng(getIntent().getExtras().getDouble("lat of first point"), getIntent().getExtras().getDouble("lng of first point")); endPoint = new LatLng(getIntent().getExtras().getDouble("lat of second point"), getIntent().getExtras().getDouble("lng of second point")); } addListenerOnButton(); } private void addListenerOnWeekDaySpinnerSelection() { weekDaySpinner = (Spinner) findViewById(R.id.spinner); DayPickSelectedListener dayPickSelectedListener = new DayPickSelectedListener(); weekDaySpinner.setOnItemSelectedListener(dayPickSelectedListener); //return dayPickSelectedListener.getWeekDay(); } private void addListenerOnTime(){ thisTimePicker = (TimePicker) findViewById(R.id.timePicker); TimePickSelectedListener timePickSelectedListener = new TimePickSelectedListener(); thisTimePicker.setOnTimeChangedListener(timePickSelectedListener); //return timePickSelectedListener.getDepartureTime(); } //Display current time public void setCurrentTimeOnView() { tvDisplayDay = (TextView) findViewById(R.id.tvTime); thisTimePicker = (TimePicker) findViewById(R.id.timePicker); final Calendar c = Calendar.getInstance(); hour = c.get(Calendar.HOUR_OF_DAY); minute = c.get(Calendar.MINUTE); am_pm = c.get(Calendar.AM_PM); dayofweek = getDayOfWeekInStr(c.get(Calendar.DAY_OF_WEEK)); departureTime = (new StringBuilder().append(hour).append(":").append(minute)).toString(); tvDisplayDay.setText( new StringBuilder().append(hour) .append(":").append(minute)); thisTimePicker.setCurrentHour(hour); thisTimePicker.setCurrentMinute(minute); } public String getDayOfWeekInStr(int value) { String day = "Sunday"; switch (value) { case 0: day = "Sunday"; break; case 1: day = "Monday"; break; case 2: day = "Tuesday"; break; case 3: day = "Wednesday"; break; case 4: day = "Thursday"; break; case 5: day = "Friday"; break; case 6: day = "Saturday"; break; } return day; } public void addListenerOnButton() { btnDepartureDate = (Button) findViewById(R.id.btnDepartureDate); btnDepartureDate.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { try { trafficStatList = (ArrayList) TrafficStat.getStatsResultListFor(startPoint, endPoint, departureTime, weekDay); } catch (APIException e) { // TODO: RESTART ACTIVITY AFTER TELLING USER THAT THEY NEED TO DO SOMETHING!! // (Did they pick bad points? Going to have to read the e.getResultWrapper().getParsedResponse() JSON to see...) Intent intent = new Intent(DatePickUp.this,MapsActivity.class); Toast.makeText(DatePickUp.this, "please re pick 2 points", Toast.LENGTH_SHORT).show(); startActivity(intent); } if(trafficStatList == null){ Log.e(TAG, "No results returned from statistics query."); } else{ // For now just print them out. // for (int j =0; j < travelingInfoList.size(); j++){ // Log.i(TAG, travelingInfoList.get(j).toString()); // } Intent intent = new Intent(getApplicationContext(),ListStat.class); intent.putParcelableArrayListExtra("travel info", trafficStatList); startActivity(intent); } }); } private static String pad(int c) { if (c >= 10) return String.valueOf(c); else return "0" + String.valueOf(c); } // for jason use if needed private String getPmAm(int value) { String pmAm = ""; switch (value) { case 1: if (am_pm == 1) { pmAm = "pm"; } break; case 2: if (am_pm == 0) { pmAm = "am"; } break; } return pmAm; } protected class DayPickSelectedListener implements AdapterView.OnItemSelectedListener { //protected int week_day; public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { Toast.makeText(parent.getContext(), "Departure day: " + parent.getItemAtPosition(pos).toString(), Toast.LENGTH_SHORT).show(); String s = parent.getItemAtPosition(pos).toString(); if(s == null){ weekDay = dayofweek; }else { weekDay = s; } // Backend might prefer integer for days //week_day = getDayOfWeekInInt(s); } @Override public void onNothingSelected(AdapterView<?> arg0) { //TODO } public String getWeekDay() { return weekDay; } // Backend might prefer integer for days private int getDayOfWeekInInt(String value) { int day = 0; switch (value) { case "Sunday": day = 0; break; case "Monday": day = 1; break; case "Tuesday": day = 2; break; case "Wednesday": day = 3; break; case "Thursday": day = 4; break; case "Friday": day = 5; break; case "Saturday": day = 6; break; } return day; } } private class TimePickSelectedListener implements TimePicker.OnTimeChangedListener { @Override public void onTimeChanged(TimePicker timePicker, int hourOfDay, int minute) { setTimePickerInterval(timePicker); StringBuilder s = new StringBuilder().append(hourOfDay).append(":").append(minute); departureTime = s.toString(); } @SuppressLint("NewApi") private void setTimePickerInterval(TimePicker timePicker) { try { Class<?> classForid = Class.forName("com.android.internal.R$id"); Field field = classForid.getField("minute"); NumberPicker minutePicker = (NumberPicker) timePicker .findViewById(field.getInt(null)); minutePicker.setMinValue(0); minutePicker.setMaxValue(7); ArrayList<String> displayedValues = new ArrayList<>(); for (int i = 0; i < 60; i += TIME_PICKER_INTERVAL) { displayedValues.add(String.format("%02d", i)); } for (int i = 0; i < 60; i += TIME_PICKER_INTERVAL) { displayedValues.add(String.format("%02d", i)); } minutePicker.setDisplayedValues(displayedValues .toArray(new String[0])); } catch (Exception e) { e.printStackTrace(); } } } }
make sure we have data before move to liststats activities
routelandia/src/main/java/edu/pdx/its/portal/routelandia/DatePickUp.java
make sure we have data before move to liststats activities
<ide><path>outelandia/src/main/java/edu/pdx/its/portal/routelandia/DatePickUp.java <ide> protected String departureTime; <ide> protected ArrayList<TrafficStat> trafficStatList; <ide> private int TIME_PICKER_INTERVAL = 15; <add> <add> /** <add> * Perform initialization of all fragments and loaders. <add> * <add> * @param savedInstanceState Bundle from Google SDK <add> */ <ide> @Override <ide> public void onCreate(Bundle savedInstanceState) { <ide> super.onCreate(savedInstanceState); <ide> Log.e(TAG, "No results returned from statistics query."); <ide> } <ide> else{ <del> // For now just print them out. <del> // for (int j =0; j < travelingInfoList.size(); j++){ <del> // Log.i(TAG, travelingInfoList.get(j).toString()); <del> // <del> } <del> <del> Intent intent = new Intent(getApplicationContext(),ListStat.class); <del> intent.putParcelableArrayListExtra("travel info", trafficStatList); <del> startActivity(intent); <add> Intent intent = new Intent(getApplicationContext(),ListStat.class); <add> intent.putParcelableArrayListExtra("travel info", trafficStatList); <add> startActivity(intent); <add> } <ide> } <ide> }); <ide> }
Java
apache-2.0
340f542c466bcc484b217537af55f293dc0da84f
0
opendatakit/androidcommon
androidcommon.test/src/org/opendatakit/common/android/utilities/UrlUtilsTest.java
package org.opendatakit.common.android.utilities; import android.test.AndroidTestCase; public class UrlUtilsTest extends AndroidTestCase { public void testNoHashOrParameters() { String fileName = "this/test/file/path/.html"; this.assertRetrieveFileNameHelper(fileName, fileName); } public void testEmptyString() { this.assertRetrieveFileNameHelper("", ""); } public void testOnlyHash() { String segment = "test/file#foo"; this.assertRetrieveFileNameHelper("test/file", segment); } public void testOnlyQueryParams() { String segment = "pretty/little/liar?foo&bar=3"; this.assertRetrieveFileNameHelper("pretty/little/liar", segment); } public void testHashAndQueryParams() { String segment = "test/test/test.html#foo?bar=3&baz=55"; this.assertRetrieveFileNameHelper("test/test/test.html", segment); } public void testGetIndexOfParamsNoParams() { String segment = "test/test/test.html"; this.assertGetIndexHelper(segment, -1); } public void testGetIndexOfParamsHash() { String segment = "test/test.html#foo"; int expected = 14; this.assertGetIndexHelper(segment, expected); } public void testGetIndexOfQueryHash() { String segment = "this/is/a/file/that/i/like.html?foo=bar"; int expected = 31; this.assertGetIndexHelper(segment, expected); } public void testGetIndexOfBoth() { String segment = "foo/bar.html#foo?bar=baz"; int expected = 12; this.assertGetIndexHelper(segment, expected); } public void testGetParamsNone() { String segment = "this/test/file/path/.html"; this.assertGetParamsHelper(segment, ""); } public void testGetParamsHash() { String segment = "test/file#foo"; this.assertGetParamsHelper(segment, "#foo"); } public void testGetParamsQuery() { String segment = "pretty/little/liar?foo&bar=3"; this.assertGetParamsHelper(segment, "?foo&bar=3"); } public void testGetParamsBoth() { String segment = "test/test/test.html#foo?bar=3&baz=55"; this.assertGetParamsHelper(segment, "#foo?bar=3&baz=55"); } /** * Take start, retrieve the file name, and assert that the result is equal to * expected. * @param expected * @param start */ protected void assertRetrieveFileNameHelper(String expected, String start) { String result = UrlUtils.getFileNameFromUriSegment(start); assertEquals(expected, result); } protected void assertGetIndexHelper(String segment, int expected) { int actual = UrlUtils.getIndexOfParameters(segment); assertEquals(expected, actual); } protected void assertGetParamsHelper(String segment, String expected) { String actual = UrlUtils.getParametersFromSegment(segment); assertEquals(expected, actual); } }
Fix merge mistake
androidcommon.test/src/org/opendatakit/common/android/utilities/UrlUtilsTest.java
Fix merge mistake
<ide><path>ndroidcommon.test/src/org/opendatakit/common/android/utilities/UrlUtilsTest.java <del>package org.opendatakit.common.android.utilities; <del> <del>import android.test.AndroidTestCase; <del> <del>public class UrlUtilsTest extends AndroidTestCase { <del> <del> public void testNoHashOrParameters() { <del> String fileName = "this/test/file/path/.html"; <del> this.assertRetrieveFileNameHelper(fileName, fileName); <del> } <del> <del> public void testEmptyString() { <del> this.assertRetrieveFileNameHelper("", ""); <del> } <del> <del> public void testOnlyHash() { <del> String segment = "test/file#foo"; <del> this.assertRetrieveFileNameHelper("test/file", segment); <del> } <del> <del> public void testOnlyQueryParams() { <del> String segment = "pretty/little/liar?foo&bar=3"; <del> this.assertRetrieveFileNameHelper("pretty/little/liar", segment); <del> } <del> <del> public void testHashAndQueryParams() { <del> String segment = "test/test/test.html#foo?bar=3&baz=55"; <del> this.assertRetrieveFileNameHelper("test/test/test.html", segment); <del> } <del> <del> public void testGetIndexOfParamsNoParams() { <del> String segment = "test/test/test.html"; <del> this.assertGetIndexHelper(segment, -1); <del> } <del> <del> public void testGetIndexOfParamsHash() { <del> String segment = "test/test.html#foo"; <del> int expected = 14; <del> this.assertGetIndexHelper(segment, expected); <del> } <del> <del> public void testGetIndexOfQueryHash() { <del> String segment = "this/is/a/file/that/i/like.html?foo=bar"; <del> int expected = 31; <del> this.assertGetIndexHelper(segment, expected); <del> } <del> <del> public void testGetIndexOfBoth() { <del> String segment = "foo/bar.html#foo?bar=baz"; <del> int expected = 12; <del> this.assertGetIndexHelper(segment, expected); <del> } <del> <del> public void testGetParamsNone() { <del> String segment = "this/test/file/path/.html"; <del> this.assertGetParamsHelper(segment, ""); <del> } <del> <del> public void testGetParamsHash() { <del> String segment = "test/file#foo"; <del> this.assertGetParamsHelper(segment, "#foo"); <del> } <del> <del> public void testGetParamsQuery() { <del> String segment = "pretty/little/liar?foo&bar=3"; <del> this.assertGetParamsHelper(segment, "?foo&bar=3"); <del> } <del> <del> public void testGetParamsBoth() { <del> String segment = "test/test/test.html#foo?bar=3&baz=55"; <del> this.assertGetParamsHelper(segment, "#foo?bar=3&baz=55"); <del> } <del> <del> /** <del> * Take start, retrieve the file name, and assert that the result is equal to <del> * expected. <del> * @param expected <del> * @param start <del> */ <del> protected void assertRetrieveFileNameHelper(String expected, String start) { <del> String result = UrlUtils.getFileNameFromUriSegment(start); <del> assertEquals(expected, result); <del> } <del> <del> protected void assertGetIndexHelper(String segment, int expected) { <del> int actual = UrlUtils.getIndexOfParameters(segment); <del> assertEquals(expected, actual); <del> } <del> <del> protected void assertGetParamsHelper(String segment, String expected) { <del> String actual = UrlUtils.getParametersFromSegment(segment); <del> assertEquals(expected, actual); <del> } <del> <del>}
Java
lgpl-2.1
6b2c9cde140cb57154aefd6a3a74a11b3e855478
0
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
// // $Id: Invoker.java,v 1.12 2003/10/08 04:10:29 mdb Exp $ package com.threerings.presents.util; import java.util.HashMap; import java.util.Iterator; import com.samskivert.util.Histogram; import com.samskivert.util.LoopingThread; import com.samskivert.util.Queue; import com.samskivert.util.StringUtil; import com.threerings.presents.Log; import com.threerings.presents.server.PresentsDObjectMgr; import com.threerings.presents.server.PresentsServer.Reporter; import com.threerings.presents.server.PresentsServer; /** * The invoker is used to invoke self-contained units of code on an * invoking thread. Each invoker is associated with its own thread and * that thread is used to invoke all of the units posted to that invoker * in the order in which they were posted. The invoker also provides a * convenient mechanism for processing the result of an invocation back on * the dobjmgr thread. * * <p> The invoker is a useful tool for services that need to block and * therefore cannot be run on the distributed object thread. For example, * a user of the Presents system might provide an invoker on which to run * database queries. * * <p> Bear in mind that each invoker instance runs units on its own * thread and care must be taken to ensure that code running on separate * invokers properly synchronizes access to shared information. Where * possible, complete isolation of the services provided by a particular * invoker is desirable. */ public class Invoker extends LoopingThread implements Reporter { /** * The unit encapsulates a unit of executable code that will be run on * the invoker thread. It also provides facilities for additional code * to be run on the dobjmgr thread once the primary code has completed * on the invoker thread. */ public static abstract class Unit implements Runnable { /** * This method is called on the invoker thread and should be used * to perform the primary function of the unit. It can return true * to cause the <code>handleResult</code> method to be * subsequently invoked on the dobjmgr thread (generally to allow * the results of the invocation to be acted upon back in the * context of the distributed object world) or false to indicate * that no further processing should be performed. * * <p> Note that an invocation unit can do things like post events * from the invoker thread (which includes modification of * distributed object fields) and need not jump over to the * dobjmgr thread to do so. However, it cannot <em>read</em> * distributed object fields from the invoker thread. Any field * values needed during the course of the invocation should be * provided from the dobjmgr thread at the time that the * invocation unit is created and posted. * * @return true if the <code>handleResult</code> method should be * invoked on the dobjmgr thread, false if not. */ public abstract boolean invoke (); /** * Invocation unit implementations can implement this function to * perform any post-unit-invocation processing back on the dobjmgr * thread. It will be invoked if <code>invoke</code> returns true. */ public void handleResult () { // do nothing by default } // we want to be a runnable to make the dobjmgr happy, but we'd // like for invocation unit implementations to be able to put // their result handling code into an aptly named method public void run () { handleResult(); } } /** * Creates an invoker that will post results to the supplied * distributed object manager. */ public Invoker (PresentsDObjectMgr omgr) { super("presents.Invoker"); _omgr = omgr; if (PERF_TRACK) { PresentsServer.registerReporter(this); } } /** * Posts a unit to this invoker for subsequent invocation on the * invoker's thread. */ public void postUnit (Unit unit) { // simply append it to the queue _queue.append(unit); } // documentation inherited public void iterate () { // pop the next item off of the queue Unit unit = (Unit) _queue.get(); long start; if (PERF_TRACK) { start = System.currentTimeMillis(); _unitsRun++; } try { if (unit.invoke()) { // if it returned true, we post it to the dobjmgr // thread to invoke the result processing _omgr.postUnit(unit); } // track some performance metrics if (PERF_TRACK) { long duration = System.currentTimeMillis() - start; Object key = unit.getClass(); Histogram histo = (Histogram)_tracker.get(key); if (histo == null) { // track in buckets of 50ms up to 500ms _tracker.put(key, histo = new Histogram(0, 50, 10)); } histo.addValue((int)duration); // report long runners if (duration > 500L) { Log.warning("Invoker unit ran for '" + duration + "ms: " + unit + "' (" + key + ")."); } } } catch (Exception e) { Log.warning("Invocation unit failed [unit=" + unit + "]."); Log.logStackTrace(e); } } /** * Will do a sophisticated shutdown of both itself and the DObjectManager * thread. */ public void shutdown () { _queue.append(new ShutdownUnit()); } // documentation inherited from interface public void appendReport (StringBuffer buffer, long now, long sinceLast) { buffer.append("* presents.util.Invoker:\n"); buffer.append("- Units executed: ").append(_unitsRun).append("\n"); _unitsRun = 0; for (Iterator iter = _tracker.keySet().iterator(); iter.hasNext(); ) { Class key = (Class)iter.next(); Histogram histo = (Histogram)_tracker.get(key); buffer.append(" "); buffer.append(StringUtil.shortClassName(key)).append(": "); buffer.append(histo.summarize()).append("\n"); histo.clear(); } } /** * This unit gets posted back and forth between the invoker and DObjectMgr * until both of their queues are empty and they can both be safely * shutdown. */ protected class ShutdownUnit extends Unit { // run on the invoker thread public boolean invoke () { if (checkLoops()) { return false; // if the invoker queue is not empty, we put ourselves back on it } else if (_queue.hasElements()) { _loopCount++; postUnit(this); return false; } else { // the invoker is empty, let's go over to the omgr _loopCount = 0; _passCount++; return true; } } // run on the dobj thread public void handleResult () { if (checkLoops()) { return; // if the queue isn't empty, re-post } else if (!_omgr.queueIsEmpty()) { _loopCount++; _omgr.postUnit(this); // if the invoker still has stuff and we're still under the pass // limit, go ahead and pass it back to the invoker } else if (_queue.hasElements() && (_passCount < MAX_PASSES)) { // pass the buck back to the invoker _loopCount = 0; postUnit(this); } else { // otherwise end it, and complain if we're ending it // because of passes if (_passCount >= MAX_PASSES) { Log.warning("Shutdown Unit passed 50 times without " + "finishing, shutting down harshly."); } doShutdown(); } } /** * Check to make sure we haven't looped too many times. */ protected boolean checkLoops () { if (_loopCount > MAX_LOOPS) { Log.warning("Shutdown Unit looped on one thread 100 times " + "without finishing, shutting down harshly."); doShutdown(); return true; } return false; } /** * Do the actual shutdown. */ protected void doShutdown () { _omgr.harshShutdown(); // end the dobj thread // end the invoker thread postUnit(new Unit() { public boolean invoke () { _running = false; return false; } }); } /** The number of times we've been passed to the object manager. */ protected int _passCount = 0; /** How many times we've looped on the thread we're currently on. */ protected int _loopCount = 0; /** The maximum number of passes we allow before just ending things. */ protected static final int MAX_PASSES = 50; /** The maximum number of loops we allow before just ending things. */ protected static final int MAX_LOOPS = 100; } /** The invoker's queue of units to be executed. */ protected Queue _queue = new Queue(); /** The object manager with which we're working. */ protected PresentsDObjectMgr _omgr; /** Tracks the counts of invocations by unit's class. */ protected HashMap _tracker = new HashMap(); /** The total number of invoker units run since the last report. */ protected int _unitsRun; /** Whether or not to track invoker unit performance. */ protected static final boolean PERF_TRACK = true; }
src/java/com/threerings/presents/util/Invoker.java
// // $Id: Invoker.java,v 1.11 2003/09/24 17:10:49 mdb Exp $ package com.threerings.presents.util; import java.util.HashMap; import java.util.Iterator; import com.samskivert.util.Histogram; import com.samskivert.util.LoopingThread; import com.samskivert.util.Queue; import com.samskivert.util.StringUtil; import com.threerings.presents.Log; import com.threerings.presents.server.PresentsDObjectMgr; import com.threerings.presents.server.PresentsServer.Reporter; import com.threerings.presents.server.PresentsServer; /** * The invoker is used to invoke self-contained units of code on an * invoking thread. Each invoker is associated with its own thread and * that thread is used to invoke all of the units posted to that invoker * in the order in which they were posted. The invoker also provides a * convenient mechanism for processing the result of an invocation back on * the dobjmgr thread. * * <p> The invoker is a useful tool for services that need to block and * therefore cannot be run on the distributed object thread. For example, * a user of the Presents system might provide an invoker on which to run * database queries. * * <p> Bear in mind that each invoker instance runs units on its own * thread and care must be taken to ensure that code running on separate * invokers properly synchronizes access to shared information. Where * possible, complete isolation of the services provided by a particular * invoker is desirable. */ public class Invoker extends LoopingThread implements Reporter { /** * The unit encapsulates a unit of executable code that will be run on * the invoker thread. It also provides facilities for additional code * to be run on the dobjmgr thread once the primary code has completed * on the invoker thread. */ public static abstract class Unit implements Runnable { /** * This method is called on the invoker thread and should be used * to perform the primary function of the unit. It can return true * to cause the <code>handleResult</code> method to be * subsequently invoked on the dobjmgr thread (generally to allow * the results of the invocation to be acted upon back in the * context of the distributed object world) or false to indicate * that no further processing should be performed. * * <p> Note that an invocation unit can do things like post events * from the invoker thread (which includes modification of * distributed object fields) and need not jump over to the * dobjmgr thread to do so. However, it cannot <em>read</em> * distributed object fields from the invoker thread. Any field * values needed during the course of the invocation should be * provided from the dobjmgr thread at the time that the * invocation unit is created and posted. * * @return true if the <code>handleResult</code> method should be * invoked on the dobjmgr thread, false if not. */ public abstract boolean invoke (); /** * Invocation unit implementations can implement this function to * perform any post-unit-invocation processing back on the dobjmgr * thread. It will be invoked if <code>invoke</code> returns true. */ public void handleResult () { // do nothing by default } // we want to be a runnable to make the dobjmgr happy, but we'd // like for invocation unit implementations to be able to put // their result handling code into an aptly named method public void run () { handleResult(); } } /** * Creates an invoker that will post results to the supplied * distributed object manager. */ public Invoker (PresentsDObjectMgr omgr) { super("presents.Invoker"); _omgr = omgr; if (PERF_TRACK) { PresentsServer.registerReporter(this); } } /** * Posts a unit to this invoker for subsequent invocation on the * invoker's thread. */ public void postUnit (Unit unit) { // simply append it to the queue _queue.append(unit); } // documentation inherited public void iterate () { // pop the next item off of the queue Unit unit = (Unit) _queue.get(); long start; if (PERF_TRACK) { start = System.currentTimeMillis(); _unitsRun++; } try { if (unit.invoke()) { // if it returned true, we post it to the dobjmgr // thread to invoke the result processing _omgr.postUnit(unit); } // track some performance metrics if (PERF_TRACK) { long duration = System.currentTimeMillis() - start; Object key = unit.getClass(); Histogram histo = (Histogram)_tracker.get(key); if (histo == null) { // track in buckets of 50ms up to 500ms _tracker.put(key, histo = new Histogram(0, 50, 10)); } histo.addValue((int)duration); // report long runners if (duration > 500L) { Log.warning("Invoker unit ran long [class=" + key + ", duration=" + duration + "]."); } } } catch (Exception e) { Log.warning("Invocation unit failed [unit=" + unit + "]."); Log.logStackTrace(e); } } /** * Will do a sophisticated shutdown of both itself and the DObjectManager * thread. */ public void shutdown () { _queue.append(new ShutdownUnit()); } // documentation inherited from interface public void appendReport (StringBuffer buffer, long now, long sinceLast) { buffer.append("* presents.util.Invoker:\n"); buffer.append("- Units executed: ").append(_unitsRun).append("\n"); _unitsRun = 0; for (Iterator iter = _tracker.keySet().iterator(); iter.hasNext(); ) { Class key = (Class)iter.next(); Histogram histo = (Histogram)_tracker.get(key); buffer.append(" "); buffer.append(StringUtil.shortClassName(key)).append(": "); buffer.append(histo.summarize()).append("\n"); histo.clear(); } } /** * This unit gets posted back and forth between the invoker and DObjectMgr * until both of their queues are empty and they can both be safely * shutdown. */ protected class ShutdownUnit extends Unit { // run on the invoker thread public boolean invoke () { if (checkLoops()) { return false; // if the invoker queue is not empty, we put ourselves back on it } else if (_queue.hasElements()) { _loopCount++; postUnit(this); return false; } else { // the invoker is empty, let's go over to the omgr _loopCount = 0; _passCount++; return true; } } // run on the dobj thread public void handleResult () { if (checkLoops()) { return; // if the queue isn't empty, re-post } else if (!_omgr.queueIsEmpty()) { _loopCount++; _omgr.postUnit(this); // if the invoker still has stuff and we're still under the pass // limit, go ahead and pass it back to the invoker } else if (_queue.hasElements() && (_passCount < MAX_PASSES)) { // pass the buck back to the invoker _loopCount = 0; postUnit(this); } else { // otherwise end it, and complain if we're ending it // because of passes if (_passCount >= MAX_PASSES) { Log.warning("Shutdown Unit passed 50 times without " + "finishing, shutting down harshly."); } doShutdown(); } } /** * Check to make sure we haven't looped too many times. */ protected boolean checkLoops () { if (_loopCount > MAX_LOOPS) { Log.warning("Shutdown Unit looped on one thread 100 times " + "without finishing, shutting down harshly."); doShutdown(); return true; } return false; } /** * Do the actual shutdown. */ protected void doShutdown () { _omgr.harshShutdown(); // end the dobj thread // end the invoker thread postUnit(new Unit() { public boolean invoke () { _running = false; return false; } }); } /** The number of times we've been passed to the object manager. */ protected int _passCount = 0; /** How many times we've looped on the thread we're currently on. */ protected int _loopCount = 0; /** The maximum number of passes we allow before just ending things. */ protected static final int MAX_PASSES = 50; /** The maximum number of loops we allow before just ending things. */ protected static final int MAX_LOOPS = 100; } /** The invoker's queue of units to be executed. */ protected Queue _queue = new Queue(); /** The object manager with which we're working. */ protected PresentsDObjectMgr _omgr; /** Tracks the counts of invocations by unit's class. */ protected HashMap _tracker = new HashMap(); /** The total number of invoker units run since the last report. */ protected int _unitsRun; /** Whether or not to track invoker unit performance. */ protected static final boolean PERF_TRACK = true; }
Report the toString() output on long runners. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@2822 542714f4-19e9-0310-aa3c-eee0fc999fb1
src/java/com/threerings/presents/util/Invoker.java
Report the toString() output on long runners.
<ide><path>rc/java/com/threerings/presents/util/Invoker.java <ide> // <del>// $Id: Invoker.java,v 1.11 2003/09/24 17:10:49 mdb Exp $ <add>// $Id: Invoker.java,v 1.12 2003/10/08 04:10:29 mdb Exp $ <ide> <ide> package com.threerings.presents.util; <ide> <ide> <ide> // report long runners <ide> if (duration > 500L) { <del> Log.warning("Invoker unit ran long [class=" + key + <del> ", duration=" + duration + "]."); <add> Log.warning("Invoker unit ran for '" + duration + "ms: " + <add> unit + "' (" + key + ")."); <ide> } <ide> } <ide>
Java
apache-2.0
89fcc56ef1ce4395c87a8f8ec2f5a6ac99738884
0
KDanila/KDanila
package ru.job4j.tracker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.*; import java.util.ArrayList; import java.util.List; /** * Tracker класс. * * @author Kuzmin Danila (mailto:[email protected]) * @version $Id$ * @since 0.1 */ public class Tracker { //todo reading from file; String url = "jdbc:postgresql://localhost:5432/umlclient"; String username = "postgres"; String password = "6799963"; /** * Connection. toDB. */ Connection conn = null; /** * Logger. */ private static final Logger log = LoggerFactory.getLogger(SQLException.class); /** * Указатель ячейки для новой заявки. */ private int position = 0; /** * Name of database. */ private final String dbName = "trackerdb"; /** * Name of table. */ private final String dbTableName = "tracker"; /** * Connecting to DB method. */ void connectingToDB() { try { conn = DriverManager.getConnection(url, username, password); } catch (SQLException e) { log.error(e.getMessage(), e); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { log.error(e.getMessage(), e); } } } if (!checkDB()) { createDB(); } if (!checkTableInDB()) { createTableInDB(); } } /** * Метод public Item add(Item) добавляет заявку, переданную в аргументах в массив заявок this.items. * * @param item - заявка. * @return item - заявка. */ public void add(Item item) { try (PreparedStatement ps = conn.prepareStatement("insert into tracker values(?,?,?,?)")) { ps.setInt(1, item.getId()); ps.setString(2, item.getName()); ps.setString(3, item.getDescription()); ps.setTimestamp(4, item.getCreateTime()); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } /** * Method update(Item). * * @param item - текущая заявка. */ public void update(Item item) { try (PreparedStatement ps = conn.prepareStatement("" + "update tracker set name=?,description =?,expired_date =? where id = ?")) { ps.setString(1, item.getName()); ps.setString(2, item.getDescription()); ps.setTimestamp(3, item.getCreateTime()); ps.setInt(4, item.getId()); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } /** * Метод public void delete(Item) должен удалить ячейку из базы. * * @param item - заявка. */ public void delete(Item item) { try (PreparedStatement ps = conn.prepareStatement("delete from tracker where id=?")) { ps.setInt(1, item.getId()); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } /** * findAll() method. * <p> * return Item[] from database. * * @return массив item без пустых элементов. */ public Item[] findAll() { List<Item> toReturn = new ArrayList<Item>(); try (PreparedStatement ps = conn.prepareStatement("SELECT*FROM tracker")) { ResultSet rs = ps.executeQuery(); while (rs.next()) { toReturn.add(new Item(rs.getInt("id"), rs.getString("name"), rs.getString("description"), rs.getTimestamp("expired_date"))); } } catch (SQLException e) { e.printStackTrace(); } return toReturn.toArray(new Item[toReturn.size()]); } /** * findByName method. * * @param key - имя заявки * @return item - заявка */ public Item findByName(String key) { Item toReturn = null; try (PreparedStatement ps = conn.prepareStatement("SELECT*FROM tracker")) { ResultSet rs = ps.executeQuery(); while (rs.next()) { String name = rs.getString("name"); if (name.equals(key)) { toReturn = new Item(rs.getInt("id"), name, rs.getString("description"), rs.getTimestamp("expired_date")); } } } catch (SQLException e) { e.printStackTrace(); } return toReturn; } /** * findById method. * * @param id - требуемый id. * @return item - искомая завяка. */ public Item findById(int id) { Item toReturn = null; try (PreparedStatement ps = conn.prepareStatement("SELECT*FROM tracker")) { ResultSet rs = ps.executeQuery(); while (rs.next()) { int idTemp = rs.getInt("id"); if (idTemp == id) { toReturn = new Item(idTemp, rs.getString("name"), rs.getString("description"), rs.getTimestamp("expired_date")); } } } catch (SQLException e) { e.printStackTrace(); } return toReturn; } /** * createTableInDB method. * <p> * Creating table in database, if it's doesn't exist. */ private void createTableInDB() { Statement st = null; try { st = conn.createStatement(); //todo создать таблицу в ту же базу данных. st.executeQuery("CREATE TABLE tracker ( id integer primary key," + "name varchar(15), " + "description varchar(50)," + "expired_date timestamp)"); st.close(); } catch (SQLException e) { log.error(e.getMessage(), e); } } /** * checkTableInDB method. * <p> * checking table in database. * * @return true if db existing. */ private boolean checkTableInDB() { boolean isExist = false; try { Statement st = conn.createStatement(); ResultSet rs = st.executeQuery("SELECT * FROM pg_catalog.pg_tables;"); while (rs.next()) { if (rs.getString("tablename").equals(dbTableName)) { return true; } } rs.close(); st.close(); } catch (SQLException e) { log.error(e.getMessage(), e); } return isExist; } /** * creatDB method. */ private void createDB() { Statement st = null; try { st = conn.createStatement(); st.executeQuery("CREATE DATABASE trackerdb"); st.close(); } catch (SQLException e) { e.printStackTrace(); } } /** * checkDB method. * * @return true if DB is existing. */ private boolean checkDB() { boolean isExist = false; try { Statement st = conn.createStatement(); ResultSet rs = st.executeQuery("SELECT datname FROM pg_database"); while (rs.next()) { if (rs.getString("datname").equals(dbName)) { return true; } } rs.close(); st.close(); } catch (SQLException e) { log.error(e.getMessage(), e); } return isExist; } }
chapter_006/src/main/java/ru/job4j/tracker/Tracker.java
package ru.job4j.tracker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.*; import java.util.ArrayList; import java.util.List; /** * Tracker класс. * * @author Kuzmin Danila (mailto:[email protected]) * @version $Id$ * @since 0.1 */ public class Tracker { //todo reading from file; String url = "jdbc:postgresql://localhost:5432/umlclient"; String username = "postgres"; String password = "6799963"; /** * Connection. toDB. */ Connection conn = null; /** * Logger. */ private static final Logger log = LoggerFactory.getLogger(SQLException.class); /** * Указатель ячейки для новой заявки. */ private int position = 0; /** * Name of database. */ private final String dbName = "trackerdb"; /** * Name of table. */ private final String dbTableName = "tracker"; /** * Connecting to DB method. */ void connectingToDB() { try { conn = DriverManager.getConnection(url, username, password); } catch (SQLException e) { log.error(e.getMessage(), e); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { log.error(e.getMessage(), e); } } } if (!checkDB()) { createDB(); } if (!checkTableInDB()) { createTableInDB(); } } /** * Метод public Item add(Item) добавляет заявку, переданную в аргументах в массив заявок this.items. * * @param item - заявка. * @return item - заявка. */ public void add(Item item) { try (PreparedStatement ps = conn.prepareStatement("insert into tracker values(?,?,?,?)")) { ps.setInt(1, item.getId()); ps.setString(2, item.getName()); ps.setString(3, item.getDescription()); ps.setTimestamp(4, item.getCreateTime()); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } /** * Method update(Item). * * @param item - текущая заявка. */ public void update(Item item) { try (PreparedStatement ps = conn.prepareStatement("" + "update tracker set name=?,description =?,expired_date =? where id = ?")) { ps.setString(1, item.getName()); ps.setString(2, item.getDescription()); ps.setTimestamp(3, item.getCreateTime()); ps.setInt(4, item.getId()); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } /** * Метод public void delete(Item) должен удалить ячейку из базы. * * @param item - заявка. */ public void delete(Item item) { try (PreparedStatement ps = conn.prepareStatement("delete from tracker where id=?")) { ps.setInt(1, item.getId()); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } /** * findAll() method. * <p> * return Item[] from database. * * @return массив item без пустых элементов. */ public Item[] findAll() { List<Item> toReturn = new ArrayList<Item>(); try (PreparedStatement ps = conn.prepareStatement("SELECT*FROM tracker")) { ResultSet rs = ps.executeQuery(); while (rs.next()) { toReturn.add(new Item(rs.getInt("id"), rs.getString("name"), rs.getString("description"), rs.getTimestamp("expired_date"))); } } catch (SQLException e) { e.printStackTrace(); } return toReturn.toArray(new Item[toReturn.size()]); } /** * findByName method. * * @param key - имя заявки * @return item - заявка */ public Item findByName(String key) { Item toReturn = null; try (PreparedStatement ps = conn.prepareStatement("SELECT*FROM tracker")) { ResultSet rs = ps.executeQuery(); while (rs.next()) { String name = rs.getString("name"); if (name.equals(key)) { toReturn = new Item(rs.getInt("id"), name, rs.getString("description"), rs.getTimestamp("expired_date")); } } } catch (SQLException e) { e.printStackTrace(); } return toReturn; } /** * findById method. * * @param id - требуемый id. * @return item - искомая завяка. */ public Item findById(int id) { Item toReturn = null; try (PreparedStatement ps = conn.prepareStatement("SELECT*FROM tracker")) { ResultSet rs = ps.executeQuery(); while (rs.next()) { int idTemp = rs.getInt("id"); if (idTemp == id) { toReturn = new Item(idTemp, rs.getString("name"), rs.getString("description"), rs.getTimestamp("expired_date")); } } } catch (SQLException e) { e.printStackTrace(); } return toReturn; } /** * createTableInDB method. * <p> * Creating table in database, if it's doesn't exist. */ private void createTableInDB() { try { conn = DriverManager.getConnection(url, username, password); } catch (SQLException e) { log.error(e.getMessage(), e); } Statement st = null; try { st = conn.createStatement(); //todo создать таблицу в ту же базу данных. st.executeQuery("CREATE TABLE tracker ( id integer primary key," + "name varchar(15), " + "description varchar(50)," + "expired_date timestamp)"); st.close(); } catch (SQLException e) { log.error(e.getMessage(), e); } } /** * checkTableInDB method. * * checking table in database. * * @return true if db existing. */ private boolean checkTableInDB() { boolean isExist = false; try { conn = DriverManager.getConnection(url, username, password); Statement st = conn.createStatement(); ResultSet rs = st.executeQuery("SELECT * FROM pg_catalog.pg_tables;"); while (rs.next()) { if (rs.getString("tablename").equals(dbTableName)) { return true; } } rs.close(); st.close(); } catch (SQLException e) { log.error(e.getMessage(), e); } return isExist; } /** * creatDB method. * */ private void createDB() { try { conn = DriverManager.getConnection(url, username, password); } catch (SQLException e) { log.error(e.getMessage(), e); } Statement st = null; try { st = conn.createStatement(); st.executeQuery("CREATE DATABASE trackerdb"); st.close(); } catch (SQLException e) { e.printStackTrace(); } } /** * checkDB method. * * @return true if DB is existing. */ private boolean checkDB() { boolean isExist = false; try { conn = DriverManager.getConnection(url, username, password); Statement st = conn.createStatement(); ResultSet rs = st.executeQuery("SELECT datname FROM pg_database"); while (rs.next()) { if (rs.getString("datname").equals(dbName)) { return true; } } rs.close(); st.close(); } catch (SQLException e) { log.error(e.getMessage(), e); } return isExist; } }
SQL Tracker v 1.1
chapter_006/src/main/java/ru/job4j/tracker/Tracker.java
SQL Tracker v 1.1
<ide><path>hapter_006/src/main/java/ru/job4j/tracker/Tracker.java <ide> * Creating table in database, if it's doesn't exist. <ide> */ <ide> private void createTableInDB() { <del> try { <del> conn = DriverManager.getConnection(url, username, password); <del> } catch (SQLException e) { <del> log.error(e.getMessage(), e); <del> } <ide> Statement st = null; <ide> try { <ide> st = conn.createStatement(); <ide> <ide> /** <ide> * checkTableInDB method. <del> * <add> * <p> <ide> * checking table in database. <ide> * <ide> * @return true if db existing. <ide> private boolean checkTableInDB() { <ide> boolean isExist = false; <ide> try { <del> conn = DriverManager.getConnection(url, username, password); <ide> Statement st = conn.createStatement(); <ide> ResultSet rs = st.executeQuery("SELECT * FROM pg_catalog.pg_tables;"); <ide> while (rs.next()) { <ide> <ide> /** <ide> * creatDB method. <del> * <ide> */ <ide> private void createDB() { <del> try { <del> conn = DriverManager.getConnection(url, username, password); <del> } catch (SQLException e) { <del> log.error(e.getMessage(), e); <del> } <ide> Statement st = null; <ide> try { <ide> st = conn.createStatement(); <ide> private boolean checkDB() { <ide> boolean isExist = false; <ide> try { <del> conn = DriverManager.getConnection(url, username, password); <ide> Statement st = conn.createStatement(); <ide> ResultSet rs = st.executeQuery("SELECT datname FROM pg_database"); <ide> while (rs.next()) {
JavaScript
apache-2.0
8240b17a67c1bd7f2d0b7d9d89f1fee9fe1aae89
0
ManageIQ/manageiq-ui-classic,ManageIQ/manageiq-ui-classic,ManageIQ/manageiq-ui-classic,ManageIQ/manageiq-ui-classic
import React from 'react'; import PropTypes from 'prop-types'; import { Grid, Row, Col } from 'patternfly-react'; import TagModifier from '../InnerComponents/TagModifier'; import TagView from '../InnerComponents/TagView'; import CategoryModifier from '../InnerComponents/CategoryModifier'; import ValueModifier from '../InnerComponents/ValueModifier'; import TaggingPropTypes from '../TaggingPropTypes'; class Tagging extends React.Component { onTagValueChange = (selectedTagValue) => { const action = { tagCategory: this.props.selectedTagCategory, tagValue: selectedTagValue, }; if (this.props.options && this.props.options.onlySingleTag) { this.props.onSingleTagValueChange(action); } else if (this.findSelectedTag(this.props.selectedTagCategory).singleValue) { this.props.onTagValueChange(action, this.props.options); } else { this.props.onTagMultiValueChange(action, this.props.options); } }; onTagCategoryChange = selectedTagCategory => this.props.onTagCategoryChange(selectedTagCategory); onTagDeleteClick = (tagCategory, tagValue) => { this.props.onTagDeleteClick({ tagCategory, tagValue }, this.props.options); }; getvalues = () => (this.findSelectedTag(this.props.selectedTagCategory) && this.findSelectedTag(this.props.selectedTagCategory).values) || []; findSelectedTag = (selectedTagCategory = { id: undefined }) => this.props.tags.find(tag => tag.id === selectedTagCategory.id); isSelectedCategoryMultiValue = selectedTagCategory => (this.findSelectedTag(selectedTagCategory.id) && this.findSelectedTag(selectedTagCategory.id).singleValue) === true; tagCategories = this.props.tags.map(tag => ({ description: tag.description, id: tag.id, singleValue: tag.singleValue, })) || []; render() { return ( <Grid> <Row> <Col xs={12} md={8} lg={6}> <TagModifier hideHeader={this.props.options && this.props.options.hideHeaders}> <CategoryModifier selectedTagCategory={this.props.selectedTagCategory} onTagCategoryChange={this.props.onTagCategoryChange} tagCategories={this.tagCategories} /> <ValueModifier onTagValueChange={this.onTagValueChange} selectedTagValue={this.props.selectedTagValue} multiValue={this.isSelectedCategoryMultiValue(this.props.selectedTagCategory)} values={this.getvalues()} /> </TagModifier> </Col> <Col xs={12} md={4} lg={6}> <TagView hideHeader={this.props.options && this.props.options.hideHeaders} assignedTags={this.props.assignedTags} onTagDeleteClick={this.onTagDeleteClick} /> </Col> </Row> </Grid> ); } } Tagging.propTypes = { selectedTagCategory: TaggingPropTypes.category, selectedTagValue: TaggingPropTypes.value, tags: TaggingPropTypes.tags, assignedTags: TaggingPropTypes.tags, onTagDeleteClick: PropTypes.func.isRequired, onTagCategoryChange: PropTypes.func.isRequired, onTagValueChange: PropTypes.func.isRequired, onTagMultiValueChange: PropTypes.func.isRequired, onSingleTagValueChange: PropTypes.func.isRequired, options: PropTypes.shape({ onlySingleTag: PropTypes.bool, hideHeaders: PropTypes.bool, }), }; Tagging.defaultProps = { options: { onlySingleTag: false, hideHeaders: false, }, }; export default Tagging;
app/javascript/tagging/components/Tagging/Tagging.js
import React from 'react'; import PropTypes from 'prop-types'; import { Grid, Row, Col } from 'patternfly-react'; import TagModifier from '../InnerComponents/TagModifier'; import TagView from '../InnerComponents/TagView'; import CategoryModifier from '../InnerComponents/CategoryModifier'; import ValueModifier from '../InnerComponents/ValueModifier'; import TaggingPropTypes from '../TaggingPropTypes'; class Tagging extends React.Component { onTagValueChange = (selectedTagValue) => { const action = { tagCategory: this.props.selectedTagCategory, tagValue: selectedTagValue, }; // Single Tag Only if (this.props.options && this.props.options.onlySingleTag) { this.props.onSingleTagValueChange(action); return; } if (this.findSelectedTag(this.props.selectedTagCategory).singleValue) { this.props.onTagValueChange(action, this.props.options); } else { this.props.onTagMultiValueChange(action, this.props.options); } }; onTagCategoryChange = selectedTagCategory => this.props.onTagCategoryChange(selectedTagCategory); onTagDeleteClick = (tagCategory, tagValue) => { this.props.onTagDeleteClick({ tagCategory, tagValue }, this.props.options); }; getvalues = () => (this.findSelectedTag(this.props.selectedTagCategory) && this.findSelectedTag(this.props.selectedTagCategory).values) || []; findSelectedTag = (selectedTagCategory = { id: undefined }) => this.props.tags.find(tag => tag.id === selectedTagCategory.id); isSelectedCategoryMultiValue = selectedTagCategory => (this.findSelectedTag(selectedTagCategory.id) && this.findSelectedTag(selectedTagCategory.id).singleValue) === true; tagCategories = this.props.tags.map(tag => ({ description: tag.description, id: tag.id, singleValue: tag.singleValue, })) || []; render() { return ( <Grid> <Row> <Col xs={12} md={8} lg={6}> <TagModifier hideHeader={this.props.options && this.props.options.hideHeaders}> <CategoryModifier selectedTagCategory={this.props.selectedTagCategory} onTagCategoryChange={this.props.onTagCategoryChange} tagCategories={this.tagCategories} /> <ValueModifier onTagValueChange={this.onTagValueChange} selectedTagValue={this.props.selectedTagValue} multiValue={this.isSelectedCategoryMultiValue(this.props.selectedTagCategory)} values={this.getvalues()} /> </TagModifier> </Col> <Col xs={12} md={4} lg={6}> <TagView hideHeader={this.props.options && this.props.options.hideHeaders} assignedTags={this.props.assignedTags} onTagDeleteClick={this.onTagDeleteClick} /> </Col> </Row> </Grid> ); } } Tagging.propTypes = { selectedTagCategory: TaggingPropTypes.category, selectedTagValue: TaggingPropTypes.value, tags: TaggingPropTypes.tags, assignedTags: TaggingPropTypes.tags, onTagDeleteClick: PropTypes.func.isRequired, onTagCategoryChange: PropTypes.func.isRequired, onTagValueChange: PropTypes.func.isRequired, onTagMultiValueChange: PropTypes.func.isRequired, onSingleTagValueChange: PropTypes.func.isRequired, options: PropTypes.shape({ onlySingleTag: PropTypes.bool, hideHeaders: PropTypes.bool, }), }; Tagging.defaultProps = { options: { onlySingleTag: false, hideHeaders: false, }, }; export default Tagging;
Changed return to else if
app/javascript/tagging/components/Tagging/Tagging.js
Changed return to else if
<ide><path>pp/javascript/tagging/components/Tagging/Tagging.js <ide> tagValue: selectedTagValue, <ide> }; <ide> <del> // Single Tag Only <ide> if (this.props.options && this.props.options.onlySingleTag) { <ide> this.props.onSingleTagValueChange(action); <del> return; <del> } <del> <del> if (this.findSelectedTag(this.props.selectedTagCategory).singleValue) { <add> } else if (this.findSelectedTag(this.props.selectedTagCategory).singleValue) { <ide> this.props.onTagValueChange(action, this.props.options); <ide> } else { <ide> this.props.onTagMultiValueChange(action, this.props.options);
Java
mit
600abdf7e445c3a9a97510a9596b6adeddd5b611
0
budowski/iNaturalistAndroid,inaturalist/iNaturalistAndroid,inaturalist/iNaturalistAndroid,inaturalist/iNaturalistAndroid,inaturalist/iNaturalistAndroid
// BEGIN GENERATED BY /Users/kueda/projects/eclipse/workspace/iNaturalist/rails2android.rb AT Mon Jan 09 13:07:06 -0500 2012 package org.inaturalist.android; import java.io.Serializable; import java.sql.Timestamp; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.ContentUris; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.provider.BaseColumns; import android.util.Log; import android.view.View; public class Observation implements BaseColumns, Serializable { public Integer _id; public Timestamp _created_at; public Timestamp _synced_at; public Timestamp _updated_at; public Timestamp created_at; public String description; public String geoprivacy; public Integer iconic_taxon_id; public String iconic_taxon_name; public Integer id; public Boolean id_please; public Double latitude; public Double longitude; public Timestamp observed_on; public String observed_on_string; public Boolean out_of_range; public Boolean captive; public String place_guess; public Integer positional_accuracy; public String positioning_device; public String positioning_method; public Double private_latitude; public Double private_longitude; public Integer private_positional_accuracy; public String quality_grade; public String species_guess; public Integer taxon_id; public Timestamp time_observed_at; public Timestamp updated_at; public String user_agent; public Integer user_id; public String user_login; public Integer comments_count; public Integer identifications_count; public Integer last_comments_count; public Integer last_identifications_count; public Boolean is_deleted; public String preferred_common_name; public SerializableJSONArray comments; public SerializableJSONArray identifications; public SerializableJSONArray favorites; public List<ObservationPhoto> photos; public Timestamp _created_at_was; public Timestamp _synced_at_was; public Timestamp _updated_at_was; public Timestamp created_at_was; public String description_was; public String geoprivacy_was; public Integer iconic_taxon_id_was; public String iconic_taxon_name_was; public Integer id_was; public Boolean id_please_was; public Double latitude_was; public Double longitude_was; public Timestamp observed_on_was; public String observed_on_string_was; public Boolean out_of_range_was; public Boolean captive_was; public String place_guess_was; public Integer positional_accuracy_was; public String positioning_device_was; public String positioning_method_was; public Double private_latitude_was; public Double private_longitude_was; public Integer private_positional_accuracy_was; public String quality_grade_was; public String species_guess_was; public Integer taxon_id_was; public Timestamp time_observed_at_was; public Timestamp updated_at_was; public String user_agent_was; public Integer user_id_was; public String user_login_was; public Boolean is_deleted_was; public SerializableJSONArray projects; public String uuid; public static final String TAG = "Observation"; public static final String TABLE_NAME = "observations"; public static final int OBSERVATIONS_URI_CODE = 1279; public static final int OBSERVATION_ID_URI_CODE = 1164; public static HashMap<String, String> PROJECTION_MAP; public static final String AUTHORITY = "org.inaturalist.android.observation"; public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/observations"); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.google.observation"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.google.observation"; public static final String DEFAULT_SORT_ORDER = "CASE WHEN id IS NULL THEN _created_at ELSE created_at END DESC"; public static final String SYNC_ORDER = "_created_at ASC"; public static final String _CREATED_AT = "_created_at"; public static final String _SYNCED_AT = "_synced_at"; public static final String _UPDATED_AT = "_updated_at"; public static final String CREATED_AT = "created_at"; public static final String DESCRIPTION = "description"; public static final String GEOPRIVACY = "geoprivacy"; public static final String ICONIC_TAXON_ID = "iconic_taxon_id"; public static final String ICONIC_TAXON_NAME = "iconic_taxon_name"; public static final String ID = "id"; public static final String ID_PLEASE = "id_please"; public static final String LATITUDE = "latitude"; public static final String LONGITUDE = "longitude"; public static final String OBSERVED_ON = "observed_on"; public static final String OBSERVED_ON_STRING = "observed_on_string"; public static final String OUT_OF_RANGE = "out_of_range"; public static final String CAPTIVE = "captive"; public static final String PLACE_GUESS = "place_guess"; public static final String POSITIONAL_ACCURACY = "positional_accuracy"; public static final String POSITIONING_DEVICE = "positioning_device"; public static final String POSITIONING_METHOD = "positioning_method"; public static final String PRIVATE_LATITUDE = "private_latitude"; public static final String PRIVATE_LONGITUDE = "private_longitude"; public static final String PRIVATE_POSITIONAL_ACCURACY = "private_positional_accuracy"; public static final String QUALITY_GRADE = "quality_grade"; public static final String SPECIES_GUESS = "species_guess"; public static final String PREFERRED_COMMON_NAME = "preferred_common_name"; public static final String TAXON_ID = "taxon_id"; public static final String TIME_OBSERVED_AT = "time_observed_at"; public static final String UPDATED_AT = "updated_at"; public static final String USER_AGENT = "user_agent"; public static final String USER_ID = "user_id"; public static final String USER_LOGIN = "user_login"; public static final String COMMENTS_COUNT = "comments_count"; public static final String IDENTIFICATIONS_COUNT = "identifications_count"; public static final String LAST_COMMENTS_COUNT = "last_comments_count"; public static final String LAST_IDENTIFICATIONS_COUNT = "last_identifications_count"; public static final String IS_DELETED = "is_deleted"; public static final String UUID = "uuid"; public static final String[] PROJECTION = new String[] { Observation._ID, Observation._CREATED_AT, Observation._SYNCED_AT, Observation._UPDATED_AT, Observation.CREATED_AT, Observation.DESCRIPTION, Observation.GEOPRIVACY, Observation.ICONIC_TAXON_ID, Observation.ICONIC_TAXON_NAME, Observation.ID, Observation.ID_PLEASE, Observation.LATITUDE, Observation.LONGITUDE, Observation.OBSERVED_ON, Observation.OBSERVED_ON_STRING, Observation.OUT_OF_RANGE, Observation.CAPTIVE, Observation.PLACE_GUESS, Observation.POSITIONAL_ACCURACY, Observation.POSITIONING_DEVICE, Observation.POSITIONING_METHOD, Observation.PRIVATE_LATITUDE, Observation.PRIVATE_LONGITUDE, Observation.PRIVATE_POSITIONAL_ACCURACY, Observation.QUALITY_GRADE, Observation.SPECIES_GUESS, Observation.PREFERRED_COMMON_NAME, Observation.TAXON_ID, Observation.TIME_OBSERVED_AT, Observation.UPDATED_AT, Observation.USER_AGENT, Observation.USER_ID, Observation.USER_LOGIN, Observation.IDENTIFICATIONS_COUNT, Observation.COMMENTS_COUNT, Observation.LAST_COMMENTS_COUNT, Observation.LAST_IDENTIFICATIONS_COUNT, Observation.IS_DELETED, Observation.UUID, }; static { PROJECTION_MAP = new HashMap<String, String>(); PROJECTION_MAP.put(Observation._ID, Observation._ID); PROJECTION_MAP.put(Observation._CREATED_AT, Observation._CREATED_AT); PROJECTION_MAP.put(Observation._SYNCED_AT, Observation._SYNCED_AT); PROJECTION_MAP.put(Observation._UPDATED_AT, Observation._UPDATED_AT); PROJECTION_MAP.put(Observation.CREATED_AT, Observation.CREATED_AT); PROJECTION_MAP.put(Observation.DESCRIPTION, Observation.DESCRIPTION); PROJECTION_MAP.put(Observation.GEOPRIVACY, Observation.GEOPRIVACY); PROJECTION_MAP.put(Observation.ICONIC_TAXON_ID, Observation.ICONIC_TAXON_ID); PROJECTION_MAP.put(Observation.ICONIC_TAXON_NAME, Observation.ICONIC_TAXON_NAME); PROJECTION_MAP.put(Observation.ID, Observation.ID); PROJECTION_MAP.put(Observation.ID_PLEASE, Observation.ID_PLEASE); PROJECTION_MAP.put(Observation.LATITUDE, Observation.LATITUDE); PROJECTION_MAP.put(Observation.LONGITUDE, Observation.LONGITUDE); PROJECTION_MAP.put(Observation.OBSERVED_ON, Observation.OBSERVED_ON); PROJECTION_MAP.put(Observation.OBSERVED_ON_STRING, Observation.OBSERVED_ON_STRING); PROJECTION_MAP.put(Observation.OUT_OF_RANGE, Observation.OUT_OF_RANGE); PROJECTION_MAP.put(Observation.CAPTIVE, Observation.CAPTIVE); PROJECTION_MAP.put(Observation.PLACE_GUESS, Observation.PLACE_GUESS); PROJECTION_MAP.put(Observation.UUID, Observation.UUID); PROJECTION_MAP.put(Observation.POSITIONAL_ACCURACY, Observation.POSITIONAL_ACCURACY); PROJECTION_MAP.put(Observation.POSITIONING_DEVICE, Observation.POSITIONING_DEVICE); PROJECTION_MAP.put(Observation.POSITIONING_METHOD, Observation.POSITIONING_METHOD); PROJECTION_MAP.put(Observation.PRIVATE_LATITUDE, Observation.PRIVATE_LATITUDE); PROJECTION_MAP.put(Observation.PRIVATE_LONGITUDE, Observation.PRIVATE_LONGITUDE); PROJECTION_MAP.put(Observation.PRIVATE_POSITIONAL_ACCURACY, Observation.PRIVATE_POSITIONAL_ACCURACY); PROJECTION_MAP.put(Observation.QUALITY_GRADE, Observation.QUALITY_GRADE); PROJECTION_MAP.put(Observation.SPECIES_GUESS, Observation.SPECIES_GUESS); PROJECTION_MAP.put(Observation.PREFERRED_COMMON_NAME, Observation.PREFERRED_COMMON_NAME); PROJECTION_MAP.put(Observation.TAXON_ID, Observation.TAXON_ID); PROJECTION_MAP.put(Observation.TIME_OBSERVED_AT, Observation.TIME_OBSERVED_AT); PROJECTION_MAP.put(Observation.UPDATED_AT, Observation.UPDATED_AT); PROJECTION_MAP.put(Observation.USER_AGENT, Observation.USER_AGENT); PROJECTION_MAP.put(Observation.USER_ID, Observation.USER_ID); PROJECTION_MAP.put(Observation.USER_LOGIN, Observation.USER_LOGIN); PROJECTION_MAP.put(Observation.IDENTIFICATIONS_COUNT, Observation.IDENTIFICATIONS_COUNT); PROJECTION_MAP.put(Observation.COMMENTS_COUNT, Observation.COMMENTS_COUNT); PROJECTION_MAP.put(Observation.LAST_IDENTIFICATIONS_COUNT, Observation.LAST_IDENTIFICATIONS_COUNT); PROJECTION_MAP.put(Observation.LAST_COMMENTS_COUNT, Observation.LAST_COMMENTS_COUNT); PROJECTION_MAP.put(Observation.IS_DELETED, Observation.IS_DELETED); } public Observation() {} public Observation(Cursor c) { if (c.getPosition() == -1) c.moveToFirst(); BetterCursor bc = new BetterCursor(c); this._id = bc.getInt(_ID); this._created_at = bc.getTimestamp(_CREATED_AT); this._created_at_was = this._created_at; this._synced_at = bc.getTimestamp(_SYNCED_AT); this._synced_at_was = this._synced_at; this._updated_at = bc.getTimestamp(_UPDATED_AT); this._updated_at_was = this._updated_at; this.created_at = bc.getTimestamp(CREATED_AT); this.created_at_was = this.created_at; this.description = bc.getString(DESCRIPTION); this.description_was = this.description; this.geoprivacy = bc.getString(GEOPRIVACY); this.geoprivacy_was = this.geoprivacy; this.iconic_taxon_id = bc.getInteger(ICONIC_TAXON_ID); this.iconic_taxon_id_was = this.iconic_taxon_id; this.iconic_taxon_name = bc.getString(ICONIC_TAXON_NAME); this.iconic_taxon_name_was = this.iconic_taxon_name; this.id = bc.getInteger(ID); this.id_was = this.id; this.id_please = bc.getBoolean(ID_PLEASE); this.id_please_was = this.id_please; this.latitude = bc.getDouble(LATITUDE); this.latitude_was = this.latitude; this.longitude = bc.getDouble(LONGITUDE); this.longitude_was = this.longitude; this.observed_on = bc.getTimestamp(OBSERVED_ON); this.observed_on_was = this.observed_on; this.observed_on_string = bc.getString(OBSERVED_ON_STRING); this.observed_on_string_was = this.observed_on_string; this.out_of_range = bc.getBoolean(OUT_OF_RANGE); this.out_of_range_was = this.out_of_range; this.captive = bc.getBoolean(CAPTIVE); this.captive_was = this.captive; this.place_guess = bc.getString(PLACE_GUESS); this.place_guess_was = this.place_guess; this.uuid = bc.getString(UUID); this.positional_accuracy = bc.getInteger(POSITIONAL_ACCURACY); this.positional_accuracy_was = this.positional_accuracy; this.positioning_device = bc.getString(POSITIONING_DEVICE); this.positioning_device_was = this.positioning_device; this.positioning_method = bc.getString(POSITIONING_METHOD); this.positioning_method_was = this.positioning_method; this.private_latitude = bc.getDouble(PRIVATE_LATITUDE); this.private_latitude_was = this.private_latitude; this.private_longitude = bc.getDouble(PRIVATE_LONGITUDE); this.private_longitude_was = this.private_longitude; this.private_positional_accuracy = bc.getInteger(PRIVATE_POSITIONAL_ACCURACY); this.private_positional_accuracy_was = this.private_positional_accuracy; this.quality_grade = bc.getString(QUALITY_GRADE); this.quality_grade_was = this.quality_grade; this.species_guess = bc.getString(SPECIES_GUESS); this.species_guess_was = this.species_guess; this.preferred_common_name = bc.getString(PREFERRED_COMMON_NAME); this.taxon_id = bc.getInteger(TAXON_ID); this.taxon_id_was = this.taxon_id; this.time_observed_at = bc.getTimestamp(TIME_OBSERVED_AT); this.time_observed_at_was = this.time_observed_at; this.updated_at = bc.getTimestamp(UPDATED_AT); this.updated_at_was = this.updated_at; this.user_agent = bc.getString(USER_AGENT); this.user_agent_was = this.user_agent; this.user_id = bc.getInteger(USER_ID); this.user_id_was = this.user_id; this.user_login = bc.getString(USER_LOGIN); this.user_login_was = this.user_login; this.is_deleted = bc.getBoolean(IS_DELETED); this.is_deleted_was = this.is_deleted; this.comments_count = bc.getInteger(COMMENTS_COUNT); this.identifications_count = bc.getInteger(IDENTIFICATIONS_COUNT); this.last_comments_count = bc.getInteger(LAST_COMMENTS_COUNT); this.last_identifications_count = bc.getInteger(LAST_IDENTIFICATIONS_COUNT); } public Observation(BetterJSONObject o) { this._created_at = o.getTimestamp("_created_at"); this._created_at_was = this._created_at; this._synced_at = o.getTimestamp("_synced_at"); this._synced_at_was = this._synced_at; this._updated_at = o.getTimestamp("_updated_at"); this._updated_at_was = this._updated_at; this.created_at = o.getTimestamp("created_at"); this.created_at_was = this.created_at; this.description = o.getString("description"); this.description_was = this.description; this.geoprivacy = o.getString("geoprivacy"); this.geoprivacy_was = this.geoprivacy; this.iconic_taxon_id = o.getInteger("iconic_taxon_id"); this.iconic_taxon_id_was = this.iconic_taxon_id; this.iconic_taxon_name = o.getString("iconic_taxon_name"); this.iconic_taxon_name_was = this.iconic_taxon_name; this.id = o.getInteger("id"); this.id_was = this.id; this.id_please = o.getBoolean("id_please"); this.id_please_was = this.id_please; this.latitude = o.getDouble("latitude"); this.latitude_was = this.latitude; this.longitude = o.getDouble("longitude"); this.longitude_was = this.longitude; this.observed_on = o.getTimestamp("observed_on"); this.observed_on_was = this.observed_on; this.observed_on_string = o.getString("observed_on_string"); this.observed_on_string_was = this.observed_on_string; this.out_of_range = o.getBoolean("out_of_range"); this.out_of_range_was = this.out_of_range; this.captive = o.getBoolean("captive"); this.captive_was = this.captive; this.place_guess = o.getString("place_guess"); this.place_guess_was = this.place_guess; this.uuid = o.getString("uuid"); this.positional_accuracy = o.getInteger("positional_accuracy"); this.positional_accuracy_was = this.positional_accuracy; this.positioning_device = o.getString("positioning_device"); this.positioning_device_was = this.positioning_device; this.positioning_method = o.getString("positioning_method"); this.positioning_method_was = this.positioning_method; this.private_latitude = o.getDouble("private_latitude"); this.private_latitude_was = this.private_latitude; this.private_longitude = o.getDouble("private_longitude"); this.private_longitude_was = this.private_longitude; this.private_positional_accuracy = o.getInteger("private_positional_accuracy"); this.private_positional_accuracy_was = this.private_positional_accuracy; this.quality_grade = o.getString("quality_grade"); this.quality_grade_was = this.quality_grade; this.species_guess = o.getString("species_guess"); this.species_guess_was = this.species_guess; this.taxon_id = o.getInteger("taxon_id"); this.taxon_id_was = this.taxon_id; this.time_observed_at = o.getTimestamp("time_observed_at"); this.time_observed_at_was = this.time_observed_at; this.updated_at = o.getTimestamp("updated_at"); this.updated_at_was = this.updated_at; this.user_agent = o.getString("user_agent"); this.user_agent_was = this.user_agent; this.user_id = o.getInteger("user_id"); this.user_id_was = this.user_id; this.user_login = o.getString("user_login"); this.user_login_was = this.user_login; this.is_deleted_was = this.is_deleted; this.comments = o.getJSONArray("comments"); this.identifications = o.getJSONArray("identifications"); this.favorites = o.getJSONArray("faves"); try { this.photos = new ArrayList<ObservationPhoto>(); JSONArray photos; photos = o.getJSONObject().getJSONArray("observation_photos"); for (int i = 0; i < photos.length(); i++) { BetterJSONObject json = new BetterJSONObject((JSONObject)photos.get(i)); ObservationPhoto photo = new ObservationPhoto(json); photo.observation_id = o.getInt("id"); photo._observation_id = this._id; photo._photo_id = photo.photo_id; this.photos.add(photo); } } catch (JSONException e) { e.printStackTrace(); } this.comments_count = o.getInteger("comments_count"); this.identifications_count = o.getInteger("identifications_count"); this.projects = o.getJSONArray("project_observations"); this.preferred_common_name = null; JSONObject taxon = o.getJSONObject("taxon"); if (taxon != null) { if (taxon.has("common_name") && !taxon.isNull("common_name")) { try { this.preferred_common_name = taxon.getJSONObject("common_name").optString("name"); } catch (JSONException e) { e.printStackTrace(); } } else { this.preferred_common_name = taxon.optString("name"); } } } @Override public String toString() { return "Observation(id: " + id + ", _id: " + _id + ")"; } public JSONObject toJSONObject() { BetterJSONObject bo = new BetterJSONObject(); bo.put("_created_at", _created_at); bo.put("_synced_at", _synced_at); bo.put("_updated_at", _updated_at); bo.put("created_at", created_at); bo.put("description", description); bo.put("geoprivacy", geoprivacy); bo.put("iconic_taxon_id", iconic_taxon_id); bo.put("iconic_taxon_name", iconic_taxon_name); bo.put("id", id); bo.put("id_please", id_please); bo.put("latitude", latitude); bo.put("longitude", longitude); bo.put("observed_on", observed_on); bo.put("observed_on_string", observed_on_string); bo.put("out_of_range", out_of_range); bo.put("captive", captive); bo.put("place_guess", place_guess); bo.put("uuid", uuid); bo.put("positional_accuracy", positional_accuracy); bo.put("positioning_device", positioning_device); bo.put("positioning_method", positioning_method); bo.put("private_latitude", private_latitude); bo.put("private_longitude", private_longitude); bo.put("private_positional_accuracy", private_positional_accuracy); bo.put("quality_grade", quality_grade); bo.put("species_guess", species_guess); bo.put("taxon_id", taxon_id); bo.put("time_observed_at", time_observed_at); bo.put("updated_at", updated_at); bo.put("user_agent", user_agent); bo.put("user_id", user_id); bo.put("user_login", user_login); bo.put("identifications_count", identifications_count); bo.put("comment_count", comments_count); return bo.getJSONObject(); } public Uri getUri() { if (_id == null) { return null; } else { return ContentUris.withAppendedId(CONTENT_URI, _id); } } // Returns true if observation was modified because of the merge public boolean merge(Observation observation) { if (this._updated_at.before(observation.updated_at)) { // overwrite this.created_at = observation.created_at; this.description = observation.description; this.geoprivacy = observation.geoprivacy; this.iconic_taxon_id = observation.iconic_taxon_id; this.iconic_taxon_name = observation.iconic_taxon_name; if (observation.preferred_common_name != null) this.preferred_common_name = observation.preferred_common_name; this.id = observation.id; this.id_please = observation.id_please; this.latitude = observation.latitude; this.longitude = observation.longitude; this.observed_on = observation.observed_on; this.observed_on_string = observation.observed_on_string; this.out_of_range = observation.out_of_range; this.captive = observation.captive; this.place_guess = observation.place_guess; this.uuid = observation.uuid; this.positional_accuracy = observation.positional_accuracy; this.positioning_device = observation.positioning_device; this.positioning_method = observation.positioning_method; this.private_latitude = observation.private_latitude; this.private_longitude = observation.private_longitude; this.private_positional_accuracy = observation.private_positional_accuracy; this.quality_grade = observation.quality_grade; this.species_guess = observation.species_guess; this.taxon_id = observation.taxon_id; this.time_observed_at = observation.time_observed_at; this.updated_at = observation.updated_at; this.user_agent = observation.user_agent; this.user_id = observation.user_id; this.user_login = observation.user_login; this.comments_count = observation.comments_count; this.identifications_count = observation.identifications_count; return true; } else { // set if null boolean isModified = false; if ((this.created_at == null) && (observation.created_at != null)) { this.created_at = observation.created_at; isModified = true; } if ((this.description == null) && (observation.description != null)) { this.description = observation.description; isModified = true; } if ((this.geoprivacy == null) && (observation.geoprivacy != null)) { this.geoprivacy = observation.geoprivacy; isModified = true; } if ((this.iconic_taxon_id == null) && (observation.iconic_taxon_id != null)) { this.iconic_taxon_id = observation.iconic_taxon_id; isModified = true; } if ((this.iconic_taxon_name == null) && (observation.iconic_taxon_name != null)) { this.iconic_taxon_name = observation.iconic_taxon_name; isModified = true; } if ((this.id == null) && (observation.id != null)) { this.id = observation.id; isModified = true; } if ((this.id_please == null) && (observation.id_please != null)) { this.id_please = observation.id_please; isModified = true; } if ((this.latitude == null) && (observation.latitude != null)) { this.latitude = observation.latitude; isModified = true; } if ((this.longitude == null) && (observation.longitude != null)) { this.longitude = observation.longitude; isModified = true; } if ((this.observed_on == null) && (observation.observed_on != null)) { this.observed_on = observation.observed_on; isModified = true; } if ((this.observed_on_string == null) && (observation.observed_on_string != null)) { this.observed_on_string = observation.observed_on_string; isModified = true; } if ((this.out_of_range == null) && (observation.out_of_range != null)) { this.out_of_range = observation.out_of_range; isModified = true; } if ((this.captive == null) && (observation.captive != null)) { this.captive = observation.captive; isModified = true; } if ((this.place_guess == null) && (observation.place_guess != null)) { this.place_guess = observation.place_guess; isModified = true; } if ((this.uuid == null) && (observation.uuid != null)) { this.uuid = observation.uuid; isModified = true; } if ((this.positional_accuracy == null) && (observation.positional_accuracy != null)) { this.positional_accuracy = observation.positional_accuracy; isModified = true; } if ((this.positioning_device == null) && (observation.positioning_device != null)) { this.positioning_device = observation.positioning_device; isModified = true; } if ((this.positioning_method == null) && (observation.positioning_method != null)) { this.positioning_method = observation.positioning_method; isModified = true; } if ((this.private_latitude == null) && (observation.private_latitude != null)) { this.private_latitude = observation.private_latitude; isModified = true; } if ((this.private_longitude == null) && (observation.private_longitude != null)) { this.private_longitude = observation.private_longitude; isModified = true; } if ((this.private_positional_accuracy == null) && (observation.private_positional_accuracy != null)) { this.private_positional_accuracy = observation.private_positional_accuracy; isModified = true; } if ((this.quality_grade == null) && (observation.quality_grade != null)) { this.quality_grade = observation.quality_grade; isModified = true; } if ((this.species_guess == null) && (observation.species_guess != null)) { this.species_guess = observation.species_guess; isModified = true; } if ((this.preferred_common_name == null) && (observation.preferred_common_name != null)) { this.preferred_common_name = observation.preferred_common_name; isModified = true; } if ((this.taxon_id == null) && (observation.taxon_id != null)) { this.taxon_id = observation.taxon_id; isModified = true; } if ((this.time_observed_at == null) && (observation.time_observed_at != null)) { this.time_observed_at = observation.time_observed_at; isModified = true; } if ((this.updated_at == null) && (observation.updated_at != null)) { this.updated_at = observation.updated_at; isModified = true; } if ((this.user_agent == null) && (observation.user_agent != null)) { this.user_agent = observation.user_agent; isModified = true; } if ((this.user_id == null) && (observation.user_id != null)) { this.user_id = observation.user_id; isModified = true; } if ((this.user_login == null) && (observation.user_login != null)) { this.user_login = observation.user_login; isModified = true; } if ((this.comments_count == null) && (observation.comments_count != null)) { this.comments_count = observation.comments_count; isModified = true; } if ((this.identifications_count == null) && (observation.identifications_count != null)) { this.identifications_count = observation.identifications_count; isModified = true; } return isModified; } } public ContentValues getContentValues() { ContentValues cv = new ContentValues(); if (created_at != null) { cv.put(CREATED_AT, created_at.getTime()); } cv.put(DESCRIPTION, description); cv.put(GEOPRIVACY, geoprivacy); cv.put(ICONIC_TAXON_ID, iconic_taxon_id); cv.put(ICONIC_TAXON_NAME, iconic_taxon_name); cv.put(ID, id); cv.put(ID_PLEASE, id_please); cv.put(LATITUDE, latitude); cv.put(LONGITUDE, longitude); if (observed_on != null) { cv.put(OBSERVED_ON, observed_on.getTime()); } cv.put(OBSERVED_ON_STRING, observed_on_string); cv.put(OUT_OF_RANGE, out_of_range); cv.put(CAPTIVE, captive); cv.put(PLACE_GUESS, place_guess); cv.put(UUID, uuid); cv.put(POSITIONAL_ACCURACY, positional_accuracy); cv.put(POSITIONING_DEVICE, positioning_device); cv.put(POSITIONING_METHOD, positioning_method); cv.put(PRIVATE_LATITUDE, private_latitude); cv.put(PRIVATE_LONGITUDE, private_longitude); cv.put(PRIVATE_POSITIONAL_ACCURACY, private_positional_accuracy); cv.put(QUALITY_GRADE, quality_grade); cv.put(SPECIES_GUESS, species_guess); cv.put(PREFERRED_COMMON_NAME, preferred_common_name); cv.put(TAXON_ID, taxon_id); if (time_observed_at != null) { cv.put(TIME_OBSERVED_AT, time_observed_at.getTime()); } if (updated_at != null) { cv.put(UPDATED_AT, updated_at.getTime()); } cv.put(USER_AGENT, user_agent); cv.put(USER_ID, user_id); cv.put(USER_LOGIN, user_login); cv.put(COMMENTS_COUNT, comments_count); cv.put(IDENTIFICATIONS_COUNT, identifications_count); cv.put(LAST_COMMENTS_COUNT, last_comments_count); cv.put(LAST_IDENTIFICATIONS_COUNT, last_identifications_count); cv.put(IS_DELETED, is_deleted); return cv; } public ArrayList<NameValuePair> getParams() { final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); if (description != null) { params.add(new BasicNameValuePair("observation[description]", description.toString())); } if (geoprivacy != null) { params.add(new BasicNameValuePair("observation[geoprivacy]", geoprivacy.toString())); } if (iconic_taxon_id != null) { params.add(new BasicNameValuePair("observation[iconic_taxon_id]", iconic_taxon_id.toString())); } if (id_please != null) { params.add(new BasicNameValuePair("observation[id_please]", id_please.toString())); } params.add(new BasicNameValuePair("observation[latitude]", latitude != null ? latitude.toString() : "")); params.add(new BasicNameValuePair("observation[longitude]", longitude != null ? longitude.toString() : "")); if (observed_on_string != null) { params.add(new BasicNameValuePair("observation[observed_on_string]", observed_on_string.toString())); } if (out_of_range != null) { params.add(new BasicNameValuePair("observation[out_of_range]", out_of_range.toString())); } if (captive != null) { params.add(new BasicNameValuePair("observation[captive_flag]", captive.toString())); } if (place_guess != null) { params.add(new BasicNameValuePair("observation[place_guess]", place_guess.toString())); } if (uuid != null) { params.add(new BasicNameValuePair("observation[uuid]", uuid)); } params.add(new BasicNameValuePair("observation[positional_accuracy]", positional_accuracy != null ? positional_accuracy.toString() : "")); if (positioning_device != null) { params.add(new BasicNameValuePair("observation[positioning_device]", positioning_device.toString())); } if (positioning_method != null) { params.add(new BasicNameValuePair("observation[positioning_method]", positioning_method.toString())); } if (private_latitude != null) { params.add(new BasicNameValuePair("observation[private_latitude]", private_latitude.toString())); } if (private_longitude != null) { params.add(new BasicNameValuePair("observation[private_longitude]", private_longitude.toString())); } if (private_positional_accuracy != null) { params.add(new BasicNameValuePair("observation[private_positional_accuracy]", private_positional_accuracy.toString())); } if (quality_grade != null) { params.add(new BasicNameValuePair("observation[quality_grade]", quality_grade.toString())); } if (species_guess != null) { params.add(new BasicNameValuePair("observation[species_guess]", species_guess.toString())); } if (taxon_id != null) { params.add(new BasicNameValuePair("observation[taxon_id]", taxon_id.toString())); } if (user_agent != null) { params.add(new BasicNameValuePair("observation[user_agent]", user_agent.toString())); } return params; } public static String sqlCreate() { return "CREATE TABLE " + TABLE_NAME + " (" + Observation._ID + " INTEGER PRIMARY KEY," + "_created_at INTEGER," + "_synced_at INTEGER," + "_updated_at INTEGER," + "created_at INTEGER," + "description TEXT," + "geoprivacy TEXT," + "iconic_taxon_id INTEGER," + "iconic_taxon_name TEXT," + "id INTEGER," + "id_please INTEGER," + "latitude REAL," + "longitude REAL," + "observed_on INTEGER," + "observed_on_string TEXT," + "out_of_range INTEGER," + "captive INTEGER," + "place_guess TEXT," + "uuid TEXT," + "positional_accuracy INTEGER," + "positioning_device TEXT," + "positioning_method TEXT," + "private_latitude REAL," + "private_longitude REAL," + "private_positional_accuracy INTEGER," + "quality_grade TEXT," + "species_guess TEXT," + "preferred_common_name TEXT," + "taxon_id INTEGER," + "time_observed_at INTEGER," + "updated_at INTEGER," + "user_agent TEXT," + "user_id INTEGER," + "user_login TEXT," + "comments_count INTEGER," + "identifications_count INTEGER," + "last_comments_count INTEGER," + "last_identifications_count INTEGER," + "activity_viewed_at INTEGER," + "last_activity_at INTEGER," + "is_deleted INTEGER" + ");"; } public boolean _created_at_changed() { return !String.valueOf(_created_at).equals(String.valueOf(_created_at_was)); } public boolean _synced_at_changed() { return !String.valueOf(_synced_at).equals(String.valueOf(_synced_at_was)); } public boolean _updated_at_changed() { return !String.valueOf(_updated_at).equals(String.valueOf(_updated_at_was)); } public boolean created_at_changed() { return !String.valueOf(created_at).equals(String.valueOf(created_at_was)); } public boolean description_changed() { return !String.valueOf(description).equals(String.valueOf(description_was)); } public boolean geoprivacy_changed() { return !String.valueOf(geoprivacy).equals(String.valueOf(geoprivacy_was)); } public boolean iconic_taxon_id_changed() { return !String.valueOf(iconic_taxon_id).equals(String.valueOf(iconic_taxon_id_was)); } public boolean iconic_taxon_name_changed() { return !String.valueOf(iconic_taxon_name).equals(String.valueOf(iconic_taxon_name_was)); } public boolean id_changed() { return !String.valueOf(id).equals(String.valueOf(id_was)); } public boolean id_please_changed() { return !String.valueOf(id_please).equals(String.valueOf(id_please_was)); } public boolean latitude_changed() { return !String.valueOf(latitude).equals(String.valueOf(latitude_was)); } public boolean longitude_changed() { return !String.valueOf(longitude).equals(String.valueOf(longitude_was)); } public boolean observed_on_changed() { return !String.valueOf(observed_on).equals(String.valueOf(observed_on_was)); } public boolean observed_on_string_changed() { return !String.valueOf(observed_on_string).equals(String.valueOf(observed_on_string_was)); } public boolean out_of_range_changed() { return !String.valueOf(out_of_range).equals(String.valueOf(out_of_range_was)); } public boolean captive_changed() { return !String.valueOf(captive).equals(String.valueOf(captive_was)); } public boolean place_guess_changed() { return !String.valueOf(place_guess).equals(String.valueOf(place_guess_was)); } public boolean positional_accuracy_changed() { return !String.valueOf(positional_accuracy).equals(String.valueOf(positional_accuracy_was)); } public boolean positioning_device_changed() { return !String.valueOf(positioning_device).equals(String.valueOf(positioning_device_was)); } public boolean positioning_method_changed() { return !String.valueOf(positioning_method).equals(String.valueOf(positioning_method_was)); } public boolean private_latitude_changed() { return !String.valueOf(private_latitude).equals(String.valueOf(private_latitude_was)); } public boolean private_longitude_changed() { return !String.valueOf(private_longitude).equals(String.valueOf(private_longitude_was)); } public boolean private_positional_accuracy_changed() { return !String.valueOf(private_positional_accuracy).equals(String.valueOf(private_positional_accuracy_was)); } public boolean quality_grade_changed() { return !String.valueOf(quality_grade).equals(String.valueOf(quality_grade_was)); } public boolean species_guess_changed() { return !String.valueOf(species_guess).equals(String.valueOf(species_guess_was)); } public boolean taxon_id_changed() { return !String.valueOf(taxon_id).equals(String.valueOf(taxon_id_was)); } public boolean time_observed_at_changed() { return !String.valueOf(time_observed_at).equals(String.valueOf(time_observed_at_was)); } public boolean updated_at_changed() { return !String.valueOf(updated_at).equals(String.valueOf(updated_at_was)); } public boolean user_agent_changed() { return !String.valueOf(user_agent).equals(String.valueOf(user_agent_was)); } public boolean user_id_changed() { return !String.valueOf(user_id).equals(String.valueOf(user_id_was)); } public boolean user_login_changed() { return !String.valueOf(user_login).equals(String.valueOf(user_login_was)); } public boolean is_deleted_changed() { return is_deleted != is_deleted_was; } public boolean isDirty() { if (_created_at_changed()) { return true; } if (_synced_at_changed()) { return true; } if (_updated_at_changed()) { return true; } if (created_at_changed()) { return true; } if (description_changed()) { return true; } if (geoprivacy_changed()) { return true; } if (iconic_taxon_id_changed()) { return true; } if (iconic_taxon_name_changed()) { return true; } if (id_changed()) { return true; } if (id_please_changed()) { return true; } if (latitude_changed()) { return true; } if (longitude_changed()) { return true; } if (observed_on_changed()) { return true; } if (observed_on_string_changed()) { return true; } if (out_of_range_changed()) { return true; } if (captive_changed()) { return true; } if (place_guess_changed()) { return true; } if (positional_accuracy_changed()) { return true; } if (positioning_device_changed()) { return true; } if (positioning_method_changed()) { return true; } if (private_latitude_changed()) { return true; } if (private_longitude_changed()) { return true; } if (private_positional_accuracy_changed()) { return true; } if (quality_grade_changed()) { return true; } if (species_guess_changed()) { return true; } if (taxon_id_changed()) { return true; } if (time_observed_at_changed()) { return true; } if (updated_at_changed()) { return true; } if (user_agent_changed()) { return true; } if (user_id_changed()) { return true; } if (user_login_changed()) { return true; } if (is_deleted_changed()) { return true; } return false; } public Integer updatesCount() { Integer idCount = this.identifications_count; // assume that one of the IDs is the owner's. Not entirely safe, but often is if (this.taxon_id != null && this.taxon_id != 0 && idCount != null && idCount > 0) { idCount--; } Integer c = this.comments_count == null ? 0 : this.comments_count + idCount; return c >= 0 ? c : 0; } public boolean unviewedUpdates() { Integer c = this.updatesCount(); if (c == 0) { return false; } return (this.last_comments_count == null) || (this.last_comments_count < this.comments_count) || (this.last_identifications_count == null) || (this.last_identifications_count < this.identifications_count); } } // END GENERATED BY /Users/kueda/projects/eclipse/workspace/iNaturalist/rails2android.rb AT Mon Jan 09 13:07:06 -0500 2012
iNaturalist/src/main/java/org/inaturalist/android/Observation.java
// BEGIN GENERATED BY /Users/kueda/projects/eclipse/workspace/iNaturalist/rails2android.rb AT Mon Jan 09 13:07:06 -0500 2012 package org.inaturalist.android; import java.io.Serializable; import java.sql.Timestamp; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.ContentUris; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.provider.BaseColumns; import android.util.Log; import android.view.View; public class Observation implements BaseColumns, Serializable { public Integer _id; public Timestamp _created_at; public Timestamp _synced_at; public Timestamp _updated_at; public Timestamp created_at; public String description; public String geoprivacy; public Integer iconic_taxon_id; public String iconic_taxon_name; public Integer id; public Boolean id_please; public Double latitude; public Double longitude; public Timestamp observed_on; public String observed_on_string; public Boolean out_of_range; public Boolean captive; public String place_guess; public Integer positional_accuracy; public String positioning_device; public String positioning_method; public Double private_latitude; public Double private_longitude; public Integer private_positional_accuracy; public String quality_grade; public String species_guess; public Integer taxon_id; public Timestamp time_observed_at; public Timestamp updated_at; public String user_agent; public Integer user_id; public String user_login; public Integer comments_count; public Integer identifications_count; public Integer last_comments_count; public Integer last_identifications_count; public Boolean is_deleted; public String preferred_common_name; public SerializableJSONArray comments; public SerializableJSONArray identifications; public SerializableJSONArray favorites; public List<ObservationPhoto> photos; public Timestamp _created_at_was; public Timestamp _synced_at_was; public Timestamp _updated_at_was; public Timestamp created_at_was; public String description_was; public String geoprivacy_was; public Integer iconic_taxon_id_was; public String iconic_taxon_name_was; public Integer id_was; public Boolean id_please_was; public Double latitude_was; public Double longitude_was; public Timestamp observed_on_was; public String observed_on_string_was; public Boolean out_of_range_was; public Boolean captive_was; public String place_guess_was; public Integer positional_accuracy_was; public String positioning_device_was; public String positioning_method_was; public Double private_latitude_was; public Double private_longitude_was; public Integer private_positional_accuracy_was; public String quality_grade_was; public String species_guess_was; public Integer taxon_id_was; public Timestamp time_observed_at_was; public Timestamp updated_at_was; public String user_agent_was; public Integer user_id_was; public String user_login_was; public Boolean is_deleted_was; public SerializableJSONArray projects; public String uuid; public static final String TAG = "Observation"; public static final String TABLE_NAME = "observations"; public static final int OBSERVATIONS_URI_CODE = 1279; public static final int OBSERVATION_ID_URI_CODE = 1164; public static HashMap<String, String> PROJECTION_MAP; public static final String AUTHORITY = "org.inaturalist.android.observation"; public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/observations"); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.google.observation"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.google.observation"; public static final String DEFAULT_SORT_ORDER = "CASE WHEN id IS NULL THEN _created_at ELSE created_at END DESC"; public static final String SYNC_ORDER = "_created_at ASC"; public static final String _CREATED_AT = "_created_at"; public static final String _SYNCED_AT = "_synced_at"; public static final String _UPDATED_AT = "_updated_at"; public static final String CREATED_AT = "created_at"; public static final String DESCRIPTION = "description"; public static final String GEOPRIVACY = "geoprivacy"; public static final String ICONIC_TAXON_ID = "iconic_taxon_id"; public static final String ICONIC_TAXON_NAME = "iconic_taxon_name"; public static final String ID = "id"; public static final String ID_PLEASE = "id_please"; public static final String LATITUDE = "latitude"; public static final String LONGITUDE = "longitude"; public static final String OBSERVED_ON = "observed_on"; public static final String OBSERVED_ON_STRING = "observed_on_string"; public static final String OUT_OF_RANGE = "out_of_range"; public static final String CAPTIVE = "captive"; public static final String PLACE_GUESS = "place_guess"; public static final String POSITIONAL_ACCURACY = "positional_accuracy"; public static final String POSITIONING_DEVICE = "positioning_device"; public static final String POSITIONING_METHOD = "positioning_method"; public static final String PRIVATE_LATITUDE = "private_latitude"; public static final String PRIVATE_LONGITUDE = "private_longitude"; public static final String PRIVATE_POSITIONAL_ACCURACY = "private_positional_accuracy"; public static final String QUALITY_GRADE = "quality_grade"; public static final String SPECIES_GUESS = "species_guess"; public static final String PREFERRED_COMMON_NAME = "preferred_common_name"; public static final String TAXON_ID = "taxon_id"; public static final String TIME_OBSERVED_AT = "time_observed_at"; public static final String UPDATED_AT = "updated_at"; public static final String USER_AGENT = "user_agent"; public static final String USER_ID = "user_id"; public static final String USER_LOGIN = "user_login"; public static final String COMMENTS_COUNT = "comments_count"; public static final String IDENTIFICATIONS_COUNT = "identifications_count"; public static final String LAST_COMMENTS_COUNT = "last_comments_count"; public static final String LAST_IDENTIFICATIONS_COUNT = "last_identifications_count"; public static final String IS_DELETED = "is_deleted"; public static final String UUID = "uuid"; public static final String[] PROJECTION = new String[] { Observation._ID, Observation._CREATED_AT, Observation._SYNCED_AT, Observation._UPDATED_AT, Observation.CREATED_AT, Observation.DESCRIPTION, Observation.GEOPRIVACY, Observation.ICONIC_TAXON_ID, Observation.ICONIC_TAXON_NAME, Observation.ID, Observation.ID_PLEASE, Observation.LATITUDE, Observation.LONGITUDE, Observation.OBSERVED_ON, Observation.OBSERVED_ON_STRING, Observation.OUT_OF_RANGE, Observation.CAPTIVE, Observation.PLACE_GUESS, Observation.POSITIONAL_ACCURACY, Observation.POSITIONING_DEVICE, Observation.POSITIONING_METHOD, Observation.PRIVATE_LATITUDE, Observation.PRIVATE_LONGITUDE, Observation.PRIVATE_POSITIONAL_ACCURACY, Observation.QUALITY_GRADE, Observation.SPECIES_GUESS, Observation.PREFERRED_COMMON_NAME, Observation.TAXON_ID, Observation.TIME_OBSERVED_AT, Observation.UPDATED_AT, Observation.USER_AGENT, Observation.USER_ID, Observation.USER_LOGIN, Observation.IDENTIFICATIONS_COUNT, Observation.COMMENTS_COUNT, Observation.LAST_COMMENTS_COUNT, Observation.LAST_IDENTIFICATIONS_COUNT, Observation.IS_DELETED, Observation.UUID, }; static { PROJECTION_MAP = new HashMap<String, String>(); PROJECTION_MAP.put(Observation._ID, Observation._ID); PROJECTION_MAP.put(Observation._CREATED_AT, Observation._CREATED_AT); PROJECTION_MAP.put(Observation._SYNCED_AT, Observation._SYNCED_AT); PROJECTION_MAP.put(Observation._UPDATED_AT, Observation._UPDATED_AT); PROJECTION_MAP.put(Observation.CREATED_AT, Observation.CREATED_AT); PROJECTION_MAP.put(Observation.DESCRIPTION, Observation.DESCRIPTION); PROJECTION_MAP.put(Observation.GEOPRIVACY, Observation.GEOPRIVACY); PROJECTION_MAP.put(Observation.ICONIC_TAXON_ID, Observation.ICONIC_TAXON_ID); PROJECTION_MAP.put(Observation.ICONIC_TAXON_NAME, Observation.ICONIC_TAXON_NAME); PROJECTION_MAP.put(Observation.ID, Observation.ID); PROJECTION_MAP.put(Observation.ID_PLEASE, Observation.ID_PLEASE); PROJECTION_MAP.put(Observation.LATITUDE, Observation.LATITUDE); PROJECTION_MAP.put(Observation.LONGITUDE, Observation.LONGITUDE); PROJECTION_MAP.put(Observation.OBSERVED_ON, Observation.OBSERVED_ON); PROJECTION_MAP.put(Observation.OBSERVED_ON_STRING, Observation.OBSERVED_ON_STRING); PROJECTION_MAP.put(Observation.OUT_OF_RANGE, Observation.OUT_OF_RANGE); PROJECTION_MAP.put(Observation.CAPTIVE, Observation.CAPTIVE); PROJECTION_MAP.put(Observation.PLACE_GUESS, Observation.PLACE_GUESS); PROJECTION_MAP.put(Observation.UUID, Observation.UUID); PROJECTION_MAP.put(Observation.POSITIONAL_ACCURACY, Observation.POSITIONAL_ACCURACY); PROJECTION_MAP.put(Observation.POSITIONING_DEVICE, Observation.POSITIONING_DEVICE); PROJECTION_MAP.put(Observation.POSITIONING_METHOD, Observation.POSITIONING_METHOD); PROJECTION_MAP.put(Observation.PRIVATE_LATITUDE, Observation.PRIVATE_LATITUDE); PROJECTION_MAP.put(Observation.PRIVATE_LONGITUDE, Observation.PRIVATE_LONGITUDE); PROJECTION_MAP.put(Observation.PRIVATE_POSITIONAL_ACCURACY, Observation.PRIVATE_POSITIONAL_ACCURACY); PROJECTION_MAP.put(Observation.QUALITY_GRADE, Observation.QUALITY_GRADE); PROJECTION_MAP.put(Observation.SPECIES_GUESS, Observation.SPECIES_GUESS); PROJECTION_MAP.put(Observation.PREFERRED_COMMON_NAME, Observation.PREFERRED_COMMON_NAME); PROJECTION_MAP.put(Observation.TAXON_ID, Observation.TAXON_ID); PROJECTION_MAP.put(Observation.TIME_OBSERVED_AT, Observation.TIME_OBSERVED_AT); PROJECTION_MAP.put(Observation.UPDATED_AT, Observation.UPDATED_AT); PROJECTION_MAP.put(Observation.USER_AGENT, Observation.USER_AGENT); PROJECTION_MAP.put(Observation.USER_ID, Observation.USER_ID); PROJECTION_MAP.put(Observation.USER_LOGIN, Observation.USER_LOGIN); PROJECTION_MAP.put(Observation.IDENTIFICATIONS_COUNT, Observation.IDENTIFICATIONS_COUNT); PROJECTION_MAP.put(Observation.COMMENTS_COUNT, Observation.COMMENTS_COUNT); PROJECTION_MAP.put(Observation.LAST_IDENTIFICATIONS_COUNT, Observation.LAST_IDENTIFICATIONS_COUNT); PROJECTION_MAP.put(Observation.LAST_COMMENTS_COUNT, Observation.LAST_COMMENTS_COUNT); PROJECTION_MAP.put(Observation.IS_DELETED, Observation.IS_DELETED); } public Observation() {} public Observation(Cursor c) { if (c.getPosition() == -1) c.moveToFirst(); BetterCursor bc = new BetterCursor(c); this._id = bc.getInt(_ID); this._created_at = bc.getTimestamp(_CREATED_AT); this._created_at_was = this._created_at; this._synced_at = bc.getTimestamp(_SYNCED_AT); this._synced_at_was = this._synced_at; this._updated_at = bc.getTimestamp(_UPDATED_AT); this._updated_at_was = this._updated_at; this.created_at = bc.getTimestamp(CREATED_AT); this.created_at_was = this.created_at; this.description = bc.getString(DESCRIPTION); this.description_was = this.description; this.geoprivacy = bc.getString(GEOPRIVACY); this.geoprivacy_was = this.geoprivacy; this.iconic_taxon_id = bc.getInteger(ICONIC_TAXON_ID); this.iconic_taxon_id_was = this.iconic_taxon_id; this.iconic_taxon_name = bc.getString(ICONIC_TAXON_NAME); this.iconic_taxon_name_was = this.iconic_taxon_name; this.id = bc.getInteger(ID); this.id_was = this.id; this.id_please = bc.getBoolean(ID_PLEASE); this.id_please_was = this.id_please; this.latitude = bc.getDouble(LATITUDE); this.latitude_was = this.latitude; this.longitude = bc.getDouble(LONGITUDE); this.longitude_was = this.longitude; this.observed_on = bc.getTimestamp(OBSERVED_ON); this.observed_on_was = this.observed_on; this.observed_on_string = bc.getString(OBSERVED_ON_STRING); this.observed_on_string_was = this.observed_on_string; this.out_of_range = bc.getBoolean(OUT_OF_RANGE); this.out_of_range_was = this.out_of_range; this.captive = bc.getBoolean(CAPTIVE); this.captive_was = this.captive; this.place_guess = bc.getString(PLACE_GUESS); this.place_guess_was = this.place_guess; this.uuid = bc.getString(UUID); this.positional_accuracy = bc.getInteger(POSITIONAL_ACCURACY); this.positional_accuracy_was = this.positional_accuracy; this.positioning_device = bc.getString(POSITIONING_DEVICE); this.positioning_device_was = this.positioning_device; this.positioning_method = bc.getString(POSITIONING_METHOD); this.positioning_method_was = this.positioning_method; this.private_latitude = bc.getDouble(PRIVATE_LATITUDE); this.private_latitude_was = this.private_latitude; this.private_longitude = bc.getDouble(PRIVATE_LONGITUDE); this.private_longitude_was = this.private_longitude; this.private_positional_accuracy = bc.getInteger(PRIVATE_POSITIONAL_ACCURACY); this.private_positional_accuracy_was = this.private_positional_accuracy; this.quality_grade = bc.getString(QUALITY_GRADE); this.quality_grade_was = this.quality_grade; this.species_guess = bc.getString(SPECIES_GUESS); this.species_guess_was = this.species_guess; this.preferred_common_name = bc.getString(PREFERRED_COMMON_NAME); this.taxon_id = bc.getInteger(TAXON_ID); this.taxon_id_was = this.taxon_id; this.time_observed_at = bc.getTimestamp(TIME_OBSERVED_AT); this.time_observed_at_was = this.time_observed_at; this.updated_at = bc.getTimestamp(UPDATED_AT); this.updated_at_was = this.updated_at; this.user_agent = bc.getString(USER_AGENT); this.user_agent_was = this.user_agent; this.user_id = bc.getInteger(USER_ID); this.user_id_was = this.user_id; this.user_login = bc.getString(USER_LOGIN); this.user_login_was = this.user_login; this.is_deleted = bc.getBoolean(IS_DELETED); this.is_deleted_was = this.is_deleted; this.comments_count = bc.getInteger(COMMENTS_COUNT); this.identifications_count = bc.getInteger(IDENTIFICATIONS_COUNT); this.last_comments_count = bc.getInteger(LAST_COMMENTS_COUNT); this.last_identifications_count = bc.getInteger(LAST_IDENTIFICATIONS_COUNT); } public Observation(BetterJSONObject o) { this._created_at = o.getTimestamp("_created_at"); this._created_at_was = this._created_at; this._synced_at = o.getTimestamp("_synced_at"); this._synced_at_was = this._synced_at; this._updated_at = o.getTimestamp("_updated_at"); this._updated_at_was = this._updated_at; this.created_at = o.getTimestamp("created_at"); this.created_at_was = this.created_at; this.description = o.getString("description"); this.description_was = this.description; this.geoprivacy = o.getString("geoprivacy"); this.geoprivacy_was = this.geoprivacy; this.iconic_taxon_id = o.getInteger("iconic_taxon_id"); this.iconic_taxon_id_was = this.iconic_taxon_id; this.iconic_taxon_name = o.getString("iconic_taxon_name"); this.iconic_taxon_name_was = this.iconic_taxon_name; this.id = o.getInteger("id"); this.id_was = this.id; this.id_please = o.getBoolean("id_please"); this.id_please_was = this.id_please; this.latitude = o.getDouble("latitude"); this.latitude_was = this.latitude; this.longitude = o.getDouble("longitude"); this.longitude_was = this.longitude; this.observed_on = o.getTimestamp("observed_on"); this.observed_on_was = this.observed_on; this.observed_on_string = o.getString("observed_on_string"); this.observed_on_string_was = this.observed_on_string; this.out_of_range = o.getBoolean("out_of_range"); this.out_of_range_was = this.out_of_range; this.captive = o.getBoolean("captive"); this.captive_was = this.captive; this.place_guess = o.getString("place_guess"); this.place_guess_was = this.place_guess; this.uuid = o.getString("uuid"); this.positional_accuracy = o.getInteger("positional_accuracy"); this.positional_accuracy_was = this.positional_accuracy; this.positioning_device = o.getString("positioning_device"); this.positioning_device_was = this.positioning_device; this.positioning_method = o.getString("positioning_method"); this.positioning_method_was = this.positioning_method; this.private_latitude = o.getDouble("private_latitude"); this.private_latitude_was = this.private_latitude; this.private_longitude = o.getDouble("private_longitude"); this.private_longitude_was = this.private_longitude; this.private_positional_accuracy = o.getInteger("private_positional_accuracy"); this.private_positional_accuracy_was = this.private_positional_accuracy; this.quality_grade = o.getString("quality_grade"); this.quality_grade_was = this.quality_grade; this.species_guess = o.getString("species_guess"); this.species_guess_was = this.species_guess; this.taxon_id = o.getInteger("taxon_id"); this.taxon_id_was = this.taxon_id; this.time_observed_at = o.getTimestamp("time_observed_at"); this.time_observed_at_was = this.time_observed_at; this.updated_at = o.getTimestamp("updated_at"); this.updated_at_was = this.updated_at; this.user_agent = o.getString("user_agent"); this.user_agent_was = this.user_agent; this.user_id = o.getInteger("user_id"); this.user_id_was = this.user_id; this.user_login = o.getString("user_login"); this.user_login_was = this.user_login; this.is_deleted_was = this.is_deleted; this.comments = o.getJSONArray("comments"); this.identifications = o.getJSONArray("identifications"); this.favorites = o.getJSONArray("faves"); try { this.photos = new ArrayList<ObservationPhoto>(); JSONArray photos; photos = o.getJSONObject().getJSONArray("observation_photos"); for (int i = 0; i < photos.length(); i++) { BetterJSONObject json = new BetterJSONObject((JSONObject)photos.get(i)); ObservationPhoto photo = new ObservationPhoto(json); photo.observation_id = o.getInt("id"); photo._observation_id = this._id; photo._photo_id = photo.photo_id; this.photos.add(photo); } } catch (JSONException e) { e.printStackTrace(); } this.comments_count = o.getInteger("comments_count"); this.identifications_count = o.getInteger("identifications_count"); this.projects = o.getJSONArray("project_observations"); this.preferred_common_name = null; JSONObject taxon = o.getJSONObject("taxon"); if (taxon != null) { if (taxon.has("common_name") && !taxon.isNull("common_name")) { try { this.preferred_common_name = taxon.getJSONObject("common_name").optString("name"); } catch (JSONException e) { e.printStackTrace(); } } else { this.preferred_common_name = taxon.optString("name"); } } } @Override public String toString() { return "Observation(id: " + id + ", _id: " + _id + ")"; } public JSONObject toJSONObject() { BetterJSONObject bo = new BetterJSONObject(); bo.put("_created_at", _created_at); bo.put("_synced_at", _synced_at); bo.put("_updated_at", _updated_at); bo.put("created_at", created_at); bo.put("description", description); bo.put("geoprivacy", geoprivacy); bo.put("iconic_taxon_id", iconic_taxon_id); bo.put("iconic_taxon_name", iconic_taxon_name); bo.put("id", id); bo.put("id_please", id_please); bo.put("latitude", latitude); bo.put("longitude", longitude); bo.put("observed_on", observed_on); bo.put("observed_on_string", observed_on_string); bo.put("out_of_range", out_of_range); bo.put("captive", captive); bo.put("place_guess", place_guess); bo.put("uuid", uuid); bo.put("positional_accuracy", positional_accuracy); bo.put("positioning_device", positioning_device); bo.put("positioning_method", positioning_method); bo.put("private_latitude", private_latitude); bo.put("private_longitude", private_longitude); bo.put("private_positional_accuracy", private_positional_accuracy); bo.put("quality_grade", quality_grade); bo.put("species_guess", species_guess); bo.put("taxon_id", taxon_id); bo.put("time_observed_at", time_observed_at); bo.put("updated_at", updated_at); bo.put("user_agent", user_agent); bo.put("user_id", user_id); bo.put("user_login", user_login); bo.put("identifications_count", identifications_count); bo.put("comment_count", comments_count); return bo.getJSONObject(); } public Uri getUri() { if (_id == null) { return null; } else { return ContentUris.withAppendedId(CONTENT_URI, _id); } } // Returns true if observation was modified because of the merge public boolean merge(Observation observation) { if (this._updated_at.before(observation.updated_at)) { // overwrite this.created_at = observation.created_at; this.description = observation.description; this.geoprivacy = observation.geoprivacy; this.iconic_taxon_id = observation.iconic_taxon_id; this.iconic_taxon_name = observation.iconic_taxon_name; this.id = observation.id; this.id_please = observation.id_please; this.latitude = observation.latitude; this.longitude = observation.longitude; this.observed_on = observation.observed_on; this.observed_on_string = observation.observed_on_string; this.out_of_range = observation.out_of_range; this.captive = observation.captive; this.place_guess = observation.place_guess; this.uuid = observation.uuid; this.positional_accuracy = observation.positional_accuracy; this.positioning_device = observation.positioning_device; this.positioning_method = observation.positioning_method; this.private_latitude = observation.private_latitude; this.private_longitude = observation.private_longitude; this.private_positional_accuracy = observation.private_positional_accuracy; this.quality_grade = observation.quality_grade; this.species_guess = observation.species_guess; this.taxon_id = observation.taxon_id; this.time_observed_at = observation.time_observed_at; this.updated_at = observation.updated_at; this.user_agent = observation.user_agent; this.user_id = observation.user_id; this.user_login = observation.user_login; this.comments_count = observation.comments_count; this.identifications_count = observation.identifications_count; return true; } else { // set if null boolean isModified = false; if ((this.created_at == null) && (observation.created_at != null)) { this.created_at = observation.created_at; isModified = true; } if ((this.description == null) && (observation.description != null)) { this.description = observation.description; isModified = true; } if ((this.geoprivacy == null) && (observation.geoprivacy != null)) { this.geoprivacy = observation.geoprivacy; isModified = true; } if ((this.iconic_taxon_id == null) && (observation.iconic_taxon_id != null)) { this.iconic_taxon_id = observation.iconic_taxon_id; isModified = true; } if ((this.iconic_taxon_name == null) && (observation.iconic_taxon_name != null)) { this.iconic_taxon_name = observation.iconic_taxon_name; isModified = true; } if ((this.id == null) && (observation.id != null)) { this.id = observation.id; isModified = true; } if ((this.id_please == null) && (observation.id_please != null)) { this.id_please = observation.id_please; isModified = true; } if ((this.latitude == null) && (observation.latitude != null)) { this.latitude = observation.latitude; isModified = true; } if ((this.longitude == null) && (observation.longitude != null)) { this.longitude = observation.longitude; isModified = true; } if ((this.observed_on == null) && (observation.observed_on != null)) { this.observed_on = observation.observed_on; isModified = true; } if ((this.observed_on_string == null) && (observation.observed_on_string != null)) { this.observed_on_string = observation.observed_on_string; isModified = true; } if ((this.out_of_range == null) && (observation.out_of_range != null)) { this.out_of_range = observation.out_of_range; isModified = true; } if ((this.captive == null) && (observation.captive != null)) { this.captive = observation.captive; isModified = true; } if ((this.place_guess == null) && (observation.place_guess != null)) { this.place_guess = observation.place_guess; isModified = true; } if ((this.uuid == null) && (observation.uuid != null)) { this.uuid = observation.uuid; isModified = true; } if ((this.positional_accuracy == null) && (observation.positional_accuracy != null)) { this.positional_accuracy = observation.positional_accuracy; isModified = true; } if ((this.positioning_device == null) && (observation.positioning_device != null)) { this.positioning_device = observation.positioning_device; isModified = true; } if ((this.positioning_method == null) && (observation.positioning_method != null)) { this.positioning_method = observation.positioning_method; isModified = true; } if ((this.private_latitude == null) && (observation.private_latitude != null)) { this.private_latitude = observation.private_latitude; isModified = true; } if ((this.private_longitude == null) && (observation.private_longitude != null)) { this.private_longitude = observation.private_longitude; isModified = true; } if ((this.private_positional_accuracy == null) && (observation.private_positional_accuracy != null)) { this.private_positional_accuracy = observation.private_positional_accuracy; isModified = true; } if ((this.quality_grade == null) && (observation.quality_grade != null)) { this.quality_grade = observation.quality_grade; isModified = true; } if ((this.species_guess == null) && (observation.species_guess != null)) { this.species_guess = observation.species_guess; isModified = true; } if ((this.preferred_common_name == null) && (observation.preferred_common_name != null)) { this.preferred_common_name = observation.preferred_common_name; isModified = true; } if ((this.taxon_id == null) && (observation.taxon_id != null)) { this.taxon_id = observation.taxon_id; isModified = true; } if ((this.time_observed_at == null) && (observation.time_observed_at != null)) { this.time_observed_at = observation.time_observed_at; isModified = true; } if ((this.updated_at == null) && (observation.updated_at != null)) { this.updated_at = observation.updated_at; isModified = true; } if ((this.user_agent == null) && (observation.user_agent != null)) { this.user_agent = observation.user_agent; isModified = true; } if ((this.user_id == null) && (observation.user_id != null)) { this.user_id = observation.user_id; isModified = true; } if ((this.user_login == null) && (observation.user_login != null)) { this.user_login = observation.user_login; isModified = true; } if ((this.comments_count == null) && (observation.comments_count != null)) { this.comments_count = observation.comments_count; isModified = true; } if ((this.identifications_count == null) && (observation.identifications_count != null)) { this.identifications_count = observation.identifications_count; isModified = true; } return isModified; } } public ContentValues getContentValues() { ContentValues cv = new ContentValues(); if (created_at != null) { cv.put(CREATED_AT, created_at.getTime()); } cv.put(DESCRIPTION, description); cv.put(GEOPRIVACY, geoprivacy); cv.put(ICONIC_TAXON_ID, iconic_taxon_id); cv.put(ICONIC_TAXON_NAME, iconic_taxon_name); cv.put(ID, id); cv.put(ID_PLEASE, id_please); cv.put(LATITUDE, latitude); cv.put(LONGITUDE, longitude); if (observed_on != null) { cv.put(OBSERVED_ON, observed_on.getTime()); } cv.put(OBSERVED_ON_STRING, observed_on_string); cv.put(OUT_OF_RANGE, out_of_range); cv.put(CAPTIVE, captive); cv.put(PLACE_GUESS, place_guess); cv.put(UUID, uuid); cv.put(POSITIONAL_ACCURACY, positional_accuracy); cv.put(POSITIONING_DEVICE, positioning_device); cv.put(POSITIONING_METHOD, positioning_method); cv.put(PRIVATE_LATITUDE, private_latitude); cv.put(PRIVATE_LONGITUDE, private_longitude); cv.put(PRIVATE_POSITIONAL_ACCURACY, private_positional_accuracy); cv.put(QUALITY_GRADE, quality_grade); cv.put(SPECIES_GUESS, species_guess); cv.put(PREFERRED_COMMON_NAME, preferred_common_name); cv.put(TAXON_ID, taxon_id); if (time_observed_at != null) { cv.put(TIME_OBSERVED_AT, time_observed_at.getTime()); } if (updated_at != null) { cv.put(UPDATED_AT, updated_at.getTime()); } cv.put(USER_AGENT, user_agent); cv.put(USER_ID, user_id); cv.put(USER_LOGIN, user_login); cv.put(COMMENTS_COUNT, comments_count); cv.put(IDENTIFICATIONS_COUNT, identifications_count); cv.put(LAST_COMMENTS_COUNT, last_comments_count); cv.put(LAST_IDENTIFICATIONS_COUNT, last_identifications_count); cv.put(IS_DELETED, is_deleted); return cv; } public ArrayList<NameValuePair> getParams() { final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); if (description != null) { params.add(new BasicNameValuePair("observation[description]", description.toString())); } if (geoprivacy != null) { params.add(new BasicNameValuePair("observation[geoprivacy]", geoprivacy.toString())); } if (iconic_taxon_id != null) { params.add(new BasicNameValuePair("observation[iconic_taxon_id]", iconic_taxon_id.toString())); } if (id_please != null) { params.add(new BasicNameValuePair("observation[id_please]", id_please.toString())); } params.add(new BasicNameValuePair("observation[latitude]", latitude != null ? latitude.toString() : "")); params.add(new BasicNameValuePair("observation[longitude]", longitude != null ? longitude.toString() : "")); if (observed_on_string != null) { params.add(new BasicNameValuePair("observation[observed_on_string]", observed_on_string.toString())); } if (out_of_range != null) { params.add(new BasicNameValuePair("observation[out_of_range]", out_of_range.toString())); } if (captive != null) { params.add(new BasicNameValuePair("observation[captive_flag]", captive.toString())); } if (place_guess != null) { params.add(new BasicNameValuePair("observation[place_guess]", place_guess.toString())); } if (uuid != null) { params.add(new BasicNameValuePair("observation[uuid]", uuid)); } params.add(new BasicNameValuePair("observation[positional_accuracy]", positional_accuracy != null ? positional_accuracy.toString() : "")); if (positioning_device != null) { params.add(new BasicNameValuePair("observation[positioning_device]", positioning_device.toString())); } if (positioning_method != null) { params.add(new BasicNameValuePair("observation[positioning_method]", positioning_method.toString())); } if (private_latitude != null) { params.add(new BasicNameValuePair("observation[private_latitude]", private_latitude.toString())); } if (private_longitude != null) { params.add(new BasicNameValuePair("observation[private_longitude]", private_longitude.toString())); } if (private_positional_accuracy != null) { params.add(new BasicNameValuePair("observation[private_positional_accuracy]", private_positional_accuracy.toString())); } if (quality_grade != null) { params.add(new BasicNameValuePair("observation[quality_grade]", quality_grade.toString())); } if (species_guess != null) { params.add(new BasicNameValuePair("observation[species_guess]", species_guess.toString())); } if (taxon_id != null) { params.add(new BasicNameValuePair("observation[taxon_id]", taxon_id.toString())); } if (user_agent != null) { params.add(new BasicNameValuePair("observation[user_agent]", user_agent.toString())); } return params; } public static String sqlCreate() { return "CREATE TABLE " + TABLE_NAME + " (" + Observation._ID + " INTEGER PRIMARY KEY," + "_created_at INTEGER," + "_synced_at INTEGER," + "_updated_at INTEGER," + "created_at INTEGER," + "description TEXT," + "geoprivacy TEXT," + "iconic_taxon_id INTEGER," + "iconic_taxon_name TEXT," + "id INTEGER," + "id_please INTEGER," + "latitude REAL," + "longitude REAL," + "observed_on INTEGER," + "observed_on_string TEXT," + "out_of_range INTEGER," + "captive INTEGER," + "place_guess TEXT," + "uuid TEXT," + "positional_accuracy INTEGER," + "positioning_device TEXT," + "positioning_method TEXT," + "private_latitude REAL," + "private_longitude REAL," + "private_positional_accuracy INTEGER," + "quality_grade TEXT," + "species_guess TEXT," + "preferred_common_name TEXT," + "taxon_id INTEGER," + "time_observed_at INTEGER," + "updated_at INTEGER," + "user_agent TEXT," + "user_id INTEGER," + "user_login TEXT," + "comments_count INTEGER," + "identifications_count INTEGER," + "last_comments_count INTEGER," + "last_identifications_count INTEGER," + "activity_viewed_at INTEGER," + "last_activity_at INTEGER," + "is_deleted INTEGER" + ");"; } public boolean _created_at_changed() { return !String.valueOf(_created_at).equals(String.valueOf(_created_at_was)); } public boolean _synced_at_changed() { return !String.valueOf(_synced_at).equals(String.valueOf(_synced_at_was)); } public boolean _updated_at_changed() { return !String.valueOf(_updated_at).equals(String.valueOf(_updated_at_was)); } public boolean created_at_changed() { return !String.valueOf(created_at).equals(String.valueOf(created_at_was)); } public boolean description_changed() { return !String.valueOf(description).equals(String.valueOf(description_was)); } public boolean geoprivacy_changed() { return !String.valueOf(geoprivacy).equals(String.valueOf(geoprivacy_was)); } public boolean iconic_taxon_id_changed() { return !String.valueOf(iconic_taxon_id).equals(String.valueOf(iconic_taxon_id_was)); } public boolean iconic_taxon_name_changed() { return !String.valueOf(iconic_taxon_name).equals(String.valueOf(iconic_taxon_name_was)); } public boolean id_changed() { return !String.valueOf(id).equals(String.valueOf(id_was)); } public boolean id_please_changed() { return !String.valueOf(id_please).equals(String.valueOf(id_please_was)); } public boolean latitude_changed() { return !String.valueOf(latitude).equals(String.valueOf(latitude_was)); } public boolean longitude_changed() { return !String.valueOf(longitude).equals(String.valueOf(longitude_was)); } public boolean observed_on_changed() { return !String.valueOf(observed_on).equals(String.valueOf(observed_on_was)); } public boolean observed_on_string_changed() { return !String.valueOf(observed_on_string).equals(String.valueOf(observed_on_string_was)); } public boolean out_of_range_changed() { return !String.valueOf(out_of_range).equals(String.valueOf(out_of_range_was)); } public boolean captive_changed() { return !String.valueOf(captive).equals(String.valueOf(captive_was)); } public boolean place_guess_changed() { return !String.valueOf(place_guess).equals(String.valueOf(place_guess_was)); } public boolean positional_accuracy_changed() { return !String.valueOf(positional_accuracy).equals(String.valueOf(positional_accuracy_was)); } public boolean positioning_device_changed() { return !String.valueOf(positioning_device).equals(String.valueOf(positioning_device_was)); } public boolean positioning_method_changed() { return !String.valueOf(positioning_method).equals(String.valueOf(positioning_method_was)); } public boolean private_latitude_changed() { return !String.valueOf(private_latitude).equals(String.valueOf(private_latitude_was)); } public boolean private_longitude_changed() { return !String.valueOf(private_longitude).equals(String.valueOf(private_longitude_was)); } public boolean private_positional_accuracy_changed() { return !String.valueOf(private_positional_accuracy).equals(String.valueOf(private_positional_accuracy_was)); } public boolean quality_grade_changed() { return !String.valueOf(quality_grade).equals(String.valueOf(quality_grade_was)); } public boolean species_guess_changed() { return !String.valueOf(species_guess).equals(String.valueOf(species_guess_was)); } public boolean taxon_id_changed() { return !String.valueOf(taxon_id).equals(String.valueOf(taxon_id_was)); } public boolean time_observed_at_changed() { return !String.valueOf(time_observed_at).equals(String.valueOf(time_observed_at_was)); } public boolean updated_at_changed() { return !String.valueOf(updated_at).equals(String.valueOf(updated_at_was)); } public boolean user_agent_changed() { return !String.valueOf(user_agent).equals(String.valueOf(user_agent_was)); } public boolean user_id_changed() { return !String.valueOf(user_id).equals(String.valueOf(user_id_was)); } public boolean user_login_changed() { return !String.valueOf(user_login).equals(String.valueOf(user_login_was)); } public boolean is_deleted_changed() { return is_deleted != is_deleted_was; } public boolean isDirty() { if (_created_at_changed()) { return true; } if (_synced_at_changed()) { return true; } if (_updated_at_changed()) { return true; } if (created_at_changed()) { return true; } if (description_changed()) { return true; } if (geoprivacy_changed()) { return true; } if (iconic_taxon_id_changed()) { return true; } if (iconic_taxon_name_changed()) { return true; } if (id_changed()) { return true; } if (id_please_changed()) { return true; } if (latitude_changed()) { return true; } if (longitude_changed()) { return true; } if (observed_on_changed()) { return true; } if (observed_on_string_changed()) { return true; } if (out_of_range_changed()) { return true; } if (captive_changed()) { return true; } if (place_guess_changed()) { return true; } if (positional_accuracy_changed()) { return true; } if (positioning_device_changed()) { return true; } if (positioning_method_changed()) { return true; } if (private_latitude_changed()) { return true; } if (private_longitude_changed()) { return true; } if (private_positional_accuracy_changed()) { return true; } if (quality_grade_changed()) { return true; } if (species_guess_changed()) { return true; } if (taxon_id_changed()) { return true; } if (time_observed_at_changed()) { return true; } if (updated_at_changed()) { return true; } if (user_agent_changed()) { return true; } if (user_id_changed()) { return true; } if (user_login_changed()) { return true; } if (is_deleted_changed()) { return true; } return false; } public Integer updatesCount() { Integer idCount = this.identifications_count; // assume that one of the IDs is the owner's. Not entirely safe, but often is if (this.taxon_id != null && this.taxon_id != 0 && idCount != null && idCount > 0) { idCount--; } Integer c = this.comments_count == null ? 0 : this.comments_count + idCount; return c >= 0 ? c : 0; } public boolean unviewedUpdates() { Integer c = this.updatesCount(); if (c == 0) { return false; } return (this.last_comments_count == null) || (this.last_comments_count < this.comments_count) || (this.last_identifications_count == null) || (this.last_identifications_count < this.identifications_count); } } // END GENERATED BY /Users/kueda/projects/eclipse/workspace/iNaturalist/rails2android.rb AT Mon Jan 09 13:07:06 -0500 2012
Fix #202
iNaturalist/src/main/java/org/inaturalist/android/Observation.java
Fix #202
<ide><path>Naturalist/src/main/java/org/inaturalist/android/Observation.java <ide> this.geoprivacy = observation.geoprivacy; <ide> this.iconic_taxon_id = observation.iconic_taxon_id; <ide> this.iconic_taxon_name = observation.iconic_taxon_name; <add> if (observation.preferred_common_name != null) this.preferred_common_name = observation.preferred_common_name; <ide> this.id = observation.id; <ide> this.id_please = observation.id_please; <ide> this.latitude = observation.latitude;
Java
apache-2.0
19a2d2dc5d850da8b1f3f634b2a9e2c9ae46dd81
0
andrey-kuznetsov/ignite,andrey-kuznetsov/ignite,vldpyatkov/ignite,louishust/incubator-ignite,leveyj/ignite,akuznetsov-gridgain/ignite,amirakhmedov/ignite,daradurvs/ignite,shroman/ignite,ryanzz/ignite,tkpanther/ignite,irudyak/ignite,StalkXT/ignite,NSAmelchev/ignite,f7753/ignite,endian675/ignite,ilantukh/ignite,kromulan/ignite,pperalta/ignite,mcherkasov/ignite,VladimirErshov/ignite,nizhikov/ignite,gridgain/apache-ignite,ilantukh/ignite,a1vanov/ignite,vldpyatkov/ignite,ascherbakoff/ignite,svladykin/ignite,StalkXT/ignite,StalkXT/ignite,gargvish/ignite,akuznetsov-gridgain/ignite,chandresh-pancholi/ignite,irudyak/ignite,gridgain/apache-ignite,ilantukh/ignite,vadopolski/ignite,wmz7year/ignite,irudyak/ignite,vsuslov/incubator-ignite,andrey-kuznetsov/ignite,voipp/ignite,arijitt/incubator-ignite,kidaa/incubator-ignite,zzcclp/ignite,dmagda/incubator-ignite,andrey-kuznetsov/ignite,chandresh-pancholi/ignite,SharplEr/ignite,ascherbakoff/ignite,arijitt/incubator-ignite,SomeFire/ignite,vladisav/ignite,sk0x50/ignite,vladisav/ignite,murador/ignite,vadopolski/ignite,ilantukh/ignite,VladimirErshov/ignite,NSAmelchev/ignite,StalkXT/ignite,vladisav/ignite,svladykin/ignite,dmagda/incubator-ignite,nizhikov/ignite,apacheignite/ignite,agoncharuk/ignite,BiryukovVA/ignite,amirakhmedov/ignite,xtern/ignite,irudyak/ignite,StalkXT/ignite,daradurvs/ignite,dlnufox/ignite,ashutakGG/incubator-ignite,vsisko/incubator-ignite,VladimirErshov/ignite,wmz7year/ignite,ntikhonov/ignite,endian675/ignite,irudyak/ignite,DoudTechData/ignite,f7753/ignite,shroman/ignite,leveyj/ignite,agura/incubator-ignite,abhishek-ch/incubator-ignite,ptupitsyn/ignite,svladykin/ignite,dlnufox/ignite,ascherbakoff/ignite,agoncharuk/ignite,avinogradovgg/ignite,alexzaitzev/ignite,VladimirErshov/ignite,sk0x50/ignite,zzcclp/ignite,wmz7year/ignite,dmagda/incubator-ignite,WilliamDo/ignite,thuTom/ignite,ntikhonov/ignite,xtern/ignite,ryanzz/ignite,gridgain/apache-ignite,a1vanov/ignite,f7753/ignite,apache/ignite,sk0x50/ignite,dmagda/incubator-ignite,shurun19851206/ignite,apache/ignite,chandresh-pancholi/ignite,alexzaitzev/ignite,samaitra/ignite,arijitt/incubator-ignite,voipp/ignite,dlnufox/ignite,kromulan/ignite,pperalta/ignite,amirakhmedov/ignite,vsisko/incubator-ignite,shroman/ignite,xtern/ignite,chandresh-pancholi/ignite,NSAmelchev/ignite,alexzaitzev/ignite,nivanov/ignite,xtern/ignite,murador/ignite,sylentprayer/ignite,BiryukovVA/ignite,murador/ignite,VladimirErshov/ignite,f7753/ignite,thuTom/ignite,avinogradovgg/ignite,endian675/ignite,andrey-kuznetsov/ignite,BiryukovVA/ignite,chandresh-pancholi/ignite,a1vanov/ignite,murador/ignite,agoncharuk/ignite,SomeFire/ignite,mcherkasov/ignite,WilliamDo/ignite,tkpanther/ignite,tkpanther/ignite,dream-x/ignite,gridgain/apache-ignite,apacheignite/ignite,andrey-kuznetsov/ignite,dream-x/ignite,vadopolski/ignite,rfqu/ignite,dmagda/incubator-ignite,daradurvs/ignite,dmagda/incubator-ignite,samaitra/ignite,nizhikov/ignite,abhishek-ch/incubator-ignite,sk0x50/ignite,mcherkasov/ignite,afinka77/ignite,a1vanov/ignite,agura/incubator-ignite,andrey-kuznetsov/ignite,voipp/ignite,louishust/incubator-ignite,amirakhmedov/ignite,SomeFire/ignite,kromulan/ignite,adeelmahmood/ignite,leveyj/ignite,zzcclp/ignite,leveyj/ignite,vsisko/incubator-ignite,agoncharuk/ignite,wmz7year/ignite,chandresh-pancholi/ignite,ashutakGG/incubator-ignite,thuTom/ignite,alexzaitzev/ignite,murador/ignite,rfqu/ignite,SharplEr/ignite,akuznetsov-gridgain/ignite,SharplEr/ignite,dream-x/ignite,ashutakGG/incubator-ignite,ascherbakoff/ignite,akuznetsov-gridgain/ignite,BiryukovVA/ignite,nivanov/ignite,apache/ignite,f7753/ignite,leveyj/ignite,StalkXT/ignite,SharplEr/ignite,dlnufox/ignite,sk0x50/ignite,ascherbakoff/ignite,BiryukovVA/ignite,nizhikov/ignite,vldpyatkov/ignite,agura/incubator-ignite,adeelmahmood/ignite,mcherkasov/ignite,psadusumilli/ignite,NSAmelchev/ignite,wmz7year/ignite,endian675/ignite,shurun19851206/ignite,ilantukh/ignite,samaitra/ignite,zzcclp/ignite,vldpyatkov/ignite,daradurvs/ignite,ptupitsyn/ignite,dlnufox/ignite,sylentprayer/ignite,kidaa/incubator-ignite,voipp/ignite,wmz7year/ignite,thuTom/ignite,apache/ignite,mcherkasov/ignite,ascherbakoff/ignite,ascherbakoff/ignite,pperalta/ignite,sk0x50/ignite,ilantukh/ignite,ryanzz/ignite,dmagda/incubator-ignite,irudyak/ignite,SharplEr/ignite,WilliamDo/ignite,afinka77/ignite,ptupitsyn/ignite,sylentprayer/ignite,vadopolski/ignite,xtern/ignite,ryanzz/ignite,murador/ignite,StalkXT/ignite,kromulan/ignite,xtern/ignite,dream-x/ignite,gargvish/ignite,thuTom/ignite,gargvish/ignite,vldpyatkov/ignite,apache/ignite,chandresh-pancholi/ignite,afinka77/ignite,tkpanther/ignite,NSAmelchev/ignite,kidaa/incubator-ignite,BiryukovVA/ignite,abhishek-ch/incubator-ignite,VladimirErshov/ignite,apacheignite/ignite,zzcclp/ignite,avinogradovgg/ignite,daradurvs/ignite,rfqu/ignite,sylentprayer/ignite,alexzaitzev/ignite,ryanzz/ignite,psadusumilli/ignite,BiryukovVA/ignite,akuznetsov-gridgain/ignite,SomeFire/ignite,vsisko/incubator-ignite,nivanov/ignite,akuznetsov-gridgain/ignite,agura/incubator-ignite,amirakhmedov/ignite,ptupitsyn/ignite,voipp/ignite,alexzaitzev/ignite,rfqu/ignite,vladisav/ignite,shroman/ignite,psadusumilli/ignite,shurun19851206/ignite,ntikhonov/ignite,alexzaitzev/ignite,shurun19851206/ignite,NSAmelchev/ignite,nizhikov/ignite,shroman/ignite,shroman/ignite,ptupitsyn/ignite,DoudTechData/ignite,pperalta/ignite,dream-x/ignite,iveselovskiy/ignite,nizhikov/ignite,svladykin/ignite,SomeFire/ignite,gridgain/apache-ignite,a1vanov/ignite,SomeFire/ignite,vladisav/ignite,avinogradovgg/ignite,voipp/ignite,WilliamDo/ignite,WilliamDo/ignite,svladykin/ignite,wmz7year/ignite,agoncharuk/ignite,afinka77/ignite,dlnufox/ignite,ashutakGG/incubator-ignite,ntikhonov/ignite,endian675/ignite,shurun19851206/ignite,amirakhmedov/ignite,alexzaitzev/ignite,zzcclp/ignite,f7753/ignite,svladykin/ignite,rfqu/ignite,afinka77/ignite,dlnufox/ignite,DoudTechData/ignite,adeelmahmood/ignite,tkpanther/ignite,agoncharuk/ignite,leveyj/ignite,f7753/ignite,voipp/ignite,voipp/ignite,iveselovskiy/ignite,adeelmahmood/ignite,rfqu/ignite,daradurvs/ignite,vsuslov/incubator-ignite,ryanzz/ignite,endian675/ignite,wmz7year/ignite,amirakhmedov/ignite,iveselovskiy/ignite,agura/incubator-ignite,vsisko/incubator-ignite,vldpyatkov/ignite,SomeFire/ignite,gargvish/ignite,ryanzz/ignite,DoudTechData/ignite,StalkXT/ignite,gargvish/ignite,apacheignite/ignite,avinogradovgg/ignite,sk0x50/ignite,DoudTechData/ignite,tkpanther/ignite,apache/ignite,samaitra/ignite,vsisko/incubator-ignite,kidaa/incubator-ignite,afinka77/ignite,arijitt/incubator-ignite,StalkXT/ignite,SharplEr/ignite,DoudTechData/ignite,louishust/incubator-ignite,nizhikov/ignite,sylentprayer/ignite,chandresh-pancholi/ignite,DoudTechData/ignite,apache/ignite,SharplEr/ignite,endian675/ignite,daradurvs/ignite,alexzaitzev/ignite,kromulan/ignite,arijitt/incubator-ignite,daradurvs/ignite,amirakhmedov/ignite,apacheignite/ignite,a1vanov/ignite,kidaa/incubator-ignite,vladisav/ignite,shroman/ignite,iveselovskiy/ignite,ascherbakoff/ignite,daradurvs/ignite,f7753/ignite,ilantukh/ignite,ntikhonov/ignite,abhishek-ch/incubator-ignite,vsuslov/incubator-ignite,svladykin/ignite,sk0x50/ignite,andrey-kuznetsov/ignite,psadusumilli/ignite,BiryukovVA/ignite,samaitra/ignite,shurun19851206/ignite,ashutakGG/incubator-ignite,kromulan/ignite,abhishek-ch/incubator-ignite,shurun19851206/ignite,SomeFire/ignite,mcherkasov/ignite,vsisko/incubator-ignite,samaitra/ignite,WilliamDo/ignite,nivanov/ignite,agoncharuk/ignite,ptupitsyn/ignite,ptupitsyn/ignite,dream-x/ignite,nivanov/ignite,gargvish/ignite,mcherkasov/ignite,gridgain/apache-ignite,rfqu/ignite,leveyj/ignite,pperalta/ignite,thuTom/ignite,agura/incubator-ignite,nivanov/ignite,leveyj/ignite,adeelmahmood/ignite,xtern/ignite,andrey-kuznetsov/ignite,apacheignite/ignite,adeelmahmood/ignite,DoudTechData/ignite,apache/ignite,kromulan/ignite,pperalta/ignite,vldpyatkov/ignite,apache/ignite,a1vanov/ignite,xtern/ignite,murador/ignite,nivanov/ignite,ilantukh/ignite,amirakhmedov/ignite,kidaa/incubator-ignite,louishust/incubator-ignite,daradurvs/ignite,andrey-kuznetsov/ignite,rfqu/ignite,dlnufox/ignite,samaitra/ignite,vladisav/ignite,iveselovskiy/ignite,VladimirErshov/ignite,xtern/ignite,shroman/ignite,ntikhonov/ignite,pperalta/ignite,shroman/ignite,ryanzz/ignite,shurun19851206/ignite,vadopolski/ignite,adeelmahmood/ignite,irudyak/ignite,ptupitsyn/ignite,nizhikov/ignite,nivanov/ignite,chandresh-pancholi/ignite,vadopolski/ignite,pperalta/ignite,endian675/ignite,vladisav/ignite,SomeFire/ignite,louishust/incubator-ignite,tkpanther/ignite,SharplEr/ignite,louishust/incubator-ignite,psadusumilli/ignite,vsuslov/incubator-ignite,vsuslov/incubator-ignite,ashutakGG/incubator-ignite,BiryukovVA/ignite,agoncharuk/ignite,avinogradovgg/ignite,samaitra/ignite,NSAmelchev/ignite,NSAmelchev/ignite,psadusumilli/ignite,irudyak/ignite,zzcclp/ignite,nizhikov/ignite,tkpanther/ignite,WilliamDo/ignite,ptupitsyn/ignite,vsuslov/incubator-ignite,vldpyatkov/ignite,sylentprayer/ignite,apacheignite/ignite,dmagda/incubator-ignite,sk0x50/ignite,SharplEr/ignite,gridgain/apache-ignite,vadopolski/ignite,samaitra/ignite,psadusumilli/ignite,mcherkasov/ignite,adeelmahmood/ignite,SomeFire/ignite,agura/incubator-ignite,ntikhonov/ignite,irudyak/ignite,thuTom/ignite,murador/ignite,gargvish/ignite,kromulan/ignite,VladimirErshov/ignite,psadusumilli/ignite,agura/incubator-ignite,vsisko/incubator-ignite,samaitra/ignite,iveselovskiy/ignite,vadopolski/ignite,ntikhonov/ignite,avinogradovgg/ignite,ilantukh/ignite,thuTom/ignite,afinka77/ignite,dream-x/ignite,sylentprayer/ignite,voipp/ignite,arijitt/incubator-ignite,apacheignite/ignite,ascherbakoff/ignite,WilliamDo/ignite,abhishek-ch/incubator-ignite,ilantukh/ignite,gargvish/ignite,afinka77/ignite,ptupitsyn/ignite,zzcclp/ignite,BiryukovVA/ignite,sylentprayer/ignite,NSAmelchev/ignite,dream-x/ignite,shroman/ignite,a1vanov/ignite
/* @java.file.header */ /* _________ _____ __________________ _____ * __ ____/___________(_)______ /__ ____/______ ____(_)_______ * _ / __ __ ___/__ / _ __ / _ / __ _ __ `/__ / __ __ \ * / /_/ / _ / _ / / /_/ / / /_/ / / /_/ / _ / _ / / / * \____/ /_/ /_/ \_,__/ \____/ \__,_/ /_/ /_/ /_/ */ package org.gridgain.grid.kernal.processors.cache; import org.gridgain.grid.*; import org.gridgain.grid.kernal.managers.swapspace.*; import org.gridgain.grid.kernal.processors.cache.query.*; import org.gridgain.grid.kernal.processors.license.*; import org.gridgain.grid.kernal.processors.offheap.*; import org.gridgain.grid.lang.*; import org.gridgain.grid.spi.swapspace.*; import org.gridgain.grid.util.*; import org.gridgain.grid.util.lang.*; import org.gridgain.grid.util.offheap.*; import org.gridgain.grid.util.typedef.*; import org.gridgain.grid.util.typedef.internal.*; import org.jdk8.backport.*; import org.jetbrains.annotations.*; import java.lang.ref.*; import java.util.*; import java.util.concurrent.*; import static org.gridgain.grid.cache.GridCacheMemoryMode.*; import static org.gridgain.grid.events.GridEventType.*; import static org.gridgain.grid.product.GridProductEdition.*; /** * Handles all swap operations. */ public class GridCacheSwapManager<K, V> extends GridCacheManagerAdapter<K, V> { /** Swap manager. */ private GridSwapSpaceManager swapMgr; /** */ private String spaceName; /** Flag to indicate if manager is enabled. */ private final boolean enabled; /** Flag to indicate if swap is enabled. */ private boolean swapEnabled; /** Flag to indicate if offheap is enabled. */ private boolean offheapEnabled; /** Swap listeners. */ private final ConcurrentMap<Integer, Collection<GridCacheSwapListener<K, V>>> swapLsnrs = new ConcurrentHashMap8<>(); /** Swap listeners. */ private final ConcurrentMap<Integer, Collection<GridCacheSwapListener<K, V>>> offheapLsnrs = new ConcurrentHashMap8<>(); /** Offheap. */ private GridOffHeapProcessor offheap; /** Soft iterator queue. */ private final ReferenceQueue<Iterator<Map.Entry<K, V>>> itQ = new ReferenceQueue<>(); /** Soft iterator set. */ private final Collection<GridWeakIterator<Map.Entry<K, V>>> itSet = new GridConcurrentHashSet<>(); /** * @param enabled Flag to indicate if swap is enabled. */ public GridCacheSwapManager(boolean enabled) { this.enabled = enabled; } /** {@inheritDoc} */ @Override public void start0() throws GridException { spaceName = CU.swapSpaceName(cctx); swapMgr = cctx.gridSwap(); offheap = cctx.offheap(); swapEnabled = enabled && cctx.config().isSwapEnabled() && cctx.kernalContext().swap().enabled(); offheapEnabled = enabled && cctx.config().getOffHeapMaxMemory() >= 0 && (cctx.config().getMemoryMode() == ONHEAP_TIERED || cctx.config().getMemoryMode() == OFFHEAP_TIERED); if (offheapEnabled) initOffHeap(); } /** * Initializes off-heap space. */ private void initOffHeap() { // Register big data usage. GridLicenseUseRegistry.onUsage(DATA_GRID, GridOffHeapMapFactory.class); long max = cctx.config().getOffHeapMaxMemory(); long init = max > 0 ? max / 1024 : 8L * 1024L * 1024L; int parts = cctx.config().getAffinity().partitions(); GridOffHeapEvictListener lsnr = !swapEnabled && !offheapEnabled ? null : new GridOffHeapEvictListener() { private volatile boolean firstEvictWarn; @Override public void onEvict(int part, int hash, byte[] kb, byte[] vb) { try { if (!firstEvictWarn) warnFirstEvict(); writeToSwap(part, null, kb, vb); } catch (GridException e) { log.error("Failed to unmarshal off-heap entry [part=" + part + ", hash=" + hash + ']', e); } } private void warnFirstEvict() { synchronized (this) { if (firstEvictWarn) return; firstEvictWarn = true; } U.warn(log, "Off-heap evictions started. You may wish to increase 'offHeapMaxMemory' in " + "cache configuration [cache=" + cctx.name() + ", offHeapMaxMemory=" + cctx.config().getOffHeapMaxMemory() + ']', "Off-heap evictions started: " + cctx.name()); } }; offheap.create(spaceName, parts, init, max, lsnr); } /** * @return {@code True} if swap store is enabled. */ public boolean swapEnabled() { return swapEnabled; } /** * @return {@code True} if off-heap cache is enabled. */ public boolean offHeapEnabled() { return offheapEnabled; } /** * @return Swap size. * @throws GridException If failed. */ public long swapSize() throws GridException { return enabled ? swapMgr.swapSize(spaceName) : -1; } /** * Gets number of swap entries (keys). * * @return Swap keys count. * @throws GridException If failed. */ public long swapKeys() throws GridException { return enabled ? swapMgr.swapKeys(spaceName) : -1; } /** * @param part Partition. * @param key Cache key. * @param keyBytes Key bytes. * @param val Value. * @param valBytes Value bytes. * @param ver Version. * @param ttl TTL. * @param expireTime Expire time. */ private void onUnswapped(int part, K key, byte[] keyBytes, V val, byte[] valBytes, GridCacheVersion ver, long ttl, long expireTime) { onEntryUnswapped(swapLsnrs, part, key, keyBytes, val, valBytes, ver, ttl, expireTime); } /** * @param part Partition. * @param key Cache key. * @param keyBytes Key bytes. * @param val Value. * @param valBytes Value bytes. * @param ver Version. * @param ttl TTL. * @param expireTime Expire time. */ private void onOffHeaped(int part, K key, byte[] keyBytes, V val, byte[] valBytes, GridCacheVersion ver, long ttl, long expireTime) { onEntryUnswapped(offheapLsnrs, part, key, keyBytes, val, valBytes, ver, ttl, expireTime); } /** * @param part Partition. * @param key Cache key. * @param keyBytes Key bytes. * @param val Value. * @param valBytes Value bytes. * @param ver Version. * @param ttl TTL. * @param expireTime Expire time. */ private void onEntryUnswapped(ConcurrentMap<Integer, Collection<GridCacheSwapListener<K, V>>> map, int part, K key, byte[] keyBytes, V val, byte[] valBytes, GridCacheVersion ver, long ttl, long expireTime) { Collection<GridCacheSwapListener<K, V>> lsnrs = map.get(part); if (lsnrs == null) { if (log.isDebugEnabled()) log.debug("Skipping unswapped notification [key=" + key + ", part=" + part + ']'); return; } for (GridCacheSwapListener<K, V> lsnr : lsnrs) lsnr.onEntryUnswapped(part, key, keyBytes, val, valBytes, ver, ttl, expireTime); } /** * @param part Partition. * @param lsnr Listener. */ public void addSwapListener(int part, GridCacheSwapListener<K, V> lsnr) { addListener(part, swapLsnrs, lsnr); } /** * @param part Partition. * @param lsnr Listener. */ public void removeSwapListener(int part, GridCacheSwapListener<K, V> lsnr) { removeListener(part, swapLsnrs, lsnr); } /** * @param part Partition. * @param lsnr Listener. */ public void addOffHeapListener(int part, GridCacheSwapListener<K, V> lsnr) { addListener(part, offheapLsnrs, lsnr); } /** * @param part Partition. * @param lsnr Listener. */ public void removeOffHeapListener(int part, GridCacheSwapListener<K, V> lsnr) { removeListener(part, offheapLsnrs, lsnr); } /** * @param part Partition. * @param lsnr Listener. */ @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") private void addListener(int part, ConcurrentMap<Integer, Collection<GridCacheSwapListener<K, V>>> map, GridCacheSwapListener<K, V> lsnr) { Collection<GridCacheSwapListener<K, V>> lsnrs = map.get(part); while (true) { if (lsnrs != null) { synchronized (lsnrs) { if (!lsnrs.isEmpty()) { lsnrs.add(lsnr); break; } } lsnrs = swapLsnrs.remove(part, lsnrs) ? null : swapLsnrs.get(part); } else { lsnrs = new GridConcurrentHashSet<GridCacheSwapListener<K, V>>() { @Override public boolean equals(Object o) { return o == this; } }; lsnrs.add(lsnr); Collection<GridCacheSwapListener<K, V>> old = swapLsnrs.putIfAbsent(part, lsnrs); if (old == null) break; else lsnrs = old; } } } /** * @param part Partition. * @param lsnr Listener. */ @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") private void removeListener(int part, ConcurrentMap<Integer, Collection<GridCacheSwapListener<K, V>>> map, GridCacheSwapListener<K, V> lsnr) { Collection<GridCacheSwapListener<K, V>> lsnrs = map.get(part); if (lsnrs != null) { boolean empty; synchronized (lsnrs) { lsnrs.remove(lsnr); empty = lsnrs.isEmpty(); } if (empty) map.remove(part, lsnrs); } } /** * Checks iterator queue. */ @SuppressWarnings("RedundantCast") private void checkIteratorQueue() { GridWeakIterator<Map.Entry<K, V>> it; do { // NOTE: don't remove redundant cast - otherwise build fails. it = (GridWeakIterator<Map.Entry<K,V>>)(Reference<Iterator<Map.Entry<K, V>>>)itQ.poll(); try { if (it != null) it.close(); } catch (GridException e) { log.error("Failed to close iterator.", e); } finally { if (it != null) itSet.remove(it); } } while (it != null); } /** * Recreates raw swap entry (that just has been received from swap storage). * * @param e Swap entry to reconstitute. * @return Reconstituted swap entry or {@code null} if entry is obsolete. * @throws GridException If failed. */ @Nullable private GridCacheSwapEntry<V> swapEntry(GridCacheSwapEntry<V> e) throws GridException { assert e != null; checkIteratorQueue(); if (e.valueIsByteArray()) e.value((V)e.valueBytes()); else { ClassLoader ldr = e.valueClassLoaderId() != null ? cctx.deploy().getClassLoader(e.valueClassLoaderId()) : cctx.deploy().localLoader(); if (ldr == null) return null; e.value(this.<V>unmarshal(e.valueBytes(), ldr)); } return e; } /** * @param key Key to check. * @param keyBytes Key bytes to check. * @return {@code True} if key is contained. * @throws GridException If failed. */ public boolean containsKey(K key, byte[] keyBytes) throws GridException { if (!offheapEnabled && !swapEnabled) return false; checkIteratorQueue(); int part = cctx.affinity().partition(key); // First check off-heap store. if (offheapEnabled) if (offheap.contains(spaceName, part, key, keyBytes)) return true; if (swapEnabled) { assert key != null; byte[] valBytes = swapMgr.read(spaceName, new GridSwapKey(key, part, keyBytes), cctx.deploy().globalLoader()); return valBytes != null; } return false; } /** * @param key Key to read. * @param keyBytes Key bytes. * @return Value from swap or {@code null}. * @throws GridException If failed. */ @SuppressWarnings({"unchecked"}) @Nullable GridCacheSwapEntry<V> read(K key, byte[] keyBytes) throws GridException { if (!offheapEnabled && !swapEnabled) return null; checkIteratorQueue(); int part = cctx.affinity().partition(key); // First check off-heap store. if (offheapEnabled) { byte[] entryBytes = offheap.get(spaceName, part, key, keyBytes); // To unmarshal entry itself local class loader will be enough. if (entryBytes != null) return swapEntry((GridCacheSwapEntry<V>)unmarshal(entryBytes, cctx.deploy().localLoader())); } if (!swapEnabled) return null; assert key != null; byte[] valBytes = swapMgr.read(spaceName, new GridSwapKey(key, part, keyBytes), cctx.deploy().globalLoader()); if (valBytes == null) return null; // To unmarshal swap entry itself local class loader will be enough. return swapEntry((GridCacheSwapEntry<V>)unmarshal(valBytes, cctx.deploy().localLoader())); } /** * @param key Key to remove. * @param keyBytes Key bytes. * @return {@code true} if value was actually removed, {@code false} otherwise. * @throws GridException If failed. */ @SuppressWarnings({"unchecked"}) @Nullable GridCacheSwapEntry<V> readAndRemove(final K key, final byte[] keyBytes) throws GridException { if (!offheapEnabled && !swapEnabled) return null; checkIteratorQueue(); final int part = cctx.affinity().partition(key); // First try removing from offheap. if (offheapEnabled) { byte[] entryBytes = offheap.remove(spaceName, part, key, keyBytes); if (entryBytes != null) { // To unmarshal swap entry itself local class loader will be enough. GridCacheSwapEntry<V> entry = swapEntry((GridCacheSwapEntry<V>)unmarshal(entryBytes, cctx.deploy().localLoader())); if (entry == null) return null; // Always fire this event, since preloading depends on it. onOffHeaped(part, key, keyBytes, entry.value(), entry.valueBytes(), entry.version(), entry.ttl(), entry.expireTime()); if (cctx.events().isRecordable(EVT_CACHE_OBJECT_FROM_OFFHEAP)) cctx.events().addEvent(part, key, cctx.nodeId(), (GridUuid)null, null, EVT_CACHE_OBJECT_FROM_OFFHEAP, null, false, null, true); GridCacheQueryManager<K, V> qryMgr = cctx.queries(); if (qryMgr != null) qryMgr.onUnswap(key, entry.value(), entry.valueBytes()); return entry; } } if (swapEnabled) { final GridTuple<GridCacheSwapEntry<V>> t = F.t1(); final GridTuple<GridException> err = F.t1(); swapMgr.remove(spaceName, new GridSwapKey(key, part, keyBytes), new CI1<byte[]>() { @Override public void apply(byte[] rmv) { if (rmv != null) { try { // To unmarshal swap entry itself local class loader will be enough. GridCacheSwapEntry<V> entry = swapEntry((GridCacheSwapEntry<V>)unmarshal(rmv, cctx.deploy().localLoader())); if (entry == null) return; t.set(entry); V v = entry.value(); byte[] valBytes = entry.valueBytes(); // Event notification. if (cctx.events().isRecordable(EVT_CACHE_OBJECT_UNSWAPPED)) cctx.events().addEvent(part, key, cctx.nodeId(), (GridUuid)null, null, EVT_CACHE_OBJECT_UNSWAPPED, null, false, v, true); // Always fire this event, since preloading depends on it. onUnswapped(part, key, keyBytes, v, valBytes, entry.version(), entry.ttl(), entry.expireTime()); GridCacheQueryManager<K, V> qryMgr = cctx.queries(); if (qryMgr != null) qryMgr.onUnswap(key, v, valBytes); } catch (GridException e) { err.set(e); } } } }, cctx.deploy().globalLoader()); if (err.get() != null) throw err.get(); return t.get(); } return null; } /** * @param entry Entry to read. * @return Read value. * @throws GridException If read failed. */ @Nullable GridCacheSwapEntry<V> read(GridCacheMapEntry<K, V> entry) throws GridException { if (!offheapEnabled && !swapEnabled) return null; return read(entry.key(), entry.getOrMarshalKeyBytes()); } /** * @param key Key to read swap entry for. * @return Read value. * @throws GridException If read failed. */ @Nullable GridCacheSwapEntry<V> read(K key) throws GridException { if (!offheapEnabled && !swapEnabled) return null; return read(key, CU.marshal(cctx, key)); } /** * @param entry Entry to read. * @return Read value. * @throws GridException If read failed. */ @Nullable GridCacheSwapEntry<V> readAndRemove(GridCacheMapEntry<K, V> entry) throws GridException { if (!offheapEnabled && !swapEnabled) return null; return readAndRemove(entry.key(), entry.getOrMarshalKeyBytes()); } /** * @param keys Collection of keys to remove from swap. * @return Collection of swap entries. * @throws GridException If failed, */ public Collection<GridCacheBatchSwapEntry<K, V>> readAndRemove(Collection<? extends K> keys) throws GridException { if (!offheapEnabled && !swapEnabled) return Collections.emptyList(); checkIteratorQueue(); final GridCacheQueryManager<K, V> qryMgr = cctx.queries(); ArrayList<K> keysList = new ArrayList<>(keys); final Collection<GridCacheBatchSwapEntry<K, V>> res = new ArrayList<>(keys.size()); // First try removing from offheap. if (offheapEnabled) { Iterator<K> iter = keysList.iterator(); while (iter.hasNext()) { K key = iter.next(); int part = cctx.affinity().partition(key); byte[] keyBytes = CU.marshal(cctx, key); int hash = U.hash(key); byte[] entryBytes = offheap.remove(spaceName, part, key, keyBytes); if (entryBytes != null) { // To unmarshal swap entry itself local class loader will be enough. GridCacheSwapEntry<V> entry = swapEntry((GridCacheSwapEntry<V>)unmarshal(entryBytes, cctx.deploy().localLoader())); if (entry == null) continue; iter.remove(); // Always fire this event, since preloading depends on it. onOffHeaped(part, key, keyBytes, entry.value(), entry.valueBytes(), entry.version(), entry.ttl(), entry.expireTime()); if (cctx.events().isRecordable(EVT_CACHE_OBJECT_FROM_OFFHEAP)) cctx.events().addEvent(part, key, cctx.nodeId(), (GridUuid)null, null, EVT_CACHE_OBJECT_FROM_OFFHEAP, null, false, null, true); if (qryMgr != null) qryMgr.onUnswap(key, entry.value(), entry.valueBytes()); GridCacheBatchSwapEntry<K, V> unswapped = new GridCacheBatchSwapEntry<>(key, keyBytes, hash, part, entry.valueBytes(),entry.valueIsByteArray(), entry.version(), entry.ttl(), entry.expireTime(), entry.keyClassLoaderId(), entry.valueClassLoaderId()); unswapped.value(entry.value()); res.add(unswapped); } } if (!swapEnabled || keysList.isEmpty()) return res; } // Swap is enabled. final GridTuple<GridException> err = F.t1(); Collection<GridSwapKey> converted = new ArrayList<>(F.viewReadOnly(keysList, new C1<K, GridSwapKey>() { @Override public GridSwapKey apply(K key) { try { return new GridSwapKey(key, cctx.affinity().partition(key), CU.marshal(cctx, key)); } catch (GridException e) { throw new GridRuntimeException(e); } } })); swapMgr.removeAll(spaceName, converted, new GridBiInClosure<GridSwapKey, byte[]>() { @Override public void apply(GridSwapKey swapKey, byte[] rmv) { if (rmv != null) { try { // To unmarshal swap entry itself local class loader will be enough. GridCacheSwapEntry<V> entry = swapEntry((GridCacheSwapEntry<V>)unmarshal(rmv, cctx.deploy().localLoader())); if (entry == null) return; K key = (K)swapKey.key(); GridCacheBatchSwapEntry<K, V> unswapped = new GridCacheBatchSwapEntry<>(key, swapKey.keyBytes(), U.hash(key), swapKey.partition(), entry.valueBytes(), entry.valueIsByteArray(), entry.version(), entry.ttl(), entry.expireTime(), entry.keyClassLoaderId(), entry.valueClassLoaderId()); unswapped.value(entry.value()); res.add(unswapped); // Event notification. if (cctx.events().isRecordable(EVT_CACHE_OBJECT_UNSWAPPED)) cctx.events().addEvent(swapKey.partition(), key, cctx.nodeId(), (GridUuid)null, null, EVT_CACHE_OBJECT_UNSWAPPED, null, false, entry.value(), true); // Always fire this event, since preloading depends on it. onUnswapped(swapKey.partition(), key, swapKey.keyBytes(), entry.value(), entry.valueBytes(), entry.version(), entry.ttl(), entry.expireTime()); if (qryMgr != null) qryMgr.onUnswap(key, entry.value(), entry.valueBytes()); } catch (GridException e) { err.set(e); } } } }, cctx.deploy().globalLoader()); if (err.get() != null) throw err.get(); return res; } /** * @param key Key to read swap entry for. * @return Read value. * @throws GridException If read failed. */ @Nullable GridCacheSwapEntry<V> readAndRemove(K key) throws GridException { if (!offheapEnabled && !swapEnabled) return null; return readAndRemove(key, CU.marshal(cctx, key)); } /** * @param key Key to remove. * @param keyBytes Key bytes. * @throws GridException If failed. */ void remove(final K key, byte[] keyBytes) throws GridException { if (!offheapEnabled && !swapEnabled) return; checkIteratorQueue(); final GridCacheQueryManager<K, V> qryMgr = cctx.queries(); CI1<byte[]> c = qryMgr == null ? null : new CI1<byte[]>() { @Override public void apply(byte[] rmv) { if (rmv == null) return; try { // To unmarshal swap entry itself local class loader will be enough. GridCacheSwapEntry<V> entry = swapEntry((GridCacheSwapEntry<V>)unmarshal(rmv, cctx.deploy().localLoader())); if (entry == null) return; qryMgr.onUnswap(key, entry.value(), entry.valueBytes()); } catch (GridException e) { throw new GridRuntimeException(e); } } }; int part = cctx.affinity().partition(key); // First try offheap. if (offheapEnabled) { byte[] val = offheap.remove(spaceName, part, key, keyBytes); if (val != null) { if (c != null) c.apply(val); // Probably we should read value and apply closure before removing... return; } } if (swapEnabled) swapMgr.remove(spaceName, new GridSwapKey(key, part, keyBytes), c, cctx.deploy().globalLoader()); } /** * Writes a versioned value to swap. * * @param key Key. * @param keyBytes Key bytes. * @param keyHash Key hash. * @param val Value. * @param valIsByteArr Whether value is byte array. * @param ver Version. * @param ttl Entry time to live. * @param expireTime Swap entry expiration time. * @param keyClsLdrId Class loader ID for entry key. * @param valClsLdrId Class loader ID for entry value. * @throws GridException If failed. */ void write(K key, byte[] keyBytes, int keyHash, byte[] val, boolean valIsByteArr, GridCacheVersion ver, long ttl, long expireTime, @Nullable GridUuid keyClsLdrId, @Nullable GridUuid valClsLdrId) throws GridException { if (!offheapEnabled && !swapEnabled) return; checkIteratorQueue(); int part = cctx.affinity().partition(key); if (offheapEnabled) { GridCacheSwapEntry<V> entry = new GridCacheSwapEntry<>(keyHash, val, valIsByteArr, ver, ttl, expireTime, keyClsLdrId, valClsLdrId); offheap.put(spaceName, part, key, keyBytes, marshal(entry)); if (cctx.events().isRecordable(EVT_CACHE_OBJECT_TO_OFFHEAP)) cctx.events().addEvent(part, key, cctx.nodeId(), (GridUuid)null, null, EVT_CACHE_OBJECT_TO_OFFHEAP, null, false, null, true); } else if (swapEnabled) { GridCacheSwapEntry<V> entry = new GridCacheSwapEntry<>(keyHash, val, valIsByteArr, ver, ttl, expireTime, keyClsLdrId, valClsLdrId); writeToSwap(part, key, keyBytes, marshal(entry)); } GridCacheQueryManager<K, V> qryMgr = cctx.queries(); if (qryMgr != null) qryMgr.onSwap(spaceName, key); } /** * Performs batch write of swapped entries. * * @param swapped Collection of swapped entries. * @throws GridException If failed. */ void writeAll(Iterable<GridCacheBatchSwapEntry<K, V>> swapped) throws GridException { assert offheapEnabled || swapEnabled; checkIteratorQueue(); GridCacheQueryManager<K, V> qryMgr = cctx.queries(); if (offheapEnabled) { for (GridCacheBatchSwapEntry<K, V> swapEntry : swapped) { offheap.put(spaceName, swapEntry.partition(), swapEntry.key(), swapEntry.keyBytes(), marshal(swapEntry)); if (cctx.events().isRecordable(EVT_CACHE_OBJECT_TO_OFFHEAP)) cctx.events().addEvent(swapEntry.partition(), swapEntry.key(), cctx.nodeId(), (GridUuid)null, null, EVT_CACHE_OBJECT_TO_OFFHEAP, null, false, null, true); if (qryMgr != null) qryMgr.onSwap(spaceName, swapEntry.key()); } } else { // Swap enabled. swapMgr.writeAll(spaceName, swapped, cctx.deploy().globalLoader()); if (cctx.events().isRecordable(EVT_CACHE_OBJECT_SWAPPED)) { for (GridCacheBatchSwapEntry<K, V> batchSwapEntry : swapped) { cctx.events().addEvent(batchSwapEntry.partition(), batchSwapEntry.key(), cctx.nodeId(), (GridUuid)null, null, EVT_CACHE_OBJECT_SWAPPED, null, false, null, true); if (qryMgr != null) qryMgr.onSwap(spaceName, batchSwapEntry.key()); } } } } /** * Writes given bytes to swap. * * @param part Partition. * @param key Key. If {@code null} then it will be deserialized from {@code keyBytes}. * @param keyBytes Key bytes. * @param entry Entry bytes. * @throws GridException If failed. */ private void writeToSwap(int part, @Nullable K key, byte[] keyBytes, byte[] entry) throws GridException{ checkIteratorQueue(); if (key == null) key = unmarshal(keyBytes, cctx.deploy().globalLoader()); swapMgr.write(spaceName, new GridSwapKey(key, part, keyBytes), entry, cctx.deploy().globalLoader()); if (cctx.events().isRecordable(EVT_CACHE_OBJECT_SWAPPED)) cctx.events().addEvent(part, key, cctx.nodeId(), (GridUuid)null, null, EVT_CACHE_OBJECT_SWAPPED, null, false, null, true); } /** * Clears off-heap. */ public void clearOffHeap() { if (offheapEnabled) initOffHeap(); } /** * Clears swap. * * @throws GridException If failed. */ public void clearSwap() throws GridException { if (swapEnabled) swapMgr.clear(spaceName); } /** * Gets offheap and swap iterator over partition. * * @param part Partition to iterate over. * @return Iterator over partition. * @throws GridException If failed. */ @Nullable public GridCloseableIterator<Map.Entry<byte[], GridCacheSwapEntry<V>>> iterator(final int part) throws GridException { if (!swapEnabled() && !offHeapEnabled()) return null; checkIteratorQueue(); if (offHeapEnabled() && !swapEnabled()) return offHeapIterator(part); if (swapEnabled() && !offHeapEnabled()) return swapIterator(part); // Both, swap and off-heap are enabled. return new GridCloseableIteratorAdapter<Map.Entry<byte[], GridCacheSwapEntry<V>>>() { private GridCloseableIterator<Map.Entry<byte[], GridCacheSwapEntry<V>>> it; private boolean offheap = true; private boolean done; { it = offHeapIterator(part); advance(); } private void advance() throws GridException { if (it != null && it.hasNext()) return; if (it != null) it.close(); if (offheap) { offheap = false; it = swapIterator(part); if (!it.hasNext()) { it.close(); done = true; } } else done = true; } @Override protected Map.Entry<byte[], GridCacheSwapEntry<V>> onNext() throws GridException { if (done) throw new NoSuchElementException(); Map.Entry<byte[], GridCacheSwapEntry<V>> e = it.next(); advance(); return e; } @Override protected boolean onHasNext() { return !done; } @Override protected void onRemove() { throw new UnsupportedOperationException(); } @Override protected void onClose() throws GridException { if (it != null) it.close(); } }; } /** * Gets offheap and swap iterator over partition. * * @return Iterator over partition. * @throws GridException If failed. */ @Nullable public GridCloseableIterator<Map.Entry<byte[], byte[]>> rawIterator() throws GridException { if (!swapEnabled() && !offHeapEnabled()) return new GridEmptyCloseableIterator<>(); checkIteratorQueue(); if (offHeapEnabled() && !swapEnabled()) return rawOffHeapIterator(); if (swapEnabled() && !offHeapEnabled()) return rawSwapIterator(); // Both, swap and off-heap are enabled. return new GridCloseableIteratorAdapter<Map.Entry<byte[], byte[]>>() { private GridCloseableIterator<Map.Entry<byte[], byte[]>> it; private boolean offheapFlag = true; private boolean done; private Map.Entry<byte[], byte[]> cur; { it = rawOffHeapIterator(); if (it == null || !it.hasNext()) { it.close(); offheapFlag = false; } advance(); } private void advance() throws GridException { if (it.hasNext()) return; it.close(); if (offheapFlag) { offheapFlag = false; it = rawSwapIterator(); if (it == null || !it.hasNext()) { it.close(); done = true; } } else done = true; } @Override protected Map.Entry<byte[], byte[]> onNext() throws GridException { if (done) throw new NoSuchElementException(); cur = it.next(); advance(); return cur; } @Override protected boolean onHasNext() { return !done; } @Override protected void onRemove() throws GridException { if (offheapFlag) { K key = unmarshal(cur.getKey(), cctx.deploy().globalLoader()); int part = cctx.affinity().partition(key); offheap.removex(spaceName, part, key, cur.getKey()); } else it.removeX(); } @Override protected void onClose() throws GridException { if (it != null) it.close(); } }; } /** * @return Lazy swap iterator. * @throws GridException If failed. */ public Iterator<Map.Entry<K, V>> lazySwapIterator() throws GridException { if (!swapEnabled) return new GridEmptyIterator<>(); return lazyIterator(cctx.gridSwap().rawIterator(spaceName)); } /** * @return Lazy off-heap iterator. */ public Iterator<Map.Entry<K, V>> lazyOffHeapIterator() { if (!offheapEnabled) return new GridEmptyCloseableIterator<>(); return lazyIterator(offheap.iterator(spaceName)); } /** * Gets number of elements in off-heap * * @return Number of elements or {@code 0} if off-heap is disabled. */ public long offHeapEntriesCount() { return offheapEnabled ? offheap.entriesCount(spaceName) : 0; } /** * Gets memory size allocated in off-heap. * * @return Allocated memory size or {@code 0} if off-heap is disabled. */ public long offHeapAllocatedSize() { return offheapEnabled ? offheap.allocatedSize(spaceName) : 0; } /** * Gets lazy iterator for which key and value are lazily deserialized. * * @param it Closeable iterator. * @return Lazy iterator. */ private Iterator<Map.Entry<K, V>> lazyIterator( final GridCloseableIterator<? extends Map.Entry<byte[], byte[]>> it) { if (it == null) return new GridEmptyIterator<>(); checkIteratorQueue(); // Weak reference will hold hard reference to this iterator, so it can properly be closed. final GridCloseableIteratorAdapter<Map.Entry<K, V>> iter = new GridCloseableIteratorAdapter<Map.Entry<K, V>>() { private Map.Entry<K, V> cur; @Override protected Map.Entry<K, V> onNext() { final Map.Entry<byte[], byte[]> cur0 = it.next(); cur = new Map.Entry<K, V>() { @Override public K getKey() { try { return unmarshal(cur0.getKey(), cctx.deploy().globalLoader()); } catch (GridException e) { throw new GridRuntimeException(e); } } @Override public V getValue() { try { GridCacheSwapEntry<V> e = unmarshal(cur0.getValue(), cctx.deploy().localLoader()); swapEntry(e); return e.value(); } catch (GridException ex) { throw new GridRuntimeException(ex); } } @Override public V setValue(V val) { throw new UnsupportedOperationException(); } }; return cur; } @Override protected boolean onHasNext() { return it.hasNext(); } @Override protected void onRemove() throws GridException { if (cur == null) throw new IllegalStateException("Method next() has not yet been called, or the remove() method " + "has already been called after the last call to the next() method."); try { if (cctx.isDht()) cctx.dht().near().removex(cur.getKey(), CU.<K, V>empty()); else cctx.cache().removex(cur.getKey(), CU.<K, V>empty()); } finally { cur = null; } } @Override protected void onClose() throws GridException { it.close(); } }; // Don't hold hard reference to this iterator - only weak one. Iterator<Map.Entry<K, V>> ret = new Iterator<Map.Entry<K, V>>() { @Override public boolean hasNext() { return iter.hasNext(); } @Override public Map.Entry<K, V> next() { return iter.next(); } @Override public void remove() { iter.remove(); } }; itSet.add(new GridWeakIterator<>(ret, iter, itQ)); return ret; } /** * Gets offheap iterator over partition. * * @param part Partition to iterate over. * @return Iterator over partition. * @throws GridException If failed. */ @Nullable public GridCloseableIterator<Map.Entry<byte[], GridCacheSwapEntry<V>>> offHeapIterator(int part) throws GridException { if (!offheapEnabled) return null; checkIteratorQueue(); return new IteratorWrapper(offheap.iterator(spaceName, part)); } /** * @return Raw off-heap iterator. */ private GridCloseableIterator<Map.Entry<byte[], byte[]>> rawOffHeapIterator() { if (!offheapEnabled) return new GridEmptyCloseableIterator<>(); return new GridCloseableIteratorAdapter<Map.Entry<byte[], byte[]>>() { private GridCloseableIterator<GridBiTuple<byte[], byte[]>> it = offheap.iterator(spaceName); private Map.Entry<byte[], byte[]> cur; @Override protected Map.Entry<byte[], byte[]> onNext() { return cur = it.next(); } @Override protected boolean onHasNext() { return it.hasNext(); } @Override protected void onRemove() throws GridException { K key = unmarshal(cur.getKey(), cctx.deploy().globalLoader()); int part = cctx.affinity().partition(key); offheap.removex(spaceName, part, key, cur.getKey()); } @Override protected void onClose() throws GridException { it.close(); } }; } /** * Gets swap space iterator over partition. * * @param part Partition to iterate over. * @return Iterator over partition. * @throws GridException If failed. */ @Nullable public GridCloseableIterator<Map.Entry<byte[], GridCacheSwapEntry<V>>> swapIterator(int part) throws GridException { if (!swapEnabled) return null; checkIteratorQueue(); return new IteratorWrapper(swapMgr.rawIterator(spaceName, part)); } /** * @return Raw off-heap iterator. * @throws GridException If failed. */ private GridCloseableIterator<Map.Entry<byte[], byte[]>> rawSwapIterator() throws GridException { if (!swapEnabled) return new GridEmptyCloseableIterator<>(); checkIteratorQueue(); return swapMgr.rawIterator(spaceName); } /** * @param leftNodeId Left Node ID. * @param ldr Undeployed class loader. * @return Undeploy count. */ public int onUndeploy(UUID leftNodeId, ClassLoader ldr) { GridUuid ldrId = cctx.deploy().getClassLoaderId(ldr); assert ldrId != null; checkIteratorQueue(); try { GridCloseableIterator<Map.Entry<byte[], byte[]>> iter = rawIterator(); if (iter != null) { int undeployCnt = 0; try { ClassLoader locLdr = cctx.deploy().localLoader(); for (Map.Entry<byte[], byte[]> e : iter) { try { GridCacheSwapEntry<V> swapEntry = unmarshal(e.getValue(), locLdr); GridUuid valLdrId = swapEntry.valueClassLoaderId(); if (ldrId.equals(swapEntry.keyClassLoaderId())) { iter.removeX(); undeployCnt++; } else { if (valLdrId == null && swapEntry.value() == null && !swapEntry.valueIsByteArray()) { // We need value here only for classloading purposes. V val = cctx.marshaller().unmarshal(swapEntry.valueBytes(), cctx.deploy().globalLoader()); if (val != null) valLdrId = cctx.deploy().getClassLoaderId(val.getClass().getClassLoader()); } if (ldrId.equals(valLdrId)) { iter.removeX(); undeployCnt++; } } } catch (GridException ex) { U.error(log, "Failed to process swap entry.", ex); } } } finally { iter.close(); } return undeployCnt; } } catch (GridException e) { U.error(log, "Failed to clear cache swap space on undeploy.", e); } return 0; } /** * @param bytes Bytes to unmarshal. * @param ldr Class loader. * @return Unmarshalled value. * @throws GridException If unmarshal failed. */ private <T> T unmarshal(byte[] bytes, ClassLoader ldr) throws GridException { return cctx.marshaller().unmarshal(bytes, ldr); } /** * @param obj Object to marshal. * @return Marshalled byte array. * @throws GridException If marshalling failed. */ private byte[] marshal(Object obj) throws GridException { return cctx.marshaller().marshal(obj); } /** * @return Size of internal weak iterator set. */ int iteratorSetSize() { return itSet.size(); } /** * */ private class IteratorWrapper extends GridCloseableIteratorAdapter<Map.Entry<byte[], GridCacheSwapEntry<V>>> { /** */ private static final long serialVersionUID = 0L; /** */ private final GridCloseableIterator<? extends Map.Entry<byte[], byte[]>> iter; /** * @param iter Iterator. */ private IteratorWrapper(GridCloseableIterator<? extends Map.Entry<byte[], byte[]>> iter) { assert iter != null; this.iter = iter; } /** {@inheritDoc} */ @Override protected Map.Entry<byte[], GridCacheSwapEntry<V>> onNext() throws GridException { Map.Entry<byte[], byte[]> e = iter.nextX(); // To unmarshal swap entry itself local class loader will be enough. return F.t(e.getKey(), (GridCacheSwapEntry<V>)unmarshal(e.getValue(), cctx.deploy().localLoader())); } /** {@inheritDoc} */ @Override protected boolean onHasNext() throws GridException { return iter.hasNext(); } /** {@inheritDoc} */ @Override protected void onClose() throws GridException { iter.close(); } /** {@inheritDoc} */ @Override protected void onRemove() { iter.remove(); } } }
modules/core/src/main/java/org/gridgain/grid/kernal/processors/cache/GridCacheSwapManager.java
/* @java.file.header */ /* _________ _____ __________________ _____ * __ ____/___________(_)______ /__ ____/______ ____(_)_______ * _ / __ __ ___/__ / _ __ / _ / __ _ __ `/__ / __ __ \ * / /_/ / _ / _ / / /_/ / / /_/ / / /_/ / _ / _ / / / * \____/ /_/ /_/ \_,__/ \____/ \__,_/ /_/ /_/ /_/ */ package org.gridgain.grid.kernal.processors.cache; import org.gridgain.grid.*; import org.gridgain.grid.kernal.managers.swapspace.*; import org.gridgain.grid.kernal.processors.cache.query.*; import org.gridgain.grid.kernal.processors.license.*; import org.gridgain.grid.kernal.processors.offheap.*; import org.gridgain.grid.lang.*; import org.gridgain.grid.spi.swapspace.*; import org.gridgain.grid.util.*; import org.gridgain.grid.util.lang.*; import org.gridgain.grid.util.offheap.*; import org.gridgain.grid.util.typedef.*; import org.gridgain.grid.util.typedef.internal.*; import org.jdk8.backport.*; import org.jetbrains.annotations.*; import java.lang.ref.*; import java.util.*; import java.util.concurrent.*; import static org.gridgain.grid.cache.GridCacheMemoryMode.*; import static org.gridgain.grid.events.GridEventType.*; import static org.gridgain.grid.product.GridProductEdition.*; /** * Handles all swap operations. */ public class GridCacheSwapManager<K, V> extends GridCacheManagerAdapter<K, V> { /** Swap manager. */ private GridSwapSpaceManager swapMgr; /** */ private String spaceName; /** Flag to indicate if manager is enabled. */ private final boolean enabled; /** Flag to indicate if swap is enabled. */ private boolean swapEnabled; /** Flag to indicate if offheap is enabled. */ private boolean offheapEnabled; /** Swap listeners. */ private final ConcurrentMap<Integer, Collection<GridCacheSwapListener<K, V>>> swapLsnrs = new ConcurrentHashMap8<>(); /** Swap listeners. */ private final ConcurrentMap<Integer, Collection<GridCacheSwapListener<K, V>>> offheapLsnrs = new ConcurrentHashMap8<>(); /** Offheap. */ private GridOffHeapProcessor offheap; /** Soft iterator queue. */ private final ReferenceQueue<Iterator<Map.Entry<K, V>>> itQ = new ReferenceQueue<>(); /** Soft iterator set. */ private final Collection<GridWeakIterator<Map.Entry<K, V>>> itSet = new GridConcurrentHashSet<>(); /** * @param enabled Flag to indicate if swap is enabled. */ public GridCacheSwapManager(boolean enabled) { this.enabled = enabled; } /** {@inheritDoc} */ @Override public void start0() throws GridException { spaceName = CU.swapSpaceName(cctx); swapMgr = cctx.gridSwap(); offheap = cctx.offheap(); swapEnabled = enabled && cctx.config().isSwapEnabled() && cctx.kernalContext().swap().enabled(); offheapEnabled = enabled && cctx.config().getOffHeapMaxMemory() >= 0 && (cctx.config().getMemoryMode() == ONHEAP_TIERED || cctx.config().getMemoryMode() == OFFHEAP_TIERED); if (offheapEnabled) initOffHeap(); } /** * Initializes off-heap space. */ private void initOffHeap() { // Register big data usage. GridLicenseUseRegistry.onUsage(DATA_GRID, GridOffHeapMapFactory.class); long max = cctx.config().getOffHeapMaxMemory(); long init = max > 0 ? max / 1024 : 8L * 1024L * 1024L; int parts = cctx.config().getAffinity().partitions(); GridOffHeapEvictListener lsnr = !swapEnabled && !offheapEnabled ? null : new GridOffHeapEvictListener() { private volatile boolean firstEvictWarn; @Override public void onEvict(int part, int hash, byte[] kb, byte[] vb) { try { if (!firstEvictWarn) warnFirstEvict(); writeToSwap(part, null, kb, vb); } catch (GridException e) { log.error("Failed to unmarshal off-heap entry [part=" + part + ", hash=" + hash + ']', e); } } private void warnFirstEvict() { synchronized (this) { if (firstEvictWarn) return; firstEvictWarn = true; } U.warn(log, "Off-heap evictions started. You may wish to increase 'offHeapMaxMemory' in " + "cache configuration [cache=" + cctx.name() + ", offHeapMaxMemory=" + cctx.config().getOffHeapMaxMemory() + ']', "Off-heap evictions started: " + cctx.name()); } }; offheap.create(spaceName, parts, init, max, lsnr); } /** * @return {@code True} if swap store is enabled. */ public boolean swapEnabled() { return swapEnabled; } /** * @return {@code True} if off-heap cache is enabled. */ public boolean offHeapEnabled() { return offheapEnabled; } /** * @return Swap size. * @throws GridException If failed. */ public long swapSize() throws GridException { return enabled ? swapMgr.swapSize(spaceName) : -1; } /** * Gets number of swap entries (keys). * * @return Swap keys count. * @throws GridException If failed. */ public long swapKeys() throws GridException { return enabled ? swapMgr.swapKeys(spaceName) : -1; } /** * @param part Partition. * @param key Cache key. * @param keyBytes Key bytes. * @param val Value. * @param valBytes Value bytes. * @param ver Version. * @param ttl TTL. * @param expireTime Expire time. */ private void onUnswapped(int part, K key, byte[] keyBytes, V val, byte[] valBytes, GridCacheVersion ver, long ttl, long expireTime) { onEntryUnswapped(swapLsnrs, part, key, keyBytes, val, valBytes, ver, ttl, expireTime); } /** * @param part Partition. * @param key Cache key. * @param keyBytes Key bytes. * @param val Value. * @param valBytes Value bytes. * @param ver Version. * @param ttl TTL. * @param expireTime Expire time. */ private void onOffHeaped(int part, K key, byte[] keyBytes, V val, byte[] valBytes, GridCacheVersion ver, long ttl, long expireTime) { onEntryUnswapped(offheapLsnrs, part, key, keyBytes, val, valBytes, ver, ttl, expireTime); } /** * @param part Partition. * @param key Cache key. * @param keyBytes Key bytes. * @param val Value. * @param valBytes Value bytes. * @param ver Version. * @param ttl TTL. * @param expireTime Expire time. */ private void onEntryUnswapped(ConcurrentMap<Integer, Collection<GridCacheSwapListener<K, V>>> map, int part, K key, byte[] keyBytes, V val, byte[] valBytes, GridCacheVersion ver, long ttl, long expireTime) { Collection<GridCacheSwapListener<K, V>> lsnrs = map.get(part); if (lsnrs == null) { if (log.isDebugEnabled()) log.debug("Skipping unswapped notification [key=" + key + ", part=" + part + ']'); return; } for (GridCacheSwapListener<K, V> lsnr : lsnrs) lsnr.onEntryUnswapped(part, key, keyBytes, val, valBytes, ver, ttl, expireTime); } /** * @param part Partition. * @param lsnr Listener. */ public void addSwapListener(int part, GridCacheSwapListener<K, V> lsnr) { addListener(part, swapLsnrs, lsnr); } /** * @param part Partition. * @param lsnr Listener. */ public void removeSwapListener(int part, GridCacheSwapListener<K, V> lsnr) { removeListener(part, swapLsnrs, lsnr); } /** * @param part Partition. * @param lsnr Listener. */ public void addOffHeapListener(int part, GridCacheSwapListener<K, V> lsnr) { addListener(part, offheapLsnrs, lsnr); } /** * @param part Partition. * @param lsnr Listener. */ public void removeOffHeapListener(int part, GridCacheSwapListener<K, V> lsnr) { removeListener(part, offheapLsnrs, lsnr); } /** * @param part Partition. * @param lsnr Listener. */ @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") private void addListener(int part, ConcurrentMap<Integer, Collection<GridCacheSwapListener<K, V>>> map, GridCacheSwapListener<K, V> lsnr) { Collection<GridCacheSwapListener<K, V>> lsnrs = map.get(part); while (true) { if (lsnrs != null) { synchronized (lsnrs) { if (!lsnrs.isEmpty()) { lsnrs.add(lsnr); break; } } lsnrs = swapLsnrs.remove(part, lsnrs) ? null : swapLsnrs.get(part); } else { lsnrs = new GridConcurrentHashSet<GridCacheSwapListener<K, V>>() { @Override public boolean equals(Object o) { return o == this; } }; lsnrs.add(lsnr); Collection<GridCacheSwapListener<K, V>> old = swapLsnrs.putIfAbsent(part, lsnrs); if (old == null) break; else lsnrs = old; } } } /** * @param part Partition. * @param lsnr Listener. */ @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") private void removeListener(int part, ConcurrentMap<Integer, Collection<GridCacheSwapListener<K, V>>> map, GridCacheSwapListener<K, V> lsnr) { Collection<GridCacheSwapListener<K, V>> lsnrs = map.get(part); if (lsnrs != null) { boolean empty; synchronized (lsnrs) { lsnrs.remove(lsnr); empty = lsnrs.isEmpty(); } if (empty) map.remove(part, lsnrs); } } /** * Checks iterator queue. */ @SuppressWarnings("RedundantCast") private void checkIteratorQueue() { GridWeakIterator<Map.Entry<K, V>> it; do { // NOTE: don't remove redundant cast - otherwise build fails. it = (GridWeakIterator<Map.Entry<K,V>>)(Reference<Iterator<Map.Entry<K, V>>>)itQ.poll(); try { if (it != null) it.close(); } catch (GridException e) { log.error("Failed to close iterator.", e); } finally { if (it != null) itSet.remove(it); } } while (it != null); } /** * Recreates raw swap entry (that just has been received from swap storage). * * @param e Swap entry to reconstitute. * @return Reconstituted swap entry or {@code null} if entry is obsolete. * @throws GridException If failed. */ @Nullable private GridCacheSwapEntry<V> swapEntry(GridCacheSwapEntry<V> e) throws GridException { assert e != null; checkIteratorQueue(); if (e.valueIsByteArray()) e.value((V)e.valueBytes()); else { ClassLoader ldr = e.valueClassLoaderId() != null ? cctx.deploy().getClassLoader(e.valueClassLoaderId()) : cctx.deploy().localLoader(); if (ldr == null) return null; e.value(this.<V>unmarshal(e.valueBytes(), ldr)); } return e; } /** * @param key Key to check. * @param keyBytes Key bytes to check. * @return {@code True} if key is contained. * @throws GridException If failed. */ public boolean containsKey(K key, byte[] keyBytes) throws GridException { if (!offheapEnabled && !swapEnabled) return false; checkIteratorQueue(); int part = cctx.affinity().partition(key); // First check off-heap store. if (offheapEnabled) if (offheap.contains(spaceName, part, key, keyBytes)) return true; if (swapEnabled) { assert key != null; byte[] valBytes = swapMgr.read(spaceName, new GridSwapKey(key, part, keyBytes), cctx.deploy().globalLoader()); return valBytes != null; } return false; } /** * @param key Key to read. * @param keyBytes Key bytes. * @return Value from swap or {@code null}. * @throws GridException If failed. */ @SuppressWarnings({"unchecked"}) @Nullable GridCacheSwapEntry<V> read(K key, byte[] keyBytes) throws GridException { if (!offheapEnabled && !swapEnabled) return null; checkIteratorQueue(); int part = cctx.affinity().partition(key); // First check off-heap store. if (offheapEnabled) { byte[] entryBytes = offheap.get(spaceName, part, key, keyBytes); // To unmarshal entry itself local class loader will be enough. if (entryBytes != null) return swapEntry((GridCacheSwapEntry<V>)unmarshal(entryBytes, cctx.deploy().localLoader())); } if (!swapEnabled) return null; assert key != null; byte[] valBytes = swapMgr.read(spaceName, new GridSwapKey(key, part, keyBytes), cctx.deploy().globalLoader()); if (valBytes == null) return null; // To unmarshal swap entry itself local class loader will be enough. return swapEntry((GridCacheSwapEntry<V>)unmarshal(valBytes, cctx.deploy().localLoader())); } /** * @param key Key to remove. * @param keyBytes Key bytes. * @return {@code true} if value was actually removed, {@code false} otherwise. * @throws GridException If failed. */ @SuppressWarnings({"unchecked"}) @Nullable GridCacheSwapEntry<V> readAndRemove(final K key, final byte[] keyBytes) throws GridException { if (!offheapEnabled && !swapEnabled) return null; checkIteratorQueue(); final int part = cctx.affinity().partition(key); // First try removing from offheap. if (offheapEnabled) { byte[] entryBytes = offheap.remove(spaceName, part, key, keyBytes); if (entryBytes != null) { // To unmarshal swap entry itself local class loader will be enough. GridCacheSwapEntry<V> entry = swapEntry((GridCacheSwapEntry<V>)unmarshal(entryBytes, cctx.deploy().localLoader())); if (entry == null) return null; // Always fire this event, since preloading depends on it. onOffHeaped(part, key, keyBytes, entry.value(), entry.valueBytes(), entry.version(), entry.ttl(), entry.expireTime()); if (cctx.events().isRecordable(EVT_CACHE_OBJECT_FROM_OFFHEAP)) cctx.events().addEvent(part, key, cctx.nodeId(), (GridUuid)null, null, EVT_CACHE_OBJECT_FROM_OFFHEAP, null, false, null, true); GridCacheQueryManager<K, V> qryMgr = cctx.queries(); if (qryMgr != null) qryMgr.onUnswap(key, entry.value(), entry.valueBytes()); return entry; } } if (swapEnabled) { final GridTuple<GridCacheSwapEntry<V>> t = F.t1(); final GridTuple<GridException> err = F.t1(); swapMgr.remove(spaceName, new GridSwapKey(key, part, keyBytes), new CI1<byte[]>() { @Override public void apply(byte[] rmv) { if (rmv != null) { try { // To unmarshal swap entry itself local class loader will be enough. GridCacheSwapEntry<V> entry = swapEntry((GridCacheSwapEntry<V>)unmarshal(rmv, cctx.deploy().localLoader())); if (entry == null) return; t.set(entry); V v = entry.value(); byte[] valBytes = entry.valueBytes(); // Event notification. if (cctx.events().isRecordable(EVT_CACHE_OBJECT_UNSWAPPED)) cctx.events().addEvent(part, key, cctx.nodeId(), (GridUuid)null, null, EVT_CACHE_OBJECT_UNSWAPPED, null, false, v, true); // Always fire this event, since preloading depends on it. onUnswapped(part, key, keyBytes, v, valBytes, entry.version(), entry.ttl(), entry.expireTime()); GridCacheQueryManager<K, V> qryMgr = cctx.queries(); if (qryMgr != null) qryMgr.onUnswap(key, v, valBytes); } catch (GridException e) { err.set(e); } } } }, cctx.deploy().globalLoader()); if (err.get() != null) throw err.get(); return t.get(); } return null; } /** * @param entry Entry to read. * @return Read value. * @throws GridException If read failed. */ @Nullable GridCacheSwapEntry<V> read(GridCacheMapEntry<K, V> entry) throws GridException { if (!offheapEnabled && !swapEnabled) return null; return read(entry.key(), entry.getOrMarshalKeyBytes()); } /** * @param key Key to read swap entry for. * @return Read value. * @throws GridException If read failed. */ @Nullable GridCacheSwapEntry<V> read(K key) throws GridException { if (!offheapEnabled && !swapEnabled) return null; return read(key, CU.marshal(cctx, key)); } /** * @param entry Entry to read. * @return Read value. * @throws GridException If read failed. */ @Nullable GridCacheSwapEntry<V> readAndRemove(GridCacheMapEntry<K, V> entry) throws GridException { if (!offheapEnabled && !swapEnabled) return null; return readAndRemove(entry.key(), entry.getOrMarshalKeyBytes()); } /** * @param keys Collection of keys to remove from swap. * @return Collection of swap entries. * @throws GridException If failed, */ public Collection<GridCacheBatchSwapEntry<K, V>> readAndRemove(Collection<? extends K> keys) throws GridException { if (!offheapEnabled && !swapEnabled) return Collections.emptyList(); checkIteratorQueue(); final GridCacheQueryManager<K, V> qryMgr = cctx.queries(); ArrayList<K> keysList = new ArrayList<>(keys); final Collection<GridCacheBatchSwapEntry<K, V>> res = new ArrayList<>(keys.size()); // First try removing from offheap. if (offheapEnabled) { Iterator<K> iter = keysList.iterator(); while (iter.hasNext()) { K key = iter.next(); int part = cctx.affinity().partition(key); byte[] keyBytes = CU.marshal(cctx, key); int hash = U.hash(key); byte[] entryBytes = offheap.remove(spaceName, part, key, keyBytes); if (entryBytes != null) { // To unmarshal swap entry itself local class loader will be enough. GridCacheSwapEntry<V> entry = swapEntry((GridCacheSwapEntry<V>)unmarshal(entryBytes, cctx.deploy().localLoader())); if (entry == null) continue; iter.remove(); // Always fire this event, since preloading depends on it. onOffHeaped(part, key, keyBytes, entry.value(), entry.valueBytes(), entry.version(), entry.ttl(), entry.expireTime()); if (cctx.events().isRecordable(EVT_CACHE_OBJECT_FROM_OFFHEAP)) cctx.events().addEvent(part, key, cctx.nodeId(), (GridUuid)null, null, EVT_CACHE_OBJECT_FROM_OFFHEAP, null, false, null, true); if (qryMgr != null) qryMgr.onUnswap(key, entry.value(), entry.valueBytes()); GridCacheBatchSwapEntry<K, V> unswapped = new GridCacheBatchSwapEntry<>(key, keyBytes, hash, part, entry.valueBytes(),entry.valueIsByteArray(), entry.version(), entry.ttl(), entry.expireTime(), entry.keyClassLoaderId(), entry.valueClassLoaderId()); unswapped.value(entry.value()); res.add(unswapped); } } if (!swapEnabled || keysList.isEmpty()) return res; } // Swap is enabled. final GridTuple<GridException> err = F.t1(); Collection<GridSwapKey> converted = new ArrayList<>(F.viewReadOnly(keysList, new C1<K, GridSwapKey>() { @Override public GridSwapKey apply(K key) { try { return new GridSwapKey(key, cctx.affinity().partition(key), CU.marshal(cctx, key)); } catch (GridException e) { throw new GridRuntimeException(e); } } })); swapMgr.removeAll(spaceName, converted, new GridBiInClosure<GridSwapKey, byte[]>() { @Override public void apply(GridSwapKey swapKey, byte[] rmv) { if (rmv != null) { try { // To unmarshal swap entry itself local class loader will be enough. GridCacheSwapEntry<V> entry = swapEntry((GridCacheSwapEntry<V>)unmarshal(rmv, cctx.deploy().localLoader())); if (entry == null) return; K key = (K)swapKey.key(); GridCacheBatchSwapEntry<K, V> unswapped = new GridCacheBatchSwapEntry<>(key, swapKey.keyBytes(), U.hash(key), swapKey.partition(), entry.valueBytes(), entry.valueIsByteArray(), entry.version(), entry.ttl(), entry.expireTime(), entry.keyClassLoaderId(), entry.valueClassLoaderId()); unswapped.value(entry.value()); res.add(unswapped); // Event notification. if (cctx.events().isRecordable(EVT_CACHE_OBJECT_UNSWAPPED)) cctx.events().addEvent(swapKey.partition(), key, cctx.nodeId(), (GridUuid)null, null, EVT_CACHE_OBJECT_UNSWAPPED, null, false, entry.value(), true); // Always fire this event, since preloading depends on it. onUnswapped(swapKey.partition(), key, swapKey.keyBytes(), entry.value(), entry.valueBytes(), entry.version(), entry.ttl(), entry.expireTime()); if (qryMgr != null) qryMgr.onUnswap(key, entry.value(), entry.valueBytes()); } catch (GridException e) { err.set(e); } } } }, cctx.deploy().globalLoader()); if (err.get() != null) throw err.get(); return res; } /** * @param key Key to read swap entry for. * @return Read value. * @throws GridException If read failed. */ @Nullable GridCacheSwapEntry<V> readAndRemove(K key) throws GridException { if (!offheapEnabled && !swapEnabled) return null; return readAndRemove(key, CU.marshal(cctx, key)); } /** * @param key Key to remove. * @param keyBytes Key bytes. * @throws GridException If failed. */ void remove(final K key, byte[] keyBytes) throws GridException { if (!offheapEnabled && !swapEnabled) return; checkIteratorQueue(); final GridCacheQueryManager<K, V> qryMgr = cctx.queries(); CI1<byte[]> c = qryMgr == null ? null : new CI1<byte[]>() { @Override public void apply(byte[] rmv) { if (rmv == null) return; try { // To unmarshal swap entry itself local class loader will be enough. GridCacheSwapEntry<V> entry = swapEntry((GridCacheSwapEntry<V>)unmarshal(rmv, cctx.deploy().localLoader())); if (entry == null) return; qryMgr.onUnswap(key, entry.value(), entry.valueBytes()); } catch (GridException e) { throw new GridRuntimeException(e); } } }; int part = cctx.affinity().partition(key); // First try offheap. if (offheapEnabled) { byte[] val = offheap.remove(spaceName, part, key, keyBytes); if (val != null) { if (c != null) c.apply(val); // Probably we should read value and apply closure before removing... return; } } if (swapEnabled) swapMgr.remove(spaceName, new GridSwapKey(key, part, keyBytes), c, cctx.deploy().globalLoader()); } /** * Writes a versioned value to swap. * * @param key Key. * @param keyBytes Key bytes. * @param keyHash Key hash. * @param val Value. * @param valIsByteArr Whether value is byte array. * @param ver Version. * @param ttl Entry time to live. * @param expireTime Swap entry expiration time. * @param keyClsLdrId Class loader ID for entry key. * @param valClsLdrId Class loader ID for entry value. * @throws GridException If failed. */ void write(K key, byte[] keyBytes, int keyHash, byte[] val, boolean valIsByteArr, GridCacheVersion ver, long ttl, long expireTime, @Nullable GridUuid keyClsLdrId, @Nullable GridUuid valClsLdrId) throws GridException { if (!offheapEnabled && !swapEnabled) return; checkIteratorQueue(); int part = cctx.affinity().partition(key); if (offheapEnabled) { GridCacheSwapEntry<V> entry = new GridCacheSwapEntry<>(keyHash, val, valIsByteArr, ver, ttl, expireTime, keyClsLdrId, valClsLdrId); offheap.put(spaceName, part, key, keyBytes, marshal(entry)); if (cctx.events().isRecordable(EVT_CACHE_OBJECT_TO_OFFHEAP)) cctx.events().addEvent(part, key, cctx.nodeId(), (GridUuid)null, null, EVT_CACHE_OBJECT_TO_OFFHEAP, null, false, null, true); } else if (swapEnabled) { GridCacheSwapEntry<V> entry = new GridCacheSwapEntry<>(keyHash, val, valIsByteArr, ver, ttl, expireTime, keyClsLdrId, valClsLdrId); writeToSwap(part, key, keyBytes, marshal(entry)); } GridCacheQueryManager<K, V> qryMgr = cctx.queries(); if (qryMgr != null) qryMgr.onSwap(spaceName, key); } /** * Performs batch write of swapped entries. * * @param swapped Collection of swapped entries. * @throws GridException If failed. */ void writeAll(Iterable<GridCacheBatchSwapEntry<K, V>> swapped) throws GridException { assert offheapEnabled || swapEnabled; checkIteratorQueue(); GridCacheQueryManager<K, V> qryMgr = cctx.queries(); if (offheapEnabled) { for (GridCacheBatchSwapEntry<K, V> swapEntry : swapped) { offheap.put(spaceName, swapEntry.partition(), swapEntry.key(), swapEntry.keyBytes(), marshal(swapEntry)); if (cctx.events().isRecordable(EVT_CACHE_OBJECT_TO_OFFHEAP)) cctx.events().addEvent(swapEntry.partition(), swapEntry.key(), cctx.nodeId(), (GridUuid)null, null, EVT_CACHE_OBJECT_TO_OFFHEAP, null, false, null, true); if (qryMgr != null) qryMgr.onSwap(spaceName, swapEntry.key()); } } else { // Swap enabled. swapMgr.writeAll(spaceName, swapped, cctx.deploy().globalLoader()); if (cctx.events().isRecordable(EVT_CACHE_OBJECT_SWAPPED)) { for (GridCacheBatchSwapEntry<K, V> batchSwapEntry : swapped) { cctx.events().addEvent(batchSwapEntry.partition(), batchSwapEntry.key(), cctx.nodeId(), (GridUuid)null, null, EVT_CACHE_OBJECT_SWAPPED, null, false, null, true); if (qryMgr != null) qryMgr.onSwap(spaceName, batchSwapEntry.key()); } } } } /** * Writes given bytes to swap. * * @param part Partition. * @param key Key. If {@code null} then it will be deserialized from {@code keyBytes}. * @param keyBytes Key bytes. * @param entry Entry bytes. * @throws GridException If failed. */ private void writeToSwap(int part, @Nullable K key, byte[] keyBytes, byte[] entry) throws GridException{ checkIteratorQueue(); if (key == null) key = unmarshal(keyBytes, cctx.deploy().globalLoader()); swapMgr.write(spaceName, new GridSwapKey(key, part, keyBytes), entry, cctx.deploy().globalLoader()); if (cctx.events().isRecordable(EVT_CACHE_OBJECT_SWAPPED)) cctx.events().addEvent(part, key, cctx.nodeId(), (GridUuid)null, null, EVT_CACHE_OBJECT_SWAPPED, null, false, null, true); } /** * Clears off-heap. */ public void clearOffHeap() { if (offheapEnabled) initOffHeap(); } /** * Clears swap. * * @throws GridException If failed. */ public void clearSwap() throws GridException { if (swapEnabled) swapMgr.clear(spaceName); } /** * Gets offheap and swap iterator over partition. * * @param part Partition to iterate over. * @return Iterator over partition. * @throws GridException If failed. */ @Nullable public GridCloseableIterator<Map.Entry<byte[], GridCacheSwapEntry<V>>> iterator(final int part) throws GridException { if (!swapEnabled() && !offHeapEnabled()) return null; checkIteratorQueue(); if (offHeapEnabled() && !swapEnabled()) return offHeapIterator(part); if (swapEnabled() && !offHeapEnabled()) return swapIterator(part); // Both, swap and off-heap are enabled. return new GridCloseableIteratorAdapter<Map.Entry<byte[], GridCacheSwapEntry<V>>>() { private GridCloseableIterator<Map.Entry<byte[], GridCacheSwapEntry<V>>> it; private boolean offheap = true; private boolean done; { it = offHeapIterator(part); advance(); } private void advance() throws GridException { if (it != null && it.hasNext()) return; if (it != null) it.close(); if (offheap) { offheap = false; it = swapIterator(part); if (it == null || !it.hasNext()) { it.close(); done = true; } } else done = true; } @Override protected Map.Entry<byte[], GridCacheSwapEntry<V>> onNext() throws GridException { if (done) throw new NoSuchElementException(); Map.Entry<byte[], GridCacheSwapEntry<V>> e = it.next(); advance(); return e; } @Override protected boolean onHasNext() { return !done; } @Override protected void onRemove() { throw new UnsupportedOperationException(); } @Override protected void onClose() throws GridException { if (it != null) it.close(); } }; } /** * Gets offheap and swap iterator over partition. * * @return Iterator over partition. * @throws GridException If failed. */ @Nullable public GridCloseableIterator<Map.Entry<byte[], byte[]>> rawIterator() throws GridException { if (!swapEnabled() && !offHeapEnabled()) return new GridEmptyCloseableIterator<>(); checkIteratorQueue(); if (offHeapEnabled() && !swapEnabled()) return rawOffHeapIterator(); if (swapEnabled() && !offHeapEnabled()) return rawSwapIterator(); // Both, swap and off-heap are enabled. return new GridCloseableIteratorAdapter<Map.Entry<byte[], byte[]>>() { private GridCloseableIterator<Map.Entry<byte[], byte[]>> it; private boolean offheapFlag = true; private boolean done; private Map.Entry<byte[], byte[]> cur; { it = rawOffHeapIterator(); if (it == null || !it.hasNext()) { it.close(); offheapFlag = false; } advance(); } private void advance() throws GridException { if (it.hasNext()) return; it.close(); if (offheapFlag) { offheapFlag = false; it = rawSwapIterator(); if (it == null || !it.hasNext()) { it.close(); done = true; } } else done = true; } @Override protected Map.Entry<byte[], byte[]> onNext() throws GridException { if (done) throw new NoSuchElementException(); cur = it.next(); advance(); return cur; } @Override protected boolean onHasNext() { return !done; } @Override protected void onRemove() throws GridException { if (offheapFlag) { K key = unmarshal(cur.getKey(), cctx.deploy().globalLoader()); int part = cctx.affinity().partition(key); offheap.removex(spaceName, part, key, cur.getKey()); } else it.removeX(); } @Override protected void onClose() throws GridException { if (it != null) it.close(); } }; } /** * @return Lazy swap iterator. * @throws GridException If failed. */ public Iterator<Map.Entry<K, V>> lazySwapIterator() throws GridException { if (!swapEnabled) return new GridEmptyIterator<>(); return lazyIterator(cctx.gridSwap().rawIterator(spaceName)); } /** * @return Lazy off-heap iterator. */ public Iterator<Map.Entry<K, V>> lazyOffHeapIterator() { if (!offheapEnabled) return new GridEmptyCloseableIterator<>(); return lazyIterator(offheap.iterator(spaceName)); } /** * Gets number of elements in off-heap * * @return Number of elements or {@code 0} if off-heap is disabled. */ public long offHeapEntriesCount() { return offheapEnabled ? offheap.entriesCount(spaceName) : 0; } /** * Gets memory size allocated in off-heap. * * @return Allocated memory size or {@code 0} if off-heap is disabled. */ public long offHeapAllocatedSize() { return offheapEnabled ? offheap.allocatedSize(spaceName) : 0; } /** * Gets lazy iterator for which key and value are lazily deserialized. * * @param it Closeable iterator. * @return Lazy iterator. */ private Iterator<Map.Entry<K, V>> lazyIterator( final GridCloseableIterator<? extends Map.Entry<byte[], byte[]>> it) { if (it == null) return new GridEmptyIterator<>(); checkIteratorQueue(); // Weak reference will hold hard reference to this iterator, so it can properly be closed. final GridCloseableIteratorAdapter<Map.Entry<K, V>> iter = new GridCloseableIteratorAdapter<Map.Entry<K, V>>() { private Map.Entry<K, V> cur; @Override protected Map.Entry<K, V> onNext() { final Map.Entry<byte[], byte[]> cur0 = it.next(); cur = new Map.Entry<K, V>() { @Override public K getKey() { try { return unmarshal(cur0.getKey(), cctx.deploy().globalLoader()); } catch (GridException e) { throw new GridRuntimeException(e); } } @Override public V getValue() { try { GridCacheSwapEntry<V> e = unmarshal(cur0.getValue(), cctx.deploy().localLoader()); swapEntry(e); return e.value(); } catch (GridException ex) { throw new GridRuntimeException(ex); } } @Override public V setValue(V val) { throw new UnsupportedOperationException(); } }; return cur; } @Override protected boolean onHasNext() { return it.hasNext(); } @Override protected void onRemove() throws GridException { if (cur == null) throw new IllegalStateException("Method next() has not yet been called, or the remove() method " + "has already been called after the last call to the next() method."); try { if (cctx.isDht()) cctx.dht().near().removex(cur.getKey(), CU.<K, V>empty()); else cctx.cache().removex(cur.getKey(), CU.<K, V>empty()); } finally { cur = null; } } @Override protected void onClose() throws GridException { it.close(); } }; // Don't hold hard reference to this iterator - only weak one. Iterator<Map.Entry<K, V>> ret = new Iterator<Map.Entry<K, V>>() { @Override public boolean hasNext() { return iter.hasNext(); } @Override public Map.Entry<K, V> next() { return iter.next(); } @Override public void remove() { iter.remove(); } }; itSet.add(new GridWeakIterator<>(ret, iter, itQ)); return ret; } /** * Gets offheap iterator over partition. * * @param part Partition to iterate over. * @return Iterator over partition. * @throws GridException If failed. */ @Nullable public GridCloseableIterator<Map.Entry<byte[], GridCacheSwapEntry<V>>> offHeapIterator(int part) throws GridException { if (!offheapEnabled) return null; checkIteratorQueue(); return new IteratorWrapper(offheap.iterator(spaceName, part)); } /** * @return Raw off-heap iterator. */ private GridCloseableIterator<Map.Entry<byte[], byte[]>> rawOffHeapIterator() { if (!offheapEnabled) return new GridEmptyCloseableIterator<>(); return new GridCloseableIteratorAdapter<Map.Entry<byte[], byte[]>>() { private GridCloseableIterator<GridBiTuple<byte[], byte[]>> it = offheap.iterator(spaceName); private Map.Entry<byte[], byte[]> cur; @Override protected Map.Entry<byte[], byte[]> onNext() { return cur = it.next(); } @Override protected boolean onHasNext() { return it.hasNext(); } @Override protected void onRemove() throws GridException { K key = unmarshal(cur.getKey(), cctx.deploy().globalLoader()); int part = cctx.affinity().partition(key); offheap.removex(spaceName, part, key, cur.getKey()); } @Override protected void onClose() throws GridException { it.close(); } }; } /** * Gets swap space iterator over partition. * * @param part Partition to iterate over. * @return Iterator over partition. * @throws GridException If failed. */ @Nullable public GridCloseableIterator<Map.Entry<byte[], GridCacheSwapEntry<V>>> swapIterator(int part) throws GridException { if (!swapEnabled) return null; checkIteratorQueue(); return new IteratorWrapper(swapMgr.rawIterator(spaceName, part)); } /** * @return Raw off-heap iterator. * @throws GridException If failed. */ private GridCloseableIterator<Map.Entry<byte[], byte[]>> rawSwapIterator() throws GridException { if (!swapEnabled) return new GridEmptyCloseableIterator<>(); checkIteratorQueue(); return swapMgr.rawIterator(spaceName); } /** * @param leftNodeId Left Node ID. * @param ldr Undeployed class loader. * @return Undeploy count. */ public int onUndeploy(UUID leftNodeId, ClassLoader ldr) { GridUuid ldrId = cctx.deploy().getClassLoaderId(ldr); assert ldrId != null; checkIteratorQueue(); try { GridCloseableIterator<Map.Entry<byte[], byte[]>> iter = rawIterator(); if (iter != null) { int undeployCnt = 0; try { ClassLoader locLdr = cctx.deploy().localLoader(); for (Map.Entry<byte[], byte[]> e : iter) { try { GridCacheSwapEntry<V> swapEntry = unmarshal(e.getValue(), locLdr); GridUuid valLdrId = swapEntry.valueClassLoaderId(); if (ldrId.equals(swapEntry.keyClassLoaderId())) { iter.removeX(); undeployCnt++; } else { if (valLdrId == null && swapEntry.value() == null && !swapEntry.valueIsByteArray()) { // We need value here only for classloading purposes. V val = cctx.marshaller().unmarshal(swapEntry.valueBytes(), cctx.deploy().globalLoader()); if (val != null) valLdrId = cctx.deploy().getClassLoaderId(val.getClass().getClassLoader()); } if (ldrId.equals(valLdrId)) { iter.removeX(); undeployCnt++; } } } catch (GridException ex) { U.error(log, "Failed to process swap entry.", ex); } } } finally { iter.close(); } return undeployCnt; } } catch (GridException e) { U.error(log, "Failed to clear cache swap space on undeploy.", e); } return 0; } /** * @param bytes Bytes to unmarshal. * @param ldr Class loader. * @return Unmarshalled value. * @throws GridException If unmarshal failed. */ private <T> T unmarshal(byte[] bytes, ClassLoader ldr) throws GridException { return cctx.marshaller().unmarshal(bytes, ldr); } /** * @param obj Object to marshal. * @return Marshalled byte array. * @throws GridException If marshalling failed. */ private byte[] marshal(Object obj) throws GridException { return cctx.marshaller().marshal(obj); } /** * @return Size of internal weak iterator set. */ int iteratorSetSize() { return itSet.size(); } /** * */ private class IteratorWrapper extends GridCloseableIteratorAdapter<Map.Entry<byte[], GridCacheSwapEntry<V>>> { /** */ private static final long serialVersionUID = 0L; /** */ private final GridCloseableIterator<? extends Map.Entry<byte[], byte[]>> iter; /** * @param iter Iterator. */ private IteratorWrapper(GridCloseableIterator<? extends Map.Entry<byte[], byte[]>> iter) { assert iter != null; this.iter = iter; } /** {@inheritDoc} */ @Override protected Map.Entry<byte[], GridCacheSwapEntry<V>> onNext() throws GridException { Map.Entry<byte[], byte[]> e = iter.nextX(); // To unmarshal swap entry itself local class loader will be enough. return F.t(e.getKey(), (GridCacheSwapEntry<V>)unmarshal(e.getValue(), cctx.deploy().localLoader())); } /** {@inheritDoc} */ @Override protected boolean onHasNext() throws GridException { return iter.hasNext(); } /** {@inheritDoc} */ @Override protected void onClose() throws GridException { iter.close(); } /** {@inheritDoc} */ @Override protected void onRemove() { iter.remove(); } } }
# GG-8089
modules/core/src/main/java/org/gridgain/grid/kernal/processors/cache/GridCacheSwapManager.java
# GG-8089
<ide><path>odules/core/src/main/java/org/gridgain/grid/kernal/processors/cache/GridCacheSwapManager.java <ide> <ide> it = swapIterator(part); <ide> <del> if (it == null || !it.hasNext()) { <add> if (!it.hasNext()) { <ide> it.close(); <ide> <ide> done = true;
Java
apache-2.0
a2fd04fd85fbdc6855bc91a2a0bc6ad8f10d747a
0
xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,xfournet/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,xfournet/intellij-community,xfournet/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,xfournet/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,allotria/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,xfournet/intellij-community
/* * Copyright 2000-2017 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.lang.html; import com.intellij.lang.ASTNode; import com.intellij.openapi.editor.Document; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.XmlRecursiveElementVisitor; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.psi.formatter.xml.HtmlCodeStyleSettings; import com.intellij.psi.impl.source.codeStyle.PostFormatProcessorHelper; import com.intellij.psi.impl.source.codeStyle.PreFormatProcessor; import com.intellij.psi.tree.IElementType; import com.intellij.psi.xml.XmlAttributeValue; import com.intellij.psi.xml.XmlTokenType; import com.intellij.util.DocumentUtil; import org.jetbrains.annotations.NotNull; public class HtmlQuotesFormatPreprocessor implements PreFormatProcessor { @NotNull @Override public TextRange process(@NotNull ASTNode node, @NotNull TextRange range) { PsiElement psiElement = node.getPsi(); if (psiElement != null && psiElement.isValid() && psiElement.getLanguage().is(HTMLLanguage.INSTANCE)) { CodeStyleSettings rootSettings = CodeStyleSettingsManager.getSettings(psiElement.getProject()); HtmlCodeStyleSettings htmlSettings = rootSettings.getCustomSettings(HtmlCodeStyleSettings.class); CodeStyleSettings.QuoteStyle quoteStyle = htmlSettings.HTML_QUOTE_STYLE; if (quoteStyle != CodeStyleSettings.QuoteStyle.None && htmlSettings.HTML_ENFORCE_QUOTES) { PostFormatProcessorHelper postFormatProcessorHelper = new PostFormatProcessorHelper(rootSettings.getCommonSettings(HTMLLanguage.INSTANCE)); postFormatProcessorHelper.setResultTextRange(range); HtmlQuotesConverter converter = new HtmlQuotesConverter(quoteStyle, psiElement, postFormatProcessorHelper); Document document = converter.getDocument(); if (document != null) { DocumentUtil.executeInBulk(document, true, converter); } return postFormatProcessorHelper.getResultTextRange(); } } return range; } public static class HtmlQuotesConverter extends XmlRecursiveElementVisitor implements Runnable { private TextRange myOriginalRange; private final Document myDocument; private final PsiDocumentManager myDocumentManager; private final PostFormatProcessorHelper myPostProcessorHelper; private final PsiElement myContext; private final String myNewQuote; public HtmlQuotesConverter(@NotNull CodeStyleSettings.QuoteStyle style, @NotNull PsiElement context, @NotNull PostFormatProcessorHelper postFormatProcessorHelper) { myPostProcessorHelper = postFormatProcessorHelper; Project project = context.getProject(); PsiFile file = context.getContainingFile(); myContext = context; myOriginalRange = postFormatProcessorHelper.getResultTextRange(); myDocumentManager = PsiDocumentManager.getInstance(project); myDocument = file.getViewProvider().getDocument(); switch (style) { case Single: myNewQuote = "\'"; break; case Double: myNewQuote = "\""; break; default: myNewQuote = String.valueOf(0); } } public Document getDocument() { return myDocument; } @Override public void visitXmlAttributeValue(XmlAttributeValue value) { //use original range to check because while we are modifying document, element ranges returned from getTextRange() are not updated. if (myOriginalRange.contains(value.getTextRange())) { PsiElement child = value.getFirstChild(); if (child != null && !containsQuoteChars(value) // For now we skip values containing quotes to be inserted/replaced ) { if (child.getNode().getElementType() == XmlTokenType.XML_ATTRIBUTE_VALUE_START_DELIMITER) { PsiElement lastChild = value.getLastChild(); if (lastChild != null && lastChild.getNode().getElementType() == XmlTokenType.XML_ATTRIBUTE_VALUE_END_DELIMITER) { CharSequence delimiterChars = child.getNode().getChars(); if (delimiterChars.length() == 1 && !StringUtil.equals(delimiterChars, myNewQuote)) { int startOffset = value.getTextRange().getStartOffset(); int endOffset = value.getTextRange().getEndOffset(); replaceString(startOffset, startOffset + 1, myNewQuote); replaceString(endOffset - 1, endOffset, myNewQuote); } } } else if (child.getNode().getElementType() == XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN && child == value.getLastChild()) { insertString(child.getTextRange().getStartOffset(), myNewQuote); insertString(child.getTextRange().getEndOffset(), myNewQuote); } } } } private void replaceString(int start, int end, String newValue) { final int mappedStart = myPostProcessorHelper.mapOffset(start); final int mappedEnd = myPostProcessorHelper.mapOffset(end); myDocument.replaceString(mappedStart, mappedEnd, newValue); myPostProcessorHelper.updateResultRange(end - start, newValue.length()); } private void insertString(int offset, String value) { final int mappedOffset = myPostProcessorHelper.mapOffset(offset); myDocument.insertString(mappedOffset, value); myPostProcessorHelper.updateResultRange(0, value.length()); } private boolean containsQuoteChars(@NotNull XmlAttributeValue value) { for (PsiElement child = value.getFirstChild(); child != null; child = child.getNextSibling()) { if (!isDelimiter(child.getNode().getElementType()) && StringUtil.contains(child.getNode().getChars(), myNewQuote)) { return true; } } return false; } private static boolean isDelimiter(@NotNull IElementType elementType) { return elementType == XmlTokenType.XML_ATTRIBUTE_VALUE_START_DELIMITER || elementType == XmlTokenType.XML_ATTRIBUTE_VALUE_END_DELIMITER; } @Override public void run() { if (myDocument != null) { myDocumentManager.doPostponedOperationsAndUnblockDocument(myDocument); myContext.accept(this); myDocumentManager.commitDocument(myDocument); } } public static void runOnElement(@NotNull CodeStyleSettings.QuoteStyle quoteStyle, @NotNull PsiElement element) { PostFormatProcessorHelper postFormatProcessorHelper = new PostFormatProcessorHelper(null); postFormatProcessorHelper.setResultTextRange(element.getTextRange()); new HtmlQuotesConverter(quoteStyle, element, postFormatProcessorHelper).run(); } } }
xml/impl/src/com/intellij/lang/html/HtmlQuotesFormatPreprocessor.java
/* * Copyright 2000-2017 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.lang.html; import com.intellij.lang.ASTNode; import com.intellij.openapi.editor.Document; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.XmlRecursiveElementVisitor; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.psi.formatter.xml.HtmlCodeStyleSettings; import com.intellij.psi.impl.source.codeStyle.PostFormatProcessorHelper; import com.intellij.psi.impl.source.codeStyle.PreFormatProcessor; import com.intellij.psi.tree.IElementType; import com.intellij.psi.xml.XmlAttributeValue; import com.intellij.psi.xml.XmlTokenType; import com.intellij.util.DocumentUtil; import org.jetbrains.annotations.NotNull; public class HtmlQuotesFormatPreprocessor implements PreFormatProcessor { @NotNull @Override public TextRange process(@NotNull ASTNode node, @NotNull TextRange range) { PsiElement psiElement = node.getPsi(); if (psiElement != null && psiElement.isValid() && psiElement.getLanguage().is(HTMLLanguage.INSTANCE)) { CodeStyleSettings rootSettings = CodeStyleSettingsManager.getSettings(psiElement.getProject()); HtmlCodeStyleSettings htmlSettings = rootSettings.getCustomSettings(HtmlCodeStyleSettings.class); CodeStyleSettings.QuoteStyle quoteStyle = htmlSettings.HTML_QUOTE_STYLE; if (quoteStyle != CodeStyleSettings.QuoteStyle.None && htmlSettings.HTML_ENFORCE_QUOTES) { PostFormatProcessorHelper postFormatProcessorHelper = new PostFormatProcessorHelper(rootSettings); postFormatProcessorHelper.setResultTextRange(range); HtmlQuotesConverter converter = new HtmlQuotesConverter(quoteStyle, psiElement, postFormatProcessorHelper); Document document = converter.getDocument(); if (document != null) { DocumentUtil.executeInBulk(document, true, converter); } return postFormatProcessorHelper.getResultTextRange(); } } return range; } public static class HtmlQuotesConverter extends XmlRecursiveElementVisitor implements Runnable { private TextRange myOriginalRange; private final Document myDocument; private final PsiDocumentManager myDocumentManager; private final PostFormatProcessorHelper myPostProcessorHelper; private final PsiElement myContext; private final String myNewQuote; public HtmlQuotesConverter(@NotNull CodeStyleSettings.QuoteStyle style, @NotNull PsiElement context, @NotNull PostFormatProcessorHelper postFormatProcessorHelper) { myPostProcessorHelper = postFormatProcessorHelper; Project project = context.getProject(); PsiFile file = context.getContainingFile(); myContext = context; myOriginalRange = postFormatProcessorHelper.getResultTextRange(); myDocumentManager = PsiDocumentManager.getInstance(project); myDocument = file.getViewProvider().getDocument(); switch (style) { case Single: myNewQuote = "\'"; break; case Double: myNewQuote = "\""; break; default: myNewQuote = String.valueOf(0); } } public Document getDocument() { return myDocument; } @Override public void visitXmlAttributeValue(XmlAttributeValue value) { //use original range to check because while we are modifying document, element ranges returned from getTextRange() are not updated. if (myOriginalRange.contains(value.getTextRange())) { PsiElement child = value.getFirstChild(); if (child != null && !containsQuoteChars(value) // For now we skip values containing quotes to be inserted/replaced ) { if (child.getNode().getElementType() == XmlTokenType.XML_ATTRIBUTE_VALUE_START_DELIMITER) { PsiElement lastChild = value.getLastChild(); if (lastChild != null && lastChild.getNode().getElementType() == XmlTokenType.XML_ATTRIBUTE_VALUE_END_DELIMITER) { CharSequence delimiterChars = child.getNode().getChars(); if (delimiterChars.length() == 1 && !StringUtil.equals(delimiterChars, myNewQuote)) { int startOffset = value.getTextRange().getStartOffset(); int endOffset = value.getTextRange().getEndOffset(); replaceString(startOffset, startOffset + 1, myNewQuote); replaceString(endOffset - 1, endOffset, myNewQuote); } } } else if (child.getNode().getElementType() == XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN && child == value.getLastChild()) { insertString(child.getTextRange().getStartOffset(), myNewQuote); insertString(child.getTextRange().getEndOffset(), myNewQuote); } } } } private void replaceString(int start, int end, String newValue) { final int mappedStart = myPostProcessorHelper.mapOffset(start); final int mappedEnd = myPostProcessorHelper.mapOffset(end); myDocument.replaceString(mappedStart, mappedEnd, newValue); myPostProcessorHelper.updateResultRange(end - start, newValue.length()); } private void insertString(int offset, String value) { final int mappedOffset = myPostProcessorHelper.mapOffset(offset); myDocument.insertString(mappedOffset, value); myPostProcessorHelper.updateResultRange(0, value.length()); } private boolean containsQuoteChars(@NotNull XmlAttributeValue value) { for (PsiElement child = value.getFirstChild(); child != null; child = child.getNextSibling()) { if (!isDelimiter(child.getNode().getElementType()) && StringUtil.contains(child.getNode().getChars(), myNewQuote)) { return true; } } return false; } private static boolean isDelimiter(@NotNull IElementType elementType) { return elementType == XmlTokenType.XML_ATTRIBUTE_VALUE_START_DELIMITER || elementType == XmlTokenType.XML_ATTRIBUTE_VALUE_END_DELIMITER; } @Override public void run() { if (myDocument != null) { myDocumentManager.doPostponedOperationsAndUnblockDocument(myDocument); myContext.accept(this); myDocumentManager.commitDocument(myDocument); } } public static void runOnElement(@NotNull CodeStyleSettings.QuoteStyle quoteStyle, @NotNull PsiElement element) { PostFormatProcessorHelper postFormatProcessorHelper = new PostFormatProcessorHelper(null); postFormatProcessorHelper.setResultTextRange(element.getTextRange()); new HtmlQuotesConverter(quoteStyle, element, postFormatProcessorHelper).run(); } } }
Use settings from HTML language
xml/impl/src/com/intellij/lang/html/HtmlQuotesFormatPreprocessor.java
Use settings from HTML language
<ide><path>ml/impl/src/com/intellij/lang/html/HtmlQuotesFormatPreprocessor.java <ide> HtmlCodeStyleSettings htmlSettings = rootSettings.getCustomSettings(HtmlCodeStyleSettings.class); <ide> CodeStyleSettings.QuoteStyle quoteStyle = htmlSettings.HTML_QUOTE_STYLE; <ide> if (quoteStyle != CodeStyleSettings.QuoteStyle.None && htmlSettings.HTML_ENFORCE_QUOTES) { <del> PostFormatProcessorHelper postFormatProcessorHelper = new PostFormatProcessorHelper(rootSettings); <add> PostFormatProcessorHelper postFormatProcessorHelper = <add> new PostFormatProcessorHelper(rootSettings.getCommonSettings(HTMLLanguage.INSTANCE)); <ide> postFormatProcessorHelper.setResultTextRange(range); <ide> HtmlQuotesConverter converter = new HtmlQuotesConverter(quoteStyle, psiElement, postFormatProcessorHelper); <ide> Document document = converter.getDocument();
Java
mit
2dec420e592d4f3bef9dacff43e31c0dfbb3d43f
0
copygirl/WearableBackpacks
package net.mcft.copy.backpacks.misc.util; import java.lang.reflect.Method; import java.util.Arrays; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.common.Loader; import net.mcft.copy.backpacks.WearableBackpacks; public final class IntermodUtils { private IntermodUtils() { } private static final int DEFAULT_ENCHANTMENT_COLOR = 0xFF8040CC; private static boolean getRuneColorCached = false; private static Method setTargetStackMethod = null; private static Method getColorMethod = null; /** Returns the Quark rune color for this item or the default enchant glint * color if Quark isn't present or the item doesn't have a custom rune color. */ public static int getRuneColor(ItemStack stack) { if (!getRuneColorCached) { if (Loader.isModLoaded("quark")) { try { Class<?> clazz = Class.forName("vazkii.quark.misc.feature.ColorRunes"); setTargetStackMethod = clazz.getMethod("setTargetStack", ItemStack.class); getColorMethod = Arrays.stream(clazz.getMethods()) .filter(m -> "getColor".equals(m.getName())) .findAny().orElse(null); } catch (ClassNotFoundException | NoSuchMethodException ex) { WearableBackpacks.LOG.error("Error while fetching Quark ColorRunes methods", ex); } } getRuneColorCached = true; } if ((setTargetStackMethod == null) || (getColorMethod == null)) return DEFAULT_ENCHANTMENT_COLOR; try { setTargetStackMethod.invoke(null, stack); return (getColorMethod.getParameterCount() == 0) ? (int)getColorMethod.invoke(null) : (int)getColorMethod.invoke(null, DEFAULT_ENCHANTMENT_COLOR); } catch (Exception ex) { WearableBackpacks.LOG.error("Error while invoking Quark ColorRunes methods", ex); setTargetStackMethod = null; getColorMethod = null; return DEFAULT_ENCHANTMENT_COLOR; } } }
src/main/java/net/mcft/copy/backpacks/misc/util/IntermodUtils.java
package net.mcft.copy.backpacks.misc.util; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import net.mcft.copy.backpacks.WearableBackpacks; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.common.Loader; public final class IntermodUtils { private IntermodUtils() { } private static boolean getRuneColorCached = false; private static Method setTargetStackMethod; private static Method getColorMethod; /** Returns the Quark rune color for this item or the default enchant glint * color if Quark isn't present or the item doesn't have a custom rune color. */ public static int getRuneColor(ItemStack stack) { if (!getRuneColorCached) { if (Loader.isModLoaded("quark")) { try { Class<?> clazz = Class.forName("vazkii.quark.misc.feature.ColorRunes"); setTargetStackMethod = clazz.getMethod("setTargetStack", ItemStack.class); getColorMethod = clazz.getMethod("getColor"); } catch (ClassNotFoundException | NoSuchMethodException ex) { WearableBackpacks.LOG.error("Error while fetching Quark ColorRunes methods", ex); } } else { setTargetStackMethod = null; getColorMethod = null; } getRuneColorCached = true; } if (setTargetStackMethod == null) return 0xFF8040CC; try { setTargetStackMethod.invoke(null, stack); return (int)getColorMethod.invoke(null); } catch (IllegalAccessException | InvocationTargetException ex) { WearableBackpacks.LOG.error("Error while invoking Quark ColorRunes methods", ex); setTargetStackMethod = null; getColorMethod = null; return 0xFF8040CC; } } }
Fix Quark colored runes support I blame @lumien231 (Vazkii/Quark#738) :D
src/main/java/net/mcft/copy/backpacks/misc/util/IntermodUtils.java
Fix Quark colored runes support
<ide><path>rc/main/java/net/mcft/copy/backpacks/misc/util/IntermodUtils.java <ide> package net.mcft.copy.backpacks.misc.util; <ide> <del>import java.lang.reflect.InvocationTargetException; <ide> import java.lang.reflect.Method; <add>import java.util.Arrays; <add> <add>import net.minecraft.item.ItemStack; <add>import net.minecraftforge.fml.common.Loader; <ide> <ide> import net.mcft.copy.backpacks.WearableBackpacks; <del>import net.minecraft.item.ItemStack; <del>import net.minecraftforge.fml.common.Loader; <ide> <ide> public final class IntermodUtils { <ide> <ide> private IntermodUtils() { } <ide> <del> private static boolean getRuneColorCached = false; <del> private static Method setTargetStackMethod; <del> private static Method getColorMethod; <add> private static final int DEFAULT_ENCHANTMENT_COLOR = 0xFF8040CC; <add> private static boolean getRuneColorCached = false; <add> private static Method setTargetStackMethod = null; <add> private static Method getColorMethod = null; <ide> /** Returns the Quark rune color for this item or the default enchant glint <ide> * color if Quark isn't present or the item doesn't have a custom rune color. */ <ide> public static int getRuneColor(ItemStack stack) { <ide> try { <ide> Class<?> clazz = Class.forName("vazkii.quark.misc.feature.ColorRunes"); <ide> setTargetStackMethod = clazz.getMethod("setTargetStack", ItemStack.class); <del> getColorMethod = clazz.getMethod("getColor"); <add> getColorMethod = Arrays.stream(clazz.getMethods()) <add> .filter(m -> "getColor".equals(m.getName())) <add> .findAny().orElse(null); <ide> } catch (ClassNotFoundException | <ide> NoSuchMethodException ex) { <ide> WearableBackpacks.LOG.error("Error while fetching Quark ColorRunes methods", ex); <ide> } <del> } else { <del> setTargetStackMethod = null; <del> getColorMethod = null; <ide> } <ide> getRuneColorCached = true; <ide> } <del> if (setTargetStackMethod == null) <del> return 0xFF8040CC; <add> if ((setTargetStackMethod == null) || (getColorMethod == null)) <add> return DEFAULT_ENCHANTMENT_COLOR; <ide> try { <ide> setTargetStackMethod.invoke(null, stack); <del> return (int)getColorMethod.invoke(null); <del> } catch (IllegalAccessException | <del> InvocationTargetException ex) { <add> return (getColorMethod.getParameterCount() == 0) <add> ? (int)getColorMethod.invoke(null) <add> : (int)getColorMethod.invoke(null, DEFAULT_ENCHANTMENT_COLOR); <add> } catch (Exception ex) { <ide> WearableBackpacks.LOG.error("Error while invoking Quark ColorRunes methods", ex); <ide> setTargetStackMethod = null; <del> getColorMethod = null; <del> return 0xFF8040CC; <add> getColorMethod = null; <add> return DEFAULT_ENCHANTMENT_COLOR; <ide> } <ide> } <ide>
Java
unlicense
48aa1165184249dcb830a1f6d119d8759f242567
0
charlesmadere/that-lil-hummingbird
package com.charlesmadere.hummingbird.models; import android.os.Parcel; import android.os.Parcelable; import com.google.gson.annotations.SerializedName; public class AppNewsStatus implements Parcelable { @SerializedName("importantNewsAvailable") private boolean mImportantNewsAvailable; @SerializedName("pollTime") private long mPollTime; public long getPollTime() { return mPollTime; } public boolean isImportantNewsAvailable() { return mImportantNewsAvailable; } public void setImportantNewsAvailable(final boolean importantNewsAvailable) { mImportantNewsAvailable = importantNewsAvailable; } public void updatePollTime() { mPollTime = System.currentTimeMillis(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(final Parcel dest, final int flags) { dest.writeInt(mImportantNewsAvailable ? 1 : 0); dest.writeLong(mPollTime); } public static final Creator<AppNewsStatus> CREATOR = new Creator<AppNewsStatus>() { @Override public AppNewsStatus createFromParcel(final Parcel source) { final AppNewsStatus ans = new AppNewsStatus(); ans.mImportantNewsAvailable = source.readInt() != 0; ans.mPollTime = source.readLong(); return ans; } @Override public AppNewsStatus[] newArray(final int size) { return new AppNewsStatus[size]; } }; }
project/app/src/main/java/com/charlesmadere/hummingbird/models/AppNewsStatus.java
package com.charlesmadere.hummingbird.models; import android.os.Parcel; import android.os.Parcelable; import com.google.gson.annotations.SerializedName; public class AppNewsStatus implements Parcelable { @SerializedName("importantNewsAvailable") private boolean mImportantNewsAvailable; @SerializedName("pollTime") private long mPollTime; public AppNewsStatus(final boolean importantNewsAvailable) { mImportantNewsAvailable = importantNewsAvailable; } private AppNewsStatus(final Parcel source) { mImportantNewsAvailable = source.readInt() != 0; mPollTime = source.readLong(); } public long getPollTime() { return mPollTime; } public boolean isImportantNewsAvailable() { return mImportantNewsAvailable; } public void setImportantNewsAvailable(final boolean importantNewsAvailable) { mImportantNewsAvailable = importantNewsAvailable; } public void updatePollTime() { mPollTime = System.currentTimeMillis(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(final Parcel dest, final int flags) { dest.writeInt(mImportantNewsAvailable ? 1 : 0); dest.writeLong(mPollTime); } public static final Creator<AppNewsStatus> CREATOR = new Creator<AppNewsStatus>() { @Override public AppNewsStatus createFromParcel(final Parcel source) { return new AppNewsStatus(source); } @Override public AppNewsStatus[] newArray(final int size) { return new AppNewsStatus[size]; } }; }
tiny rework of AppNewsStatus class
project/app/src/main/java/com/charlesmadere/hummingbird/models/AppNewsStatus.java
tiny rework of AppNewsStatus class
<ide><path>roject/app/src/main/java/com/charlesmadere/hummingbird/models/AppNewsStatus.java <ide> @SerializedName("pollTime") <ide> private long mPollTime; <ide> <del> <del> public AppNewsStatus(final boolean importantNewsAvailable) { <del> mImportantNewsAvailable = importantNewsAvailable; <del> } <del> <del> private AppNewsStatus(final Parcel source) { <del> mImportantNewsAvailable = source.readInt() != 0; <del> mPollTime = source.readLong(); <del> } <ide> <ide> public long getPollTime() { <ide> return mPollTime; <ide> public static final Creator<AppNewsStatus> CREATOR = new Creator<AppNewsStatus>() { <ide> @Override <ide> public AppNewsStatus createFromParcel(final Parcel source) { <del> return new AppNewsStatus(source); <add> final AppNewsStatus ans = new AppNewsStatus(); <add> ans.mImportantNewsAvailable = source.readInt() != 0; <add> ans.mPollTime = source.readLong(); <add> return ans; <ide> } <ide> <ide> @Override
Java
apache-2.0
ba55fda898230b51df93c5a15f34706fc0a47ae0
0
asedunov/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,signed/intellij-community,da1z/intellij-community,allotria/intellij-community,da1z/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,apixandru/intellij-community,xfournet/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,semonte/intellij-community,da1z/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,signed/intellij-community,ibinti/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,allotria/intellij-community,suncycheng/intellij-community,allotria/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,semonte/intellij-community,da1z/intellij-community,xfournet/intellij-community,signed/intellij-community,signed/intellij-community,da1z/intellij-community,ibinti/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,da1z/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,semonte/intellij-community,signed/intellij-community,FHannes/intellij-community,apixandru/intellij-community,semonte/intellij-community,suncycheng/intellij-community,da1z/intellij-community,FHannes/intellij-community,da1z/intellij-community,xfournet/intellij-community,FHannes/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,apixandru/intellij-community,FHannes/intellij-community,signed/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,da1z/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,FHannes/intellij-community,FHannes/intellij-community,ibinti/intellij-community,asedunov/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,signed/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,semonte/intellij-community,vvv1559/intellij-community,allotria/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,signed/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,allotria/intellij-community,semonte/intellij-community,FHannes/intellij-community,apixandru/intellij-community,semonte/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,signed/intellij-community,allotria/intellij-community,suncycheng/intellij-community,semonte/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,signed/intellij-community,asedunov/intellij-community,ibinti/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,signed/intellij-community,allotria/intellij-community,signed/intellij-community,xfournet/intellij-community,xfournet/intellij-community,allotria/intellij-community,allotria/intellij-community,semonte/intellij-community,allotria/intellij-community,ibinti/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,semonte/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,apixandru/intellij-community,da1z/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,asedunov/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,xfournet/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,signed/intellij-community,suncycheng/intellij-community,da1z/intellij-community
/* * Copyright 2000-2017 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.testFramework; import com.intellij.openapi.util.Pair; import com.intellij.util.ThrowableRunnable; import gnu.trove.TLongLongHashMap; import gnu.trove.TObjectLongHashMap; import one.util.streamex.StreamEx; import org.jetbrains.annotations.NotNull; import java.lang.management.GarbageCollectorMXBean; import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.util.ArrayList; import java.util.List; class CpuUsageData { private static final ThreadMXBean ourThreadMXBean = ManagementFactory.getThreadMXBean(); private static final List<GarbageCollectorMXBean> ourGcBeans = ManagementFactory.getGarbageCollectorMXBeans(); final long durationMs; private final long myFreeMb; private final long myTotalMb; private final List<Pair<Long, String>> myGcTimes = new ArrayList<>(); private final List<Pair<Long, String>> myThreadTimes = new ArrayList<>(); private CpuUsageData(long durationMs, TObjectLongHashMap<GarbageCollectorMXBean> gcTimes, TLongLongHashMap threadTimes, long freeMb, long totalMb) { this.durationMs = durationMs; myFreeMb = freeMb; myTotalMb = totalMb; gcTimes.forEachEntry((bean, gcTime) -> { myGcTimes.add(Pair.create(gcTime, bean.getName())); return true; }); threadTimes.forEachEntry((id, time) -> { ThreadInfo info = ourThreadMXBean.getThreadInfo(id); myThreadTimes.add(Pair.create(toMillis(time), info == null ? "<unknown>" : info.getThreadName())); return true; }); } String getGcStats() { return printLongestNames(myGcTimes) + "; free " + myFreeMb + " of " + myTotalMb + "MB"; } String getThreadStats() { return printLongestNames(myThreadTimes); } @NotNull private static String printLongestNames(List<Pair<Long, String>> times) { String stats = StreamEx.of(times) .sortedBy(p -> -p.first) .filter(p -> p.first > 10).limit(10) .map(p -> "\"" + p.second + "\"" + " took " + p.first + "ms") .joining(", "); return stats.isEmpty() ? "insignificant" : stats; } private static long toMillis(long timeNs) { return timeNs / 1_000_000; } static <E extends Throwable> CpuUsageData measureCpuUsage(ThrowableRunnable<E> runnable) throws E { long free = toMb(Runtime.getRuntime().freeMemory()); long total = toMb(Runtime.getRuntime().totalMemory()); TObjectLongHashMap<GarbageCollectorMXBean> gcTimes = new TObjectLongHashMap<>(); for (GarbageCollectorMXBean bean : ourGcBeans) { gcTimes.put(bean, bean.getCollectionTime()); } TLongLongHashMap threadTimes = new TLongLongHashMap(); for (long id : ourThreadMXBean.getAllThreadIds()) { threadTimes.put(id, ourThreadMXBean.getThreadUserTime(id)); } long start = System.currentTimeMillis(); runnable.run(); long duration = System.currentTimeMillis() - start; for (long id : ourThreadMXBean.getAllThreadIds()) { threadTimes.put(id, ourThreadMXBean.getThreadUserTime(id) - threadTimes.get(id)); } for (GarbageCollectorMXBean bean : ourGcBeans) { gcTimes.put(bean, bean.getCollectionTime() - gcTimes.get(bean)); } return new CpuUsageData(duration, gcTimes, threadTimes, free, total); } private static long toMb(long bytes) { return bytes / 1024 / 1024; } }
platform/testFramework/src/com/intellij/testFramework/CpuUsageData.java
/* * Copyright 2000-2017 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.testFramework; import com.intellij.openapi.util.Pair; import com.intellij.util.ThrowableRunnable; import gnu.trove.TLongLongHashMap; import gnu.trove.TObjectLongHashMap; import one.util.streamex.StreamEx; import org.jetbrains.annotations.NotNull; import java.lang.management.GarbageCollectorMXBean; import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.util.ArrayList; import java.util.List; class CpuUsageData { private static final ThreadMXBean ourThreadMXBean = ManagementFactory.getThreadMXBean(); private static final List<GarbageCollectorMXBean> ourGcBeans = ManagementFactory.getGarbageCollectorMXBeans(); final long durationMs; private final TObjectLongHashMap<GarbageCollectorMXBean> myGcTimes; private final TLongLongHashMap myThreadTimes; private CpuUsageData(long durationMs, TObjectLongHashMap<GarbageCollectorMXBean> gcTimes, TLongLongHashMap threadTimes) { this.durationMs = durationMs; myGcTimes = gcTimes; myThreadTimes = threadTimes; } String getGcStats() { List<Pair<Long, String>> times = new ArrayList<>(); myGcTimes.forEachEntry((bean, time) -> { times.add(Pair.create(time, bean.getName())); return true; }); return printLongestNames(times); } String getThreadStats() { List<Pair<Long, String>> times = new ArrayList<>(); myThreadTimes.forEachEntry((id, time) -> { ThreadInfo info = ourThreadMXBean.getThreadInfo(id); times.add(Pair.create(toMillis(time), info == null ? "<unknown>" : info.getThreadName())); return true; }); return printLongestNames(times); } @NotNull private static String printLongestNames(List<Pair<Long, String>> times) { String stats = StreamEx.of(times) .sortedBy(p -> -p.first) .filter(p -> p.first > 10).limit(10) .map(p -> "\"" + p.second + "\"" + " took " + p.first + "ms") .joining(", "); return stats.isEmpty() ? "insignificant" : stats; } private static long toMillis(long timeNs) { return timeNs / 1_000_000; } static <E extends Throwable> CpuUsageData measureCpuUsage(ThrowableRunnable<E> runnable) throws E { TObjectLongHashMap<GarbageCollectorMXBean> gcTimes = new TObjectLongHashMap<>(); for (GarbageCollectorMXBean bean : ourGcBeans) { gcTimes.put(bean, bean.getCollectionTime()); } TLongLongHashMap threadTimes = new TLongLongHashMap(); for (long id : ourThreadMXBean.getAllThreadIds()) { threadTimes.put(id, ourThreadMXBean.getThreadUserTime(id)); } long start = System.currentTimeMillis(); runnable.run(); long duration = System.currentTimeMillis() - start; for (long id : ourThreadMXBean.getAllThreadIds()) { threadTimes.put(id, ourThreadMXBean.getThreadUserTime(id) - threadTimes.get(id)); } for (GarbageCollectorMXBean bean : ourGcBeans) { gcTimes.put(bean, bean.getCollectionTime() - gcTimes.get(bean)); } return new CpuUsageData(duration, gcTimes, threadTimes); } }
performance tests: print free/total memory and get thread names eagerly
platform/testFramework/src/com/intellij/testFramework/CpuUsageData.java
performance tests: print free/total memory and get thread names eagerly
<ide><path>latform/testFramework/src/com/intellij/testFramework/CpuUsageData.java <ide> private static final List<GarbageCollectorMXBean> ourGcBeans = ManagementFactory.getGarbageCollectorMXBeans(); <ide> <ide> final long durationMs; <del> private final TObjectLongHashMap<GarbageCollectorMXBean> myGcTimes; <del> private final TLongLongHashMap myThreadTimes; <add> private final long myFreeMb; <add> private final long myTotalMb; <add> private final List<Pair<Long, String>> myGcTimes = new ArrayList<>(); <add> private final List<Pair<Long, String>> myThreadTimes = new ArrayList<>(); <ide> <del> private CpuUsageData(long durationMs, TObjectLongHashMap<GarbageCollectorMXBean> gcTimes, TLongLongHashMap threadTimes) { <add> private CpuUsageData(long durationMs, TObjectLongHashMap<GarbageCollectorMXBean> gcTimes, TLongLongHashMap threadTimes, long freeMb, long totalMb) { <ide> this.durationMs = durationMs; <del> myGcTimes = gcTimes; <del> myThreadTimes = threadTimes; <add> myFreeMb = freeMb; <add> myTotalMb = totalMb; <add> gcTimes.forEachEntry((bean, gcTime) -> { <add> myGcTimes.add(Pair.create(gcTime, bean.getName())); <add> return true; <add> }); <add> threadTimes.forEachEntry((id, time) -> { <add> ThreadInfo info = ourThreadMXBean.getThreadInfo(id); <add> myThreadTimes.add(Pair.create(toMillis(time), info == null ? "<unknown>" : info.getThreadName())); <add> return true; <add> }); <ide> } <ide> <ide> String getGcStats() { <del> List<Pair<Long, String>> times = new ArrayList<>(); <del> myGcTimes.forEachEntry((bean, time) -> { <del> times.add(Pair.create(time, bean.getName())); <del> return true; <del> }); <del> return printLongestNames(times); <add> return printLongestNames(myGcTimes) + "; free " + myFreeMb + " of " + myTotalMb + "MB"; <ide> } <ide> <ide> String getThreadStats() { <del> List<Pair<Long, String>> times = new ArrayList<>(); <del> myThreadTimes.forEachEntry((id, time) -> { <del> ThreadInfo info = ourThreadMXBean.getThreadInfo(id); <del> times.add(Pair.create(toMillis(time), info == null ? "<unknown>" : info.getThreadName())); <del> return true; <del> }); <del> return printLongestNames(times); <add> return printLongestNames(myThreadTimes); <ide> } <ide> <ide> @NotNull <ide> } <ide> <ide> static <E extends Throwable> CpuUsageData measureCpuUsage(ThrowableRunnable<E> runnable) throws E { <add> long free = toMb(Runtime.getRuntime().freeMemory()); <add> long total = toMb(Runtime.getRuntime().totalMemory()); <add> <ide> TObjectLongHashMap<GarbageCollectorMXBean> gcTimes = new TObjectLongHashMap<>(); <ide> for (GarbageCollectorMXBean bean : ourGcBeans) { <ide> gcTimes.put(bean, bean.getCollectionTime()); <ide> gcTimes.put(bean, bean.getCollectionTime() - gcTimes.get(bean)); <ide> } <ide> <del> return new CpuUsageData(duration, gcTimes, threadTimes); <add> return new CpuUsageData(duration, gcTimes, threadTimes, free, total); <ide> } <ide> <add> private static long toMb(long bytes) { <add> return bytes / 1024 / 1024; <add> } <ide> }
Java
mit
28f5e36034c968973c3a2628374d0b60814c1244
0
eldering/autoanalyst,eldering/autoanalyst,eldering/autoanalyst,eldering/autoanalyst,eldering/autoanalyst,eldering/autoanalyst,eldering/autoanalyst
package model; public class Problem { final String id; final String abbreviation; final String name; public Problem(int id, String name) { this.id = String.format("%d", id); this.abbreviation = ""+Character.toChars(64+id)[0]; this.name = name.trim(); } @Override public String toString() { return String.format("#p%s", abbreviation); } public String getId() { return id; } public String getLetter() { return abbreviation; } public String getName() { String prefix = abbreviation + " - "; if (name.startsWith(prefix)) { return name; } else { return prefix + name; } } }
katalyze/src/model/Problem.java
package model; public class Problem { final String id; final String abbreviation; final String name; public Problem(int id, String name) { this.id = String.format("%d", id); this.abbreviation = ""+Character.toChars(64+id)[0]; this.name = name; } @Override public String toString() { return String.format("#p%s", abbreviation); } public String getId() { return id; } public String getLetter() { return abbreviation; } public String getName() { String prefix = abbreviation + " - "; if (name.startsWith(prefix)) { return name; } else { return prefix + name; } } }
Added trimming of problem names
katalyze/src/model/Problem.java
Added trimming of problem names
<ide><path>atalyze/src/model/Problem.java <ide> public Problem(int id, String name) { <ide> this.id = String.format("%d", id); <ide> this.abbreviation = ""+Character.toChars(64+id)[0]; <del> this.name = name; <add> this.name = name.trim(); <ide> } <ide> <ide> @Override
JavaScript
mit
0b00aecad7b0596d2a0d558893719b4eb86c13b8
0
frnsys/generator-bane,ftzeng/generator-bane
'use strict'; var util = require('util'); var path = require('path'); var yeoman = require('yeoman-generator'); var BaneGenerator = module.exports = function BaneGenerator(args, options, config) { yeoman.generators.Base.apply(this, arguments); this.on('end', function () { this.installDependencies({ skipInstall: options['skip-install'] }); }); this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json'))); }; util.inherits(BaneGenerator, yeoman.generators.Base); BaneGenerator.prototype.askFor = function askFor() { var cb = this.async(); // have Yeoman greet the user. console.log(bane); var prompts = [{ type: 'input', name: 'projectName', message: 'What is your project\'s name?', default: 'Bane' }]; this.prompt(prompts, function (props) { this.projectName = props.projectName; cb(); }.bind(this)); }; BaneGenerator.prototype.app = function app() { this.directory('app', 'app'); this.directory('assets', 'assets'); this.directory('source', 'source'); this.directory('data', 'data'); this.copy('_package.json', 'package.json'); this.copy('_bower.json', 'bower.json'); this.copy('index.html', 'index.html'); this.copy('favicon.ico', 'favicon.ico'); }; BaneGenerator.prototype.projectfiles = function projectfiles() { this.copy('gitignore', '.gitignore'); this.copy('bowerrc', '.bowerrc'); this.copy('csslintrc', '.csslintrc'); this.copy('jshintrc', '.jshintrc'); this.copy('Gruntfile.js', 'Gruntfile.js'); }; BaneGenerator.prototype.h5bp = function h5bp() { var cb = this.async(); this.remote('h5bp', 'html5-boilerplate', function(err, remote) { if (err) { return cb(err); } remote.copy('.htaccess', '.htaccess'); remote.copy('crossdomain.xml', 'crossdomain.xml'); remote.copy('humans.txt', 'humans.txt'); remote.copy('robots.txt', 'robots.txt'); cb(); }); }; BaneGenerator.prototype.stylesheets = function stylesheets() { var cb = this.async(); this.remote('ftzeng', 'atomic', function(err, remote) { if (err) { return cb(err); } remote.directory('.', 'app/styles/'); cb(); }); }; var bane = '\n\t _____ _____ _____ _____ '.blue+ '\n\t| __ | _ | | | __|'.blue+ '\n\t| __ -| | | | | __|'.blue+ '\n\t|_____|__|__|_|___|_____|'.blue+ '\n\n\t [A Yeoman generator]\n\n';
app/index.js
'use strict'; var util = require('util'); var path = require('path'); var yeoman = require('yeoman-generator'); var BaneGenerator = module.exports = function BaneGenerator(args, options, config) { yeoman.generators.Base.apply(this, arguments); this.on('end', function () { this.installDependencies({ skipInstall: options['skip-install'] }); }); this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json'))); }; util.inherits(BaneGenerator, yeoman.generators.Base); BaneGenerator.prototype.askFor = function askFor() { var cb = this.async(); // have Yeoman greet the user. console.log(bane); var prompts = [{ type: 'input', name: 'projectName', message: 'What is your project\'s name?', default: 'Bane' }]; this.prompt(prompts, function (props) { this.projectName = props.projectName; cb(); }.bind(this)); }; BaneGenerator.prototype.app = function app() { this.directory('app', 'app'); this.directory('assets', 'assets'); this.directory('source', 'source'); this.directory('data', 'data'); this.copy('_package.json', 'package.json'); this.copy('_bower.json', 'bower.json'); this.copy('index.html', 'index.html'); this.copy('favicon.ico', 'favicon.ico'); }; BaneGenerator.prototype.projectfiles = function projectfiles() { this.copy('gitignore', '.gitignore'); this.copy('bowerrc', '.bowerrc'); this.copy('csslintrc', '.csslintrc'); this.copy('jshintrc', '.jshintrc'); this.copy('Gruntfile.js', 'Gruntfile.js'); }; BaneGenerator.prototype.stylesheets = function stylesheets() { var cb = this.async(); this.remote('ftzeng', 'atomic', function(err, remote) { if (err) { return cb(err); } remote.directory('.', 'app/styles/'); cb(); }); }; var bane = '\n\t _____ _____ _____ _____ '.blue+ '\n\t| __ | _ | | | __|'.blue+ '\n\t| __ -| | | | | __|'.blue+ '\n\t|_____|__|__|_|___|_____|'.blue+ '\n\n\t [A Yeoman generator]\n\n';
bringing in some h5bp files
app/index.js
bringing in some h5bp files
<ide><path>pp/index.js <ide> this.copy('Gruntfile.js', 'Gruntfile.js'); <ide> }; <ide> <add>BaneGenerator.prototype.h5bp = function h5bp() { <add> var cb = this.async(); <add> <add> this.remote('h5bp', 'html5-boilerplate', function(err, remote) { <add> if (err) { <add> return cb(err); <add> } <add> remote.copy('.htaccess', '.htaccess'); <add> remote.copy('crossdomain.xml', 'crossdomain.xml'); <add> remote.copy('humans.txt', 'humans.txt'); <add> remote.copy('robots.txt', 'robots.txt'); <add> cb(); <add> }); <add>}; <add> <ide> BaneGenerator.prototype.stylesheets = function stylesheets() { <ide> var cb = this.async(); <ide>
JavaScript
agpl-3.0
7641c01638040737c0215f8bba99f0d4e62e8db4
0
ggasoftware/ketcher,ggasoftware/ketcher,ggasoftware/ketcher,ggasoftware/ketcher,ggasoftware/ketcher,ggasoftware/ketcher
/**************************************************************************** * Copyright (C) 2009-2011 GGA Software Services LLC * * This file may be distributed and/or modified under the terms of the * GNU Affero General Public License version 3 as published by the Free * Software Foundation and appearing in the file LICENSE.GPL included in * the packaging of this file. * * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ***************************************************************************/ if (typeof(ui) == 'undefined') ui = function () {}; // // Undo/redo actions // ui.__fixMap = function(map) { // TODO [RB] temporary map.indexOf = function(x) { var ret = [].indexOf.call(this, x); if (ret < 0) ret = this.push(x) - 1; return ret; }; }; ui.atomMap = new Array(); ui.__fixMap(ui.atomMap); ui.bondMap = new Array(); ui.__fixMap(ui.bondMap); ui.sgroupMap = new Array(); ui.Action = function () { this.operations = new Array(); }; ui.Action.OPERATION = { ATOM_POS: 1, /** @deprecated Please use action.addOp(new ui.Action.OpAtomAttr(...)) instead */ ATOM_ATTR: 2, /** @deprecated Please use action.addOp(new ui.Action.OpAtomAdd(...)) instead */ ATOM_ADD: 3, /** @deprecated Please use action.addOp(new ui.Action.OpAtomDelete(...)) instead */ ATOM_DEL: 4, /** @deprecated Please use action.addOp(new ui.Action.OpBondAttr(...)) instead */ BOND_ATTR: 5, /** @deprecated Please use action.addOp(new ui.Action.OpBondAdd(...)) instead */ BOND_ADD: 6, /** @deprecated Please use action.addOp(new ui.Action.OpBondDelete(...)) instead */ BOND_DEL: 7, /** @deprecated Please use action.mergeWith(ui.Action.toBondFlipping(...)) instead */ BOND_FLIP: 8, CANVAS_LOAD: 9, SGROUP_ATTR: 10, SGROUP_ADD: 11, SGROUP_DEL: 12, SGROUP_ATOM_ADD: 13, SGROUP_ATOM_DEL: 14, /** @deprecated Please use action.addOp(new ui.Action.OpRxnArrowDelete(...)) instead */ RXN_ARROW_DEL: 15, /** @deprecated Please use action.addOp(new ui.Action.OpRxnArrowAdd(...)) instead */ RXN_ARROW_ADD: 16, RXN_ARROW_POS: 17, /** @deprecated Please use action.addOp(new ui.Action.OpRxnPlusDelete(...)) instead */ RXN_PLUS_DEL: 18, /** @deprecated Please use action.addOp(new ui.Action.OpRxnPlusAdd(...)) instead */ RXN_PLUS_ADD: 19, RXN_PLUS_POS: 20 }; ui.Action.prototype.addOp = function(op) { this.operations.push(op); return op; }; /** @deprecated addOp to be used instead */ ui.Action.prototype.addOperation = function (type, params) { var op = { type: type, params: params, inverted: { type: null, params: null, inverted: null } }; op.inverted.inverted = op; this.operations.push(op); return op; }; ui.Action.prototype.mergeWith = function (action) { this.operations = this.operations.concat(action.operations); return this; //rbalabanov: let it be possible to chain actions in code easier }; // Perform action and return inverted one ui.Action.prototype.perform = function () { var action = new ui.Action(); var idx = 0; this.operations.each(function (op) { if ('perform' in op) { //TODO [RB] all the operations in the switch statement below are to be re-factored to this form, this "if" to be removed action.addOp(op.perform(ui.editor)); idx++; return; } switch (op.type) { case ui.Action.OPERATION.ATOM_POS: op.inverted.type = ui.Action.OPERATION.ATOM_POS; op.inverted.params = { id: op.params.id, pos: ui.render.atomGetPos(ui.atomMap[op.params.id]) }; ui.render.atomMove(ui.atomMap[op.params.id], op.params.pos); break; case ui.Action.OPERATION.ATOM_ATTR: op.inverted.type = ui.Action.OPERATION.ATOM_ATTR; op.inverted.params = { id: op.params.id, attr_name: op.params.attr_name, attr_value: ui.render.atomGetAttr(ui.atomMap[op.params.id], op.params.attr_name) }; ui.render.atomSetAttr(ui.atomMap[op.params.id], op.params.attr_name, op.params.attr_value); break; case ui.Action.OPERATION.ATOM_ADD: op.inverted.type = ui.Action.OPERATION.ATOM_DEL; var id = ui.render.atomAdd(op.params.pos, op.params.atom); if (op.inverted.params == null) { op.inverted.params = { id: ui.atomMap.push(id) - 1 }; } else ui.atomMap[op.inverted.params.id] = id; break; case ui.Action.OPERATION.ATOM_DEL: op.inverted.type = ui.Action.OPERATION.ATOM_ADD; op.inverted.params = { pos: ui.render.atomGetPos(ui.atomMap[op.params.id]), atom: ui.ctab.atoms.get(ui.atomMap[op.params.id]) }; ui.render.atomRemove(ui.atomMap[op.params.id]); break; case ui.Action.OPERATION.BOND_ATTR: op.inverted.type = ui.Action.OPERATION.BOND_ATTR; op.inverted.params = { id: op.params.id, attr_name: op.params.attr_name, attr_value: ui.render.bondGetAttr(ui.bondMap[op.params.id], op.params.attr_name) }; ui.render.bondSetAttr(ui.bondMap[op.params.id], op.params.attr_name, op.params.attr_value); break; case ui.Action.OPERATION.BOND_ADD: op.inverted.type = ui.Action.OPERATION.BOND_DEL; var id = ui.render.bondAdd(ui.atomMap[op.params.begin], ui.atomMap[op.params.end], op.params.bond); if (op.inverted.params == null) { op.inverted.params = { id: ui.bondMap.push(id) - 1 }; } else ui.bondMap[op.inverted.params.id] = id; break; case ui.Action.OPERATION.BOND_DEL: var bond = ui.ctab.bonds.get(ui.bondMap[op.params.id]); var begin = ui.atomMap.indexOf(bond.begin); var end = ui.atomMap.indexOf(bond.end); op.inverted.type = ui.Action.OPERATION.BOND_ADD; op.inverted.params = { begin: begin, end: end, bond: bond }; ui.render.bondRemove(ui.bondMap[op.params.id]); break; case ui.Action.OPERATION.BOND_FLIP: op.inverted.type = ui.Action.OPERATION.BOND_FLIP; op.inverted.params = { id: op.params.id }; ui.bondMap[op.params.id] = ui.render.bondFlip(ui.bondMap[op.params.id]); break; case ui.Action.OPERATION.CANVAS_LOAD: op.inverted.type = ui.Action.OPERATION.CANVAS_LOAD; if (op.params.atom_map == null) { op.params.atom_map = new Array(); ui.__fixMap(op.params.atom_map); op.params.bond_map = new Array(); ui.__fixMap(op.params.bond_map); op.params.sgroup_map = new Array(); op.params.ctab.atoms.each(function (aid) { op.params.atom_map.push(parseInt(aid)); }, this); op.params.ctab.bonds.each(function (bid) { op.params.bond_map.push(parseInt(bid)); }, this); op.params.ctab.sgroups.each(function (sid) { op.params.sgroup_map.push(parseInt(sid)); }, this); } op.inverted.params = { ctab: ui.ctab, atom_map: ui.atomMap, bond_map: ui.bondMap, sgroup_map: ui.sgroupMap }; ui.render.ctab.clearVisels(); ui.ctab = op.params.ctab; ui.render.setMolecule(ui.ctab); ui.atomMap = op.params.atom_map; ui.bondMap = op.params.bond_map; ui.sgroupMap = op.params.sgroup_map; break; case ui.Action.OPERATION.SGROUP_ATTR: op.inverted.type = ui.Action.OPERATION.SGROUP_ATTR; var id = ui.sgroupMap[op.params.id]; var cur_type = ui.render.sGroupGetType(id); op.inverted.params = { id: op.params.id, type: cur_type, attrs: { mul: ui.render.sGroupGetAttr(id, 'mul'), connectivity: ui.render.sGroupGetAttr(id, 'connectivity'), name: ui.render.sGroupGetAttr(id, 'name'), subscript: ui.render.sGroupGetAttr(id, 'subscript'), fieldName: ui.render.sGroupGetAttr(id, 'fieldName'), fieldValue: ui.render.sGroupGetAttr(id, 'fieldValue') } }; if (op.params.type != op.inverted.params.type) ui.render.sGroupSetType(id, op.params.type); var attrs_hash = new Hash(op.params.attrs); attrs_hash.each(function (attr) { ui.render.sGroupSetAttr(id, attr.key, attr.value); }, this); break; case ui.Action.OPERATION.SGROUP_ATOM_ADD: op.inverted.type = ui.Action.OPERATION.SGROUP_ATOM_DEL; op.inverted.params = { id: op.params.id, sid: op.params.sid }; ui.render.atomAddToSGroup(ui.atomMap[op.params.id], ui.sgroupMap[op.params.sid]); break; case ui.Action.OPERATION.SGROUP_ATOM_DEL: op.inverted.type = ui.Action.OPERATION.SGROUP_ATOM_ADD; op.inverted.params = { id: op.params.id, sid: op.params.sid }; ui.render.atomRemoveFromSGroup(ui.atomMap[op.params.id], ui.sgroupMap[op.params.sid]); break; case ui.Action.OPERATION.SGROUP_ADD: op.inverted.type = ui.Action.OPERATION.SGROUP_DEL; var id = ui.render.sGroupCreate(op.params.type); var attrs_hash = new Hash(op.params.attrs); attrs_hash.each(function (attr) { ui.render.sGroupSetAttr(id, attr.key, attr.value); }, this); op.params.atoms.each(function (aid) { ui.render.atomAddToSGroup(ui.atomMap[aid], id); }, this); if (op.inverted.params == null) { op.inverted.params = { id: ui.sgroupMap.push(id) - 1 }; } else ui.sgroupMap[op.inverted.params.id] = id; break; case ui.Action.OPERATION.SGROUP_DEL: var id = ui.sgroupMap[op.params.id]; var type = ui.render.sGroupGetType(id); var atoms = ui.render.sGroupGetAtoms(id).clone(); var i; for (i = 0; i < atoms.length; i++) atoms[i] = ui.atomMap.indexOf(atoms[i]); op.inverted.type = ui.Action.OPERATION.SGROUP_ADD; op.inverted.params = { type: type, attrs: { mul: ui.render.sGroupGetAttr(id, 'mul'), connectivity: ui.render.sGroupGetAttr(id, 'connectivity'), name: ui.render.sGroupGetAttr(id, 'name'), subscript: ui.render.sGroupGetAttr(id, 'subscript'), fieldName: ui.render.sGroupGetAttr(id, 'fieldName'), fieldValue: ui.render.sGroupGetAttr(id, 'fieldValue') }, atoms: atoms }; // remove highlighting // RB: this call seems to be obsolete // TODO Misha K. review, pls //BEGIN //ui.highlightSGroup(id, false); //END ui.render.sGroupDelete(id); break; case ui.Action.OPERATION.RXN_ARROW_DEL: op.inverted.type = ui.Action.OPERATION.RXN_ARROW_ADD; op.inverted.params = { pos: ui.render.rxnArrowGetPos(op.params.id) }; ui.render.rxnArrowRemove(op.params.id); break; case ui.Action.OPERATION.RXN_ARROW_ADD: op.inverted.type = ui.Action.OPERATION.RXN_ARROW_DEL; if (ui.ctab.rxnArrows.count() < 1) { var id = ui.render.rxnArrowAdd(op.params.pos); op.inverted.params = { id: id }; } break; case ui.Action.OPERATION.RXN_ARROW_POS: op.inverted.type = ui.Action.OPERATION.RXN_ARROW_POS; op.inverted.params = { id: op.params.id, // TODO: fix pos: ui.render.rxnArrowGetPos(op.params.id) }; ui.render.rxnArrowMove(op.params.id, op.params.pos); break; case ui.Action.OPERATION.RXN_PLUS_DEL: op.inverted.type = ui.Action.OPERATION.RXN_PLUS_ADD; op.inverted.params = { pos: ui.render.rxnPlusGetPos(op.params.id) }; ui.render.rxnPlusRemove(op.params.id); break; case ui.Action.OPERATION.RXN_PLUS_ADD: op.inverted.type = ui.Action.OPERATION.RXN_PLUS_DEL; var id = ui.render.rxnPlusAdd(op.params.pos); op.inverted.params = { id: id }; break; case ui.Action.OPERATION.RXN_PLUS_POS: op.inverted.type = ui.Action.OPERATION.RXN_PLUS_POS; op.inverted.params = { id: op.params.id, // TODO: fix pos: ui.render.rxnPlusGetPos(op.params.id) }; ui.render.rxnPlusMove(op.params.id, op.params.pos); break; default: return; } action.operations.push(op.inverted); idx++; }, this); action.operations.reverse(); return action; }; ui.Action.prototype.isDummy = function () { return this.operations.detect(function(op) { if ('isDummy' in op) return !op.isDummy(ui.editor); // TODO [RB] the condition is always true for ui.Action.Op* operations switch (op.type) { case ui.Action.OPERATION.ATOM_POS: return !ui.render.atomGetPos(ui.atomMap[op.params.id]).equals(op.params.pos); case ui.Action.OPERATION.ATOM_ATTR: return ui.render.atomGetAttr(ui.atomMap[op.params.id], op.params.attr_name) != op.params.attr_value; case ui.Action.OPERATION.BOND_ATTR: return ui.render.bondGetAttr(ui.bondMap[op.params.id], op.params.attr_name) != op.params.attr_value; case ui.Action.OPERATION.SGROUP_ATTR: if (ui.render.sGroupGetType(ui.sgroupMap[op.params.id]) == op.params.type) { var attr_hash = new Hash(op.params.attrs); if (Object.isUndefined(attr_hash.detect(function (attr) { return ui.render.sGroupGetAttr(ui.sgroupMap[op.params.id], attr.key) != attr.value; }, this))) return false; } return true; } return true; }, this) == null; }; ui.Action.fromAtomPos = function (id, pos) { var action = new ui.Action(); action.addOperation(ui.Action.OPERATION.ATOM_POS, { id: ui.atomMap.indexOf(id), pos: ui.render.atomGetPos(id) }); if (arguments.length > 1) ui.render.atomMove(id, pos); return action; }; ui.Action.fromSelectedAtomsPos = function(selection) { selection = selection || ui.selection; var action = new ui.Action(); selection.atoms.each( function(id) { action.addOperation( ui.Action.OPERATION.ATOM_POS, { id: ui.atomMap.indexOf(id), pos: ui.render.atomGetPos(id) } ); }, this ); return action; }; ui.Action.fromRxnArrowPos = function (id, pos) { var action = new ui.Action(); action.addOperation(ui.Action.OPERATION.RXN_ARROW_POS, { id: id, pos: ui.render.rxnArrowGetPos(id) }); if (arguments.length > 1) ui.render.rxnArrowMove(id, pos); return action; }; ui.Action.fromSelectedRxnArrowPos = function () { var action = new ui.Action(); ui.selection.rxnArrows.each(function (id) { action.addOperation(ui.Action.OPERATION.RXN_ARROW_POS, { id: id, pos: ui.render.rxnArrowGetPos(id) }); }, this); return action; }; ui.Action.fromRxnPlusPos = function (id, pos) { var action = new ui.Action(); action.addOperation(ui.Action.OPERATION.RXN_PLUS_POS, { id: id, pos: ui.render.rxnPlusGetPos(id) }); if (arguments.length > 1) ui.render.rxnPlusMove(id, pos); return action; }; ui.Action.fromSelectedRxnPlusPos = function () { var action = new ui.Action(); ui.selection.rxnPluses.each(function (id) { action.addOperation(ui.Action.OPERATION.RXN_PLUS_POS, { id: id, pos: ui.render.rxnPlusGetPos(id) }); }, this); return action; }; ui.Action.fromBondPos = function (id) { var action = new ui.Action(); var bond = ui.ctab.bonds.get(id); action.addOperation(ui.Action.OPERATION.ATOM_POS, { id: ui.atomMap.indexOf(bond.begin), pos: ui.render.atomGetPos(bond.begin) }); action.addOperation(ui.Action.OPERATION.ATOM_POS, { id: ui.atomMap.indexOf(bond.end), pos: ui.render.atomGetPos(bond.end) }); return action; }; ui.Action.fromAtomAttrs = function (id, attrs) { var action = new ui.Action(); new Hash(attrs).each(function (attr) { action.addOp(new ui.Action.OpAtomAttr(id, attr.key, attr.value)); }, this); return action.perform(); }; ui.Action.fromSelectedAtomsAttrs = function (attrs) { var action = new ui.Action(); new Hash(attrs).each(function(attr) { ui.selection.atoms.each(function(id) { action.addOp(new ui.Action.OpAtomAttr(id, attr.key, attr.value)); }, this) }, this); return action.perform(); }; ui.Action.fromBondAttrs = function (id, attrs, flip) { var action = new ui.Action(); new Hash(attrs).each(function(attr) { action.addOp(new ui.Action.OpBondAttr(id, attr.key, attr.value)); }, this); if (flip) { action.mergeWith(ui.Action.toBondFlipping(id)); } return action.perform(); }; ui.Action.fromSelectedBondsAttrs = function (attrs, flips) { var action = new ui.Action(); attrs = new Hash(attrs); ui.selection.bonds.each(function(id) { attrs.each(function(attr) { action.addOp(new ui.Action.OpBondAttr(id, attr.key, attr.value)); }, this); }, this); if (flips) flips.each(function (id) { action.mergeWith(ui.Action.toBondFlipping(id)); }, this); return action.perform(); }; ui.Action.fromAtomAddition = function (pos, atom) { atom = Object.clone(atom); var action = new ui.Action(); atom.fragment = action.addOp(new ui.Action.OpFragmentAdd().perform(ui.editor)).frid; action.addOp(new ui.Action.OpAtomAdd(atom, pos).perform(ui.editor)); return action; }; ui.Action.fromBondAddition = function (bond, begin, end, pos, pos2) { var action = new ui.Action(); var frid = null; if (!Object.isNumber(begin)) { if (Object.isNumber(end)) { frid = ui.render.atomGetAttr(end, 'fragment'); } } else { frid = ui.render.atomGetAttr(begin, 'fragment'); if (Object.isNumber(end)) { var frid2 = ui.render.atomGetAttr(end, 'fragment'); if (frid2 != frid && Object.isNumber(frid2)) { var rgid = chem.Struct.RGroup.findRGroupByFragment(ui.render.ctab.molecule.rgroups, frid2); if (!Object.isUndefined(rgid)) { action.mergeWith(ui.Action.fromRGroupFragment(null, frid2)); } ui.render.ctab.molecule.atoms.each(function(aid, atom) { if (atom.fragment == frid2) { action.addOp(new ui.Action.OpAtomAttr(aid, 'fragment', frid).perform(ui.editor)); } }); action.addOp(new ui.Action.OpFragmentDelete(frid2).perform(ui.editor)); } } } if (frid == null) { frid = action.addOp(new ui.Action.OpFragmentAdd().perform(ui.editor)).frid; } if (!Object.isNumber(begin)) { begin.fragment = frid; begin = action.addOp(new ui.Action.OpAtomAdd(begin, pos).perform(ui.editor)).data.aid; pos = pos2; } else { if (ui.render.atomGetAttr(begin, 'label') == '*') { action.addOp(new ui.Action.OpAtomAttr(begin, 'label', 'C').perform(ui.editor)); } } if (!Object.isNumber(end)) { end.fragment = frid; end = action.addOp(new ui.Action.OpAtomAdd(end, pos).perform(ui.editor)).data.aid; } else { if (ui.render.atomGetAttr(end, 'label') == '*') { action.addOp(new ui.Action.OpAtomAttr(end, 'label', 'C').perform(ui.editor)); } } action.addOp(new ui.Action.OpBondAdd(begin, end, bond).perform(ui.editor)); action.operations.reverse(); return [action, begin, end]; }; ui.Action.fromArrowAddition = function (pos) { var action = new ui.Action(); if (ui.ctab.rxnArrows.count() < 1) { action.addOp(new ui.Action.OpRxnArrowAdd(pos).perform(ui.editor)); } return action; }; ui.Action.fromArrowDeletion = function (id) { var action = new ui.Action(); action.addOp(new ui.Action.OpRxnArrowDelete(id)); return action.perform(); }; ui.Action.fromPlusAddition = function (pos) { var action = new ui.Action(); action.addOp(new ui.Action.OpRxnPlusAdd(pos).perform(ui.editor)); return action; }; ui.Action.fromPlusDeletion = function (id) { var action = new ui.Action(); action.addOp(new ui.Action.OpRxnPlusDelete(id)); return action.perform(); }; // Add action operation to remove atom from s-group if needed ui.Action.prototype.removeAtomFromSgroupIfNeeded = function (id) { var sgroups = ui.render.atomGetSGroups(id); if (sgroups.length > 0) { sgroups.each(function (sid) { this.addOperation(ui.Action.OPERATION.SGROUP_ATOM_DEL, { id: ui.atomMap.indexOf(id), sid: ui.sgroupMap.indexOf(sid) }); }, this); return true; } return false; }; // Add action operations to remove whole s-group if needed ui.Action.prototype.removeSgroupIfNeeded = function (atoms) { var sg_counts = new Hash(); atoms.each(function (id) { var sgroups = ui.render.atomGetSGroups(id); sgroups.each(function (sid) { var n = sg_counts.get(sid); if (Object.isUndefined(n)) n = 1; else n++; sg_counts.set(sid, n); }, this); }, this); sg_counts.each(function (sg) { var sid = parseInt(sg.key); var sg_atoms = ui.render.sGroupGetAtoms(sid); if (sg_atoms.length == sg.value) { // delete whole s-group this.addOperation(ui.Action.OPERATION.SGROUP_DEL, { id: ui.sgroupMap.indexOf(sid) }); } }, this); }; ui.Action.fromAtomDeletion = function (id) { var action = new ui.Action(); var atoms_to_remove = new Array(); var frid = ui.ctab.atoms.get(id).fragment; ui.render.atomGetNeighbors(id).each(function (nei) { action.addOp(new ui.Action.OpBondDelete(nei.bid));// [RB] !! if (ui.render.atomGetDegree(nei.aid) == 1) { if (action.removeAtomFromSgroupIfNeeded(nei.aid)) atoms_to_remove.push(nei.aid); action.addOp(new ui.Action.OpAtomDelete(nei.aid)); } }, this); if (action.removeAtomFromSgroupIfNeeded(id)) atoms_to_remove.push(id); action.addOp(new ui.Action.OpAtomDelete(id)); action.removeSgroupIfNeeded(atoms_to_remove); action = action.perform(); action.mergeWith(ui.Action.__fromFragmentSplit(frid)); return action; }; ui.Action.fromBondDeletion = function (id) { var action = new ui.Action(); var bond = ui.ctab.bonds.get(id); var frid = ui.ctab.atoms.get(bond.begin).fragment; var atoms_to_remove = new Array(); action.addOp(new ui.Action.OpBondDelete(id)); if (ui.render.atomGetDegree(bond.begin) == 1) { if (action.removeAtomFromSgroupIfNeeded(bond.begin)) atoms_to_remove.push(bond.begin); action.addOp(new ui.Action.OpAtomDelete(bond.begin)); } if (ui.render.atomGetDegree(bond.end) == 1) { if (action.removeAtomFromSgroupIfNeeded(bond.end)) atoms_to_remove.push(bond.end); action.addOp(new ui.Action.OpAtomDelete(bond.end)); } action.removeSgroupIfNeeded(atoms_to_remove); action = action.perform(); action.mergeWith(ui.Action.__fromFragmentSplit(frid)); return action; }; ui.Action.__fromFragmentSplit = function(frid) { // TODO [RB] the thing is too tricky :) need something else in future var action = new ui.Action(); var rgid = chem.Struct.RGroup.findRGroupByFragment(ui.ctab.rgroups, frid); ui.ctab.atoms.each(function(aid, atom) { if (atom.fragment == frid) { var newfrid = action.addOp(new ui.Action.OpFragmentAdd().perform(ui.editor)).frid; var processAtom = function(aid1) { action.addOp(new ui.Action.OpAtomAttr(aid1, 'fragment', newfrid).perform(ui.editor)); ui.render.atomGetNeighbors(aid1).each(function(nei) { if (ui.ctab.atoms.get(nei.aid).fragment == frid) { processAtom(nei.aid); } }); }; processAtom(aid); if (rgid) { action.mergeWith(ui.Action.fromRGroupFragment(rgid, newfrid)); } } }); if (frid != -1) { action.mergeWith(ui.Action.fromRGroupFragment(0, frid)); action.addOp(new ui.Action.OpFragmentDelete(frid).perform(ui.editor)); } return action; }; ui.Action.fromFragmentAddition = function (atoms, bonds, sgroups, rxnArrows, rxnPluses) { var action = new ui.Action(); /* atoms.each(function (aid) { ui.render.atomGetNeighbors(aid).each(function (nei) { if (ui.selection.bonds.indexOf(nei.bid) == -1) ui.selection.bonds = ui.selection.bonds.concat([nei.bid]); }, this); }, this); */ // TODO: merge close atoms and bonds sgroups.each(function (sid) { var idx = ui.sgroupMap.indexOf(sid); if (idx == -1) idx = ui.sgroupMap.push(sid) - 1; action.addOperation(ui.Action.OPERATION.SGROUP_DEL, { id: idx }); }, this); bonds.each(function (bid) { action.addOp(new ui.Action.OpBondDelete(bid)); }, this); atoms.each(function(aid) { action.addOp(new ui.Action.OpAtomDelete(aid)); }, this); rxnArrows.each(function (id) { action.addOp(new ui.Action.OpRxnArrowDelete(id)); }, this); rxnPluses.each(function (id) { action.addOp(new ui.Action.OpRxnPlusDelete(id)); }, this); action.mergeWith(new ui.Action.__fromFragmentSplit(-1)); return action; }; ui.Action.fromFragmentDeletion = function(selection) { selection = selection || ui.selection; var action = new ui.Action(); var atoms_to_remove = new Array(); var frids = []; selection.atoms.each(function (aid) { ui.render.atomGetNeighbors(aid).each(function (nei) { if (selection.bonds.indexOf(nei.bid) == -1) selection.bonds = selection.bonds.concat([nei.bid]); }, this); }, this); selection.bonds.each(function (bid) { action.addOp(new ui.Action.OpBondDelete(bid)); var bond = ui.ctab.bonds.get(bid); if (selection.atoms.indexOf(bond.begin) == -1 && ui.render.atomGetDegree(bond.begin) == 1) { var frid1 = ui.ctab.atoms.get(bond.begin).fragment; if (frids.indexOf(frid1) < 0) frids.push(frid1); if (action.removeAtomFromSgroupIfNeeded(bond.begin)) atoms_to_remove.push(bond.begin); action.addOp(new ui.Action.OpAtomDelete(bond.begin)); } if (selection.atoms.indexOf(bond.end) == -1 && ui.render.atomGetDegree(bond.end) == 1) { var frid2 = ui.ctab.atoms.get(bond.end).fragment; if (frids.indexOf(frid2) < 0) frids.push(frid2); if (action.removeAtomFromSgroupIfNeeded(bond.end)) atoms_to_remove.push(bond.end); action.addOp(new ui.Action.OpAtomDelete(bond.end)); } }, this); selection.atoms.each(function (aid) { var frid3 = ui.ctab.atoms.get(aid).fragment; if (frids.indexOf(frid3) < 0) frids.push(frid3); if (action.removeAtomFromSgroupIfNeeded(aid)) atoms_to_remove.push(aid); action.addOp(new ui.Action.OpAtomDelete(aid)); }, this); action.removeSgroupIfNeeded(atoms_to_remove); selection.rxnArrows.each(function (id) { action.addOp(new ui.Action.OpRxnArrowDelete(id)); }, this); selection.rxnPluses.each(function (id) { action.addOp(new ui.Action.OpRxnPlusDelete(id)); }, this); action = action.perform(); while (frids.length > 0) action.mergeWith(new ui.Action.__fromFragmentSplit(frids.pop())); return action; }; ui.Action.fromAtomMerge = function (src_id, dst_id) { var action = new ui.Action(); ui.render.atomGetNeighbors(src_id).each(function (nei) { var bond = ui.ctab.bonds.get(nei.bid); var begin, end; if (bond.begin == nei.aid) { begin = nei.aid; end = dst_id; } else { begin = dst_id; end = nei.aid; } if (dst_id != bond.begin && dst_id != bond.end && ui.ctab.findBondId(begin, end) == -1) // TODO: improve this { //TODO [RB] the trick to merge fragments, will find more stright way later //action.addOp(new ui.Action.OpBondAdd(begin, end, bond)); action.mergeWith(ui.Action.fromBondAddition(bond, begin, end)[0].perform()); } action.addOp(new ui.Action.OpBondDelete(nei.bid)); }, this); var attrs = chem.Struct.Atom.getAttrHash(ui.ctab.atoms.get(src_id)); if (ui.render.atomGetDegree(src_id) == 1 && attrs.get('label') == '*') attrs.set('label', 'C'); attrs.each(function(attr) { action.addOp(new ui.Action.OpAtomAttr(dst_id, attr.key, attr.value)); }, this); var sg_changed = action.removeAtomFromSgroupIfNeeded(src_id); action.addOp(new ui.Action.OpAtomDelete(src_id)); if (sg_changed) action.removeSgroupIfNeeded([src_id]); return action.perform(); }; ui.Action.toBondFlipping = function (id) { var bond = ui.ctab.bonds.get(id); var action = new ui.Action(); action.addOp(new ui.Action.OpBondDelete(id)); action.addOp(new ui.Action.OpBondAdd(bond.end, bond.begin, bond)).data.bid = id; return action; }; ui.Action.fromBondFlipping = function(bid) { return ui.Action.toBondFlipping(bid).perform(); }; ui.Action.fromPatternOnCanvas = function (pos, pattern) { var angle = 2 * Math.PI / pattern.length; var l = 1.0 / (2 * Math.sin(angle / 2)); var v = new util.Vec2(0, -l); var action = new ui.Action(); var fragAction = new ui.Action.OpFragmentAdd().perform(ui.editor); pattern.each(function() { action.addOp( new ui.Action.OpAtomAdd( { label: 'C', fragment: fragAction.frid }, util.Vec2.sum(pos, v) ).perform(ui.editor) ); v = v.rotate(angle); }, this); for (var i = 0, n = action.operations.length; i < n; i++) { action.addOp( new ui.Action.OpBondAdd( action.operations[i].data.aid, action.operations[(i + 1) % pattern.length].data.aid, { type: pattern[i] } ).perform(ui.editor) ); } action.operations.reverse(); action.addOp(fragAction); return action; }; ui.Action.fromChain = function (p0, v, nSect, atom_id) { var angle = Math.PI / 6; var dx = Math.cos(angle), dy = Math.sin(angle); var action = new ui.Action(); var frid; if (atom_id != null) { frid = ui.render.atomGetAttr(atom_id, 'fragment'); } else { frid = action.addOp(new ui.Action.OpFragmentAdd().perform(ui.editor)).frid; } var id0 = -1; if (atom_id != null) { id0 = atom_id; } else { id0 = action.addOp(new ui.Action.OpAtomAdd({ label: 'C', fragment : frid }, p0).perform(ui.editor)).data.aid; } nSect.times(function (i) { var pos = new util.Vec2(dx * (i + 1), i & 1 ? 0 : dy).rotate(v).add(p0); var a = ui.render.findClosestAtom(pos, 0.1); var id1 = -1; if (a == null) { id1 = action.addOp(new ui.Action.OpAtomAdd({ label: 'C', fragment : frid }, pos).perform(ui.editor)).data.aid; } else { //TODO [RB] need to merge fragments: is there a way to reuse fromBondAddition (which performs it) instead of using code below??? id1 = a.id; } if (!ui.render.checkBondExists(id0, id1)) { action.addOp(new ui.Action.OpBondAdd(id0, id1, {}).perform(ui.editor)); } id0 = id1; }, this); action.operations.reverse(); return action; }; ui.Action.fromPatternOnAtom = function (aid, pattern) { if (ui.render.atomGetDegree(aid) != 1) { var atom = ui.atomForNewBond(aid); atom.fragment = ui.render.atomGetAttr(aid, 'fragment'); var action_res = ui.Action.fromBondAddition({type: 1}, aid, atom.atom, atom.pos); var action = ui.Action.fromPatternOnElement(action_res[2], pattern, true); action.mergeWith(action_res[0]); return action; } return ui.Action.fromPatternOnElement(aid, pattern, true); }; ui.Action.fromPatternOnElement = function (id, pattern, on_atom) { var angle = (pattern.length - 2) * Math.PI / (2 * pattern.length); var first_idx = 0; //pattern.indexOf(bond.type) + 1; // 0 if there's no var pos = null; // center pos var v = null; // rotating vector from center if (on_atom) { var nei_id = ui.render.atomGetNeighbors(id)[0].aid; var atom_pos = ui.render.atomGetPos(id); pos = util.Vec2.diff(atom_pos, ui.render.atomGetPos(nei_id)); pos = pos.scaled(pos.length() / 2 / Math.cos(angle)); v = pos.negated(); pos.add_(atom_pos); angle = Math.PI - 2 * angle; } else { var bond = ui.ctab.bonds.get(id); var begin_pos = ui.render.atomGetPos(bond.begin); var end_pos = ui.render.atomGetPos(bond.end); v = util.Vec2.diff(end_pos, begin_pos); var l = v.length() / (2 * Math.cos(angle)); v = v.scaled(l / v.length()); var v_sym = v.rotate(-angle); v = v.rotate(angle); pos = util.Vec2.sum(begin_pos, v); var pos_sym = util.Vec2.sum(begin_pos, v_sym); var cnt = 0, bcnt = 0; var cnt_sym = 0, bcnt_sym = 0; // TODO: improve this enumeration ui.ctab.atoms.each(function (a_id) { if (util.Vec2.dist(pos, ui.render.atomGetPos(a_id)) < l * 1.1) { cnt++; bcnt += ui.render.atomGetDegree(a_id); } else if (util.Vec2.dist(pos_sym, ui.render.atomGetPos(a_id)) < l * 1.1) { cnt_sym++; bcnt_sym += ui.render.atomGetDegree(a_id); } }); angle = Math.PI - 2 * angle; if (cnt > cnt_sym || (cnt == cnt_sym && bcnt > bcnt_sym)) { pos = pos_sym; v = v_sym; } else angle = -angle; v = v.negated(); } ui.render.update(); var action = new ui.Action(); var atom_ids = new Array(pattern.length); if (!on_atom) { atom_ids[0] = bond.begin; atom_ids[pattern.length - 1] = bond.end; } var frid = ui.render.ctab.molecule.atoms.get(on_atom ? id : ui.render.ctab.molecule.bonds.get(id).begin).fragment; (pattern.length - (on_atom ? 0 : 1)).times(function(idx) { if (idx > 0 || on_atom) { var new_pos = util.Vec2.sum(pos, v); var a = ui.render.findClosestAtom(new_pos, 0.1); if (a == null) { atom_ids[idx] = action.addOp( new ui.Action.OpAtomAdd({ label: 'C', fragment : frid }, new_pos).perform(ui.editor) ).data.aid; } else { // TODO [RB] need to merge fragments? atom_ids[idx] = a.id; } } v = v.rotate(angle); }, this); var i = 0; pattern.length.times(function(idx) { var begin = atom_ids[idx]; var end = atom_ids[(idx + 1) % pattern.length]; var bond_type = pattern[(first_idx + idx) % pattern.length]; if (!ui.render.checkBondExists(begin, end)) { /* var bond_id = ui.render.bondAdd(begin, end, {type: bond_type}); action.addOperation( ui.Action.OPERATION.BOND_DEL, { id: ui.bondMap.push(bond_id) - 1 } ); */ action.addOp(new ui.Action.OpBondAdd(begin, end, { type: bond_type }).perform(ui.editor)); } else { if (bond_type == chem.Struct.BOND.TYPE.AROMATIC) { var nei = ui.render.atomGetNeighbors(begin); nei.find(function(n) { if (n.aid == end) { var src_type = ui.render.bondGetAttr(n.bid, 'type'); if (src_type != bond_type) { /* action.addOperation( ui.Action.OPERATION.BOND_ATTR, { id: ui.bondMap.indexOf(n.bid), attr_name: 'type', attr_value: src_type } ); ui.render.bondSetAttr(n.bid, 'type', bond_type); */ } return true; } return false; }, this); } } i++; }, this); action.operations.reverse(); return action; }; ui.Action.fromNewCanvas = function (ctab) { var action = new ui.Action(); action.addOperation(ui.Action.OPERATION.CANVAS_LOAD, { ctab: ctab, atom_map: null, bond_map: null, sgroup_map: null }); return action.perform(); }; ui.Action.fromSgroupAttrs = function (id, type, attrs) { var action = new ui.Action(); var id_map = ui.sgroupMap.indexOf(id); var cur_type = ui.render.sGroupGetType(id); action.addOperation(ui.Action.OPERATION.SGROUP_ATTR, { id: id_map, type: type, attrs: attrs }); if ((cur_type == 'SRU' || type == 'SRU') && cur_type != type) { ui.render.sGroupsFindCrossBonds(); var nei_atoms = ui.render.sGroupGetNeighborAtoms(id); if (cur_type == 'SRU') { nei_atoms.each(function(aid) { if (ui.render.atomGetAttr(aid, 'label') == '*') { action.addOp(new ui.Action.OpAtomAttr(aid, 'label', 'C')); } }, this); } else { nei_atoms.each(function (aid) { if (ui.render.atomGetDegree(aid) == 1 && ui.render.atomIsPlainCarbon(aid)) { action.addOp(new ui.Action.OpAtomAttr(aid, 'label', '*')); } }, this); } } return action.perform(); }; ui.Action.fromSgroupDeletion = function (id) { var action = new ui.Action(); if (ui.render.sGroupGetType(id) == 'SRU') { ui.render.sGroupsFindCrossBonds(); var nei_atoms = ui.render.sGroupGetNeighborAtoms(id); nei_atoms.each(function(aid) { if (ui.render.atomGetAttr(aid, 'label') == '*') { action.addOp(new ui.Action.OpAtomAttr(aid, 'label', 'C')); } }, this); } action.addOperation(ui.Action.OPERATION.SGROUP_DEL, { id: ui.sgroupMap.indexOf(id) }); return action.perform(); }; ui.Action.fromSgroupAddition = function (type, attrs, atoms) { var action = new ui.Action(); var i; for (i = 0; i < atoms.length; i++) atoms[i] = ui.atomMap.indexOf(atoms[i]); action.addOperation(ui.Action.OPERATION.SGROUP_ADD, { type: type, attrs: attrs, atoms: atoms }); action = action.perform(); if (type == 'SRU') { var sid = ui.sgroupMap[action.operations[0].params.id]; ui.render.sGroupsFindCrossBonds(); var nei_atoms = ui.render.sGroupGetNeighborAtoms(sid); var asterisk_action = new ui.Action(); nei_atoms.each(function(aid) { if (ui.render.atomGetDegree(aid) == 1 && ui.render.atomIsPlainCarbon(aid)) { asterisk_action.addOp(new ui.Action.OpAtomAttr(aid, 'label', 'C')); } }, this); asterisk_action = asterisk_action.perform(); asterisk_action.mergeWith(action); action = asterisk_action; } return action; }; ui.Action.fromRGroupAttrs = function(id, attrs) { var action = new ui.Action(); new Hash(attrs).each(function(attr) { action.addOp(new ui.Action.OpRGroupAttr(id, attr.key, attr.value)); }, this); return action.perform(); }; ui.Action.fromRGroupFragment = function(rgidNew, frid) { var action = new ui.Action(); action.addOp(new ui.Action.OpRGroupFragment(rgidNew, frid)); return action.perform(); }; ui.Action.fromPaste = function(objects, offset) { offset = offset || new util.Vec2(); var action = new ui.Action(), amap = {}, fmap = {}; // atoms for (var aid = 0; aid < objects.atoms.length; aid++) { var atom = Object.clone(objects.atoms[aid]); if (!(atom.fragment in fmap)) { fmap[atom.fragment] = action.addOp(new ui.Action.OpFragmentAdd().perform(ui.editor)).frid; } atom.fragment = fmap[atom.fragment]; amap[aid] = action.addOp(new ui.Action.OpAtomAdd(atom, atom.pos.add(offset)).perform(ui.editor)).data.aid; } //bonds for (var bid = 0; bid < objects.bonds.length; bid++) { var bond = Object.clone(objects.bonds[bid]); action.addOp(new ui.Action.OpBondAdd(amap[bond.begin], amap[bond.end], bond).perform(ui.editor)); } //sgroups for (var sgid = 0; sgid < objects.sgroups.length; sgid++) { var sgroup = Object.clone(objects.sgroups[sgid]), sgatoms = []; for (var sgaid = 0; sgaid < sgroup.atoms.length; sgaid++) { sgatoms.push(amap[sgroup.atoms[sgaid]]); } var sgaction = ui.Action.fromSgroupAddition(sgroup.type, sgroup, sgatoms); //action.mergeWith(sgaction); for (var iop = sgaction.operations.length - 1; iop >= 0; iop--) { action.addOp(sgaction.operations[iop]); } } //reaction arrows if (ui.editor.render.ctab.rxnArrows.count() < 1) { for (var raid = 0; raid < objects.rxnArrows.length; raid++) { action.addOp(new ui.Action.OpRxnArrowAdd(objects.rxnArrows[raid].pos.add(offset)).perform(ui.editor)); } } //reaction pluses for (var rpid = 0; rpid < objects.rxnPluses.length; rpid++) { action.addOp(new ui.Action.OpRxnPlusAdd(objects.rxnPluses[rpid].pos.add(offset)).perform(ui.editor)); } //thats all action.operations.reverse(); return action; }; ui.addUndoAction = function (action, check_dummy) { if (action == null) return; if (check_dummy != true || !action.isDummy()) { ui.undoStack.push(action); ui.redoStack.clear(); if (ui.undoStack.length > ui.HISTORY_LENGTH) ui.undoStack.splice(0, 1); ui.updateActionButtons(); } }; ui.removeDummyAction = function () { if (ui.undoStack.length != 0 && ui.undoStack.last().isDummy()) { ui.undoStack.pop(); ui.updateActionButtons(); } }; ui.updateActionButtons = function () { if (ui.undoStack.length == 0) $('undo').addClassName('buttonDisabled'); else $('undo').removeClassName('buttonDisabled'); if (ui.redoStack.length == 0) $('redo').addClassName('buttonDisabled'); else $('redo').removeClassName('buttonDisabled'); }; ui.undo = function () { ui.redoStack.push(ui.undoStack.pop().perform()); ui.updateActionButtons(); ui.updateSelection(); }; ui.redo = function () { ui.undoStack.push(ui.redoStack.pop().perform()); ui.updateActionButtons(); ui.updateSelection(); }; ui.Action.OpBase = function() {}; ui.Action.OpBase.prototype._execute = function() { throw new Error('Operation._execute() is not implemented'); }; ui.Action.OpBase.prototype._invert = function() { throw new Error('Operation._invert() is not implemented');}; ui.Action.OpBase.prototype.perform = function(editor) { this._execute(editor); if (!('__inverted' in this)) { this.__inverted = this._invert(); this.__inverted.__inverted = this; } return this.__inverted; }; ui.Action.OpBase.prototype.isDummy = function(editor) { return '_isDummy' in this ? this['_isDummy'](editor) : false; }; ui.Action.OpAtomAdd = function(atom, pos) { this.data = { aid : null, atom : atom, pos : pos }; this._execute = function(editor) { var R = editor.render, RS = R.ctab, DS = RS.molecule; var pp = {}; if (this.data.atom) for (var p in this.data.atom) pp[p] = this.data.atom[p]; pp.label = pp.label || 'C'; if (!Object.isNumber(this.data.aid)) { this.data.aid = DS.atoms.add(new chem.Struct.Atom(pp)); ui.atomMap.indexOf(this.data.aid); // TODO [RB] temporary kludge } else { DS.atoms.set(this.data.aid, new chem.Struct.Atom(pp)); } RS.notifyAtomAdded(this.data.aid); DS._atomSetPos(this.data.aid, new util.Vec2(this.data.pos)); }; this._invert = function() { var ret = new ui.Action.OpAtomDelete(); ret.data = this.data; return ret; }; }; ui.Action.OpAtomAdd.prototype = new ui.Action.OpBase(); ui.Action.OpAtomDelete = function(aid) { this.data = { aid : aid, atom : null, pos : null }; this._execute = function(editor) { var R = editor.render, RS = R.ctab, DS = RS.molecule; if (!this.data.atom) { this.data.atom = DS.atoms.get(this.data.aid); this.data.pos = R.atomGetPos(this.data.aid); } RS.notifyAtomRemoved(this.data.aid); DS.atoms.remove(this.data.aid); }; this._invert = function() { var ret = new ui.Action.OpAtomAdd(); ret.data = this.data; return ret; }; }; ui.Action.OpAtomDelete.prototype = new ui.Action.OpBase(); ui.Action.OpAtomAttr = function(aid, attribute, value) { this.data = { aid : aid, attribute : attribute, value : value }; this.data2 = null; this._execute = function(editor) { var atom = editor.render.ctab.molecule.atoms.get(this.data.aid); if (!this.data2) { this.data2 = { aid : this.data.aid, attribute : this.data.attribute, value : atom[this.data.attribute] }; } if (this.data.attribute == 'label' && this.data.value != null) // HACK TODO review atom['atomList'] = null; atom[this.data.attribute] = this.data.value; editor.render.invalidateAtom(this.data.aid); }; this._isDummy = function(editor) { return editor.render.ctab.molecule.atoms.get(this.data.aid)[this.data.attribute] == this.data.value; }; this._invert = function() { var ret = new ui.Action.OpAtomAttr(); ret.data = this.data2; ret.data2 = this.data; return ret; }; }; ui.Action.OpAtomAttr.prototype = new ui.Action.OpBase(); ui.Action.OpSGroupAtomAdd = function(sgid, aid) { this.data = { 'aid' : aid, 'sgid' : sgid }; this._execute = function(editor) { var R = editor.render, RS = R.ctab, DS = RS.molecule; var aid = this.data.aid; var sgid = this.data.sgid; var atom = DS.atoms.get(aid); var sg = DS.sgroups.get(sgid); chem.SGroup.addAtom(sg, aid); util.Set.add(atom.sgs, sgid); R.invalidateAtom(aid); }; this._invert = function() { var ret = new ui.Action.OpAtomDelete(); ret.data = this.data; return ret; }; }; ui.Action.OpSGroupAtomAdd.prototype = new ui.Action.OpBase(); ui.Action.OpSGroupAtomRemove = function(sgid, aid) { this.data = { 'aid' : aid, 'sgid' : sgid }; this._execute = function(editor) { var aid = this.data.aid; var sgid = this.data.sgid; var R = editor.render, RS = R.ctab, DS = RS.molecule; var atom = DS.atoms.get(aid); var sg = DS.sgroups.get(sgid); chem.SGroup.removeAtom(sg, aid); util.Set.remove(atom.sgs, sgid); R.invalidateAtom(aid); }; this._invert = function() { var ret = new ui.Action.OpSGroupAtomAdd(); ret.data = this.data; return ret; }; }; ui.Action.OpSGroupAtomRemove.prototype = new ui.Action.OpBase(); ui.Action.OpBondAdd = function(begin, end, bond) { this.data = { bid : null, bond : bond, begin : begin, end : end }; this._execute = function(editor) { var R = editor.render, RS = R.ctab, DS = RS.molecule; if (this.data.begin == this.data.end) throw new Error("Distinct atoms expected"); if (rnd.DEBUG && this.molecule.checkBondExists(this.data.begin, this.data.end)) throw new Error("Bond already exists"); R.invalidateAtom(this.data.begin, 1); R.invalidateAtom(this.data.end, 1); var pp = {}; if (this.data.bond) for (var p in this.data.bond) pp[p] = this.data.bond[p]; pp.type = pp.type || chem.Struct.BOND.TYPE.SINGLE; pp.begin = this.data.begin; pp.end = this.data.end; if (!Object.isNumber(this.data.bid)) { this.data.bid = DS.bonds.add(new chem.Struct.Bond(pp)); ui.bondMap.indexOf(this.data.bid); // TODO [RB] temporary kludge } else { DS.bonds.set(this.data.bid, new chem.Struct.Bond(pp)); } DS.bondInitHalfBonds(this.data.bid); DS.atomAddNeighbor(DS.bonds.get(this.data.bid).hb1); DS.atomAddNeighbor(DS.bonds.get(this.data.bid).hb2); RS.notifyBondAdded(this.data.bid); }; this._invert = function() { var ret = new ui.Action.OpBondDelete(); ret.data = this.data; return ret; }; }; ui.Action.OpBondAdd.prototype = new ui.Action.OpBase(); ui.Action.OpBondDelete = function(bid) { this.data = { bid : bid, bond : null, begin : null, end : null }; this._execute = function(editor) { var R = editor.render, RS = R.ctab, DS = RS.molecule; if (!this.data.bond) { this.data.bond = DS.bonds.get(this.data.bid); this.data.begin = this.data.bond.begin; this.data.end = this.data.bond.end; } R.invalidateBond(this.data.bid); RS.notifyBondRemoved(this.data.bid); var bond = DS.bonds.get(this.data.bid); [bond.hb1, bond.hb2].each(function(hbid) { var hb = DS.halfBonds.get(hbid); var atom = DS.atoms.get(hb.begin); var pos = atom.neighbors.indexOf(hbid); var prev = (pos + atom.neighbors.length - 1) % atom.neighbors.length; var next = (pos + 1) % atom.neighbors.length; DS.setHbNext(atom.neighbors[prev], atom.neighbors[next]); atom.neighbors.splice(pos, 1); }, this); DS.halfBonds.unset(bond.hb1); DS.halfBonds.unset(bond.hb2); DS.bonds.remove(this.data.bid); }; this._invert = function() { var ret = new ui.Action.OpBondAdd(); ret.data = this.data; return ret; }; }; ui.Action.OpBondDelete.prototype = new ui.Action.OpBase(); ui.Action.OpBondAttr = function(bid, attribute, value) { this.data = { bid : bid, attribute : attribute, value : value }; this.data2 = null; this._execute = function(editor) { var bond = editor.render.ctab.molecule.bonds.get(this.data.bid); if (!this.data2) { this.data2 = { bid : this.data.bid, attribute : this.data.attribute, value : bond[this.data.attribute] }; } bond[this.data.attribute] = this.data.value; editor.render.invalidateBond(this.data.bid, this.data.attribute == 'type' ? 1 : 0); }; this._isDummy = function(editor) { return editor.render.ctab.molecule.bonds.get(this.data.bid)[this.data.attribute] == this.data.value; }; this._invert = function() { var ret = new ui.Action.OpBondAttr(); ret.data = this.data2; ret.data2 = this.data; return ret; }; }; ui.Action.OpBondAttr.prototype = new ui.Action.OpBase(); ui.Action.OpFragmentAdd = function(frid) { this.frid = Object.isUndefined(frid) ? null : frid; this._execute = function(editor) { var RS = editor.render.ctab, DS = RS.molecule; var frag = new chem.Struct.Fragment(); if (this.frid == null) { this.frid = DS.frags.add(frag); } else { DS.frags.set(this.frid, frag); } RS.frags.set(this.frid, new rnd.ReFrag(frag)); // TODO add ReStruct.notifyFragmentAdded }; this._invert = function() { return new ui.Action.OpFragmentDelete(this.frid); }; }; ui.Action.OpFragmentAdd.prototype = new ui.Action.OpBase(); ui.Action.OpFragmentDelete = function(frid) { this.frid = frid; this._execute = function(editor) { var R = editor.render, RS = R.ctab, DS = RS.molecule; R.invalidateItem('frags', this.frid, 1); RS.frags.unset(this.frid); DS.frags.remove(this.frid); // TODO add ReStruct.notifyFragmentRemoved }; this._invert = function() { return new ui.Action.OpFragmentAdd(this.frid); }; }; ui.Action.OpFragmentDelete.prototype = new ui.Action.OpBase(); ui.Action.OpRGroupAttr = function(rgid, attribute, value) { this.data = { rgid : rgid, attribute : attribute, value : value }; this.data2 = null; this._execute = function(editor) { var rgp = editor.render.ctab.molecule.rgroups.get(this.data.rgid); if (!this.data2) { this.data2 = { rgid : this.data.rgid, attribute : this.data.attribute, value : rgp[this.data.attribute] }; } rgp[this.data.attribute] = this.data.value; editor.render.invalidateItem('rgroups', this.data.rgid); }; this._isDummy = function(editor) { return editor.render.ctab.molecule.rgroups.get(this.data.rgid)[this.data.attribute] == this.data.value; }; this._invert = function() { var ret = new ui.Action.OpRGroupAttr(); ret.data = this.data2; ret.data2 = this.data; return ret; }; }; ui.Action.OpRGroupAttr.prototype = new ui.Action.OpBase(); ui.Action.OpRGroupFragment = function(rgid, frid) { this.rgid_new = rgid; this.rgid_old = null; this.frid = frid; this._execute = function(editor) { var RS = editor.render.ctab, DS = RS.molecule; this.rgid_old = this.rgid_old || chem.Struct.RGroup.findRGroupByFragment(DS.rgroups, this.frid); var rgOld = (this.rgid_old ? DS.rgroups.get(this.rgid_old) : null); if (rgOld) { rgOld.frags.remove(rgOld.frags.keyOf(this.frid)); RS.clearVisel(RS.rgroups.get(this.rgid_old).visel); if (rgOld.frags.count() == 0) { RS.rgroups.unset(this.rgid_old); DS.rgroups.unset(this.rgid_old); RS.markItemRemoved(); } else { RS.markItem('rgroups', this.rgid_old, 1); } } if (this.rgid_new) { var rgNew = DS.rgroups.get(this.rgid_new); if (!rgNew) { rgNew = new chem.Struct.RGroup(); DS.rgroups.set(this.rgid_new, rgNew); RS.rgroups.set(this.rgid_new, new rnd.ReRGroup(rgNew)); } else { RS.markItem('rgroups', this.rgid_new, 1); } rgNew.frags.add(this.frid); } }; this._invert = function() { return new ui.Action.OpRGroupFragment(this.rgid_old, this.frid); }; }; ui.Action.OpRGroupFragment.prototype = new ui.Action.OpBase(); ui.Action.OpRxnArrowAdd = function(pos) { this.data = { arid : null, pos : pos }; this._execute = function(editor) { var R = editor.render, RS = R.ctab, DS = RS.molecule; if (!Object.isNumber(this.data.arid)) { this.data.arid = DS.rxnArrows.add(new chem.Struct.RxnArrow()); } else { DS.rxnArrows.set(this.data.arid, new chem.Struct.RxnArrow()); } RS.notifyRxnArrowAdded(this.data.arid); DS._rxnArrowSetPos(this.data.arid, new util.Vec2(this.data.pos)); R.invalidateItem('rxnArrows', this.data.arid, 1); }; this._invert = function() { var ret = new ui.Action.OpRxnArrowDelete(); ret.data = this.data; return ret; }; }; ui.Action.OpRxnArrowAdd.prototype = new ui.Action.OpBase(); ui.Action.OpRxnArrowDelete = function(arid) { this.data = { arid : arid, pos : null }; this._execute = function(editor) { var R = editor.render, RS = R.ctab, DS = RS.molecule; if (!this.data.pos) { this.data.pos = R.rxnArrowGetPos(this.data.arid); } RS.notifyRxnArrowRemoved(this.data.arid); DS.rxnArrows.remove(this.data.arid); }; this._invert = function() { var ret = new ui.Action.OpRxnArrowAdd(); ret.data = this.data; return ret; }; }; ui.Action.OpRxnArrowDelete.prototype = new ui.Action.OpBase(); ui.Action.OpRxnPlusAdd = function(pos) { this.data = { plid : null, pos : pos }; this._execute = function(editor) { var R = editor.render, RS = R.ctab, DS = RS.molecule; if (!Object.isNumber(this.data.plid)) { this.data.plid = DS.rxnPluses.add(new chem.Struct.RxnPlus()); } else { DS.rxnPluses.set(this.data.plid, new chem.Struct.RxnPlus()); } RS.notifyRxnPlusAdded(this.data.plid); DS._rxnPlusSetPos(this.data.plid, new util.Vec2(this.data.pos)); R.invalidateItem('rxnPluses', this.data.plid, 1); }; this._invert = function() { var ret = new ui.Action.OpRxnPlusDelete(); ret.data = this.data; return ret; }; }; ui.Action.OpRxnPlusAdd.prototype = new ui.Action.OpBase(); ui.Action.OpRxnPlusDelete = function(plid) { this.data = { plid : plid, pos : null }; this._execute = function(editor) { var R = editor.render, RS = R.ctab, DS = RS.molecule; if (!this.data.pos) { this.data.pos = R.rxnPlusGetPos(this.data.plid); } RS.notifyRxnPlusRemoved(this.data.plid); DS.rxnPluses.remove(this.data.plid); }; this._invert = function() { var ret = new ui.Action.OpRxnPlusAdd(); ret.data = this.data; return ret; }; }; ui.Action.OpRxnPlusDelete.prototype = new ui.Action.OpBase();
ui/actions.js
/**************************************************************************** * Copyright (C) 2009-2011 GGA Software Services LLC * * This file may be distributed and/or modified under the terms of the * GNU Affero General Public License version 3 as published by the Free * Software Foundation and appearing in the file LICENSE.GPL included in * the packaging of this file. * * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ***************************************************************************/ if (typeof(ui) == 'undefined') ui = function () {}; // // Undo/redo actions // ui.__fixMap = function(map) { // TODO [RB] temporary map.indexOf = function(x) { var ret = [].indexOf.call(this, x); if (ret < 0) ret = this.push(x) - 1; return ret; }; }; ui.atomMap = new Array(); ui.__fixMap(ui.atomMap); ui.bondMap = new Array(); ui.__fixMap(ui.bondMap); ui.sgroupMap = new Array(); ui.Action = function () { this.operations = new Array(); }; ui.Action.OPERATION = { ATOM_POS: 1, /** @deprecated Please use action.addOp(new ui.Action.OpAtomAttr(...)) instead */ ATOM_ATTR: 2, /** @deprecated Please use action.addOp(new ui.Action.OpAtomAdd(...)) instead */ ATOM_ADD: 3, /** @deprecated Please use action.addOp(new ui.Action.OpAtomDelete(...)) instead */ ATOM_DEL: 4, /** @deprecated Please use action.addOp(new ui.Action.OpBondAttr(...)) instead */ BOND_ATTR: 5, /** @deprecated Please use action.addOp(new ui.Action.OpBondAdd(...)) instead */ BOND_ADD: 6, /** @deprecated Please use action.addOp(new ui.Action.OpBondDelete(...)) instead */ BOND_DEL: 7, /** @deprecated Please use action.mergeWith(ui.Action.toBondFlipping(...)) instead */ BOND_FLIP: 8, CANVAS_LOAD: 9, SGROUP_ATTR: 10, SGROUP_ADD: 11, SGROUP_DEL: 12, SGROUP_ATOM_ADD: 13, SGROUP_ATOM_DEL: 14, /** @deprecated Please use action.addOp(new ui.Action.OpRxnArrowDelete(...)) instead */ RXN_ARROW_DEL: 15, /** @deprecated Please use action.addOp(new ui.Action.OpRxnArrowAdd(...)) instead */ RXN_ARROW_ADD: 16, RXN_ARROW_POS: 17, /** @deprecated Please use action.addOp(new ui.Action.OpRxnPlusDelete(...)) instead */ RXN_PLUS_DEL: 18, /** @deprecated Please use action.addOp(new ui.Action.OpRxnPlusAdd(...)) instead */ RXN_PLUS_ADD: 19, RXN_PLUS_POS: 20 }; ui.Action.prototype.addOp = function(op) { this.operations.push(op); return op; }; /** @deprecated addOp to be used instead */ ui.Action.prototype.addOperation = function (type, params) { var op = { type: type, params: params, inverted: { type: null, params: null, inverted: null } }; op.inverted.inverted = op; this.operations.push(op); return op; }; ui.Action.prototype.mergeWith = function (action) { this.operations = this.operations.concat(action.operations); return this; //rbalabanov: let it be possible to chain actions in code easier }; // Perform action and return inverted one ui.Action.prototype.perform = function () { var action = new ui.Action(); var idx = 0; this.operations.each(function (op) { if ('perform' in op) { //TODO [RB] all the operations in the switch statement below are to be re-factored to this form, this "if" to be removed action.addOp(op.perform(ui.editor)); idx++; return; } switch (op.type) { case ui.Action.OPERATION.ATOM_POS: op.inverted.type = ui.Action.OPERATION.ATOM_POS; op.inverted.params = { id: op.params.id, pos: ui.render.atomGetPos(ui.atomMap[op.params.id]) }; ui.render.atomMove(ui.atomMap[op.params.id], op.params.pos); break; case ui.Action.OPERATION.ATOM_ATTR: op.inverted.type = ui.Action.OPERATION.ATOM_ATTR; op.inverted.params = { id: op.params.id, attr_name: op.params.attr_name, attr_value: ui.render.atomGetAttr(ui.atomMap[op.params.id], op.params.attr_name) }; ui.render.atomSetAttr(ui.atomMap[op.params.id], op.params.attr_name, op.params.attr_value); break; case ui.Action.OPERATION.ATOM_ADD: op.inverted.type = ui.Action.OPERATION.ATOM_DEL; var id = ui.render.atomAdd(op.params.pos, op.params.atom); if (op.inverted.params == null) { op.inverted.params = { id: ui.atomMap.push(id) - 1 }; } else ui.atomMap[op.inverted.params.id] = id; break; case ui.Action.OPERATION.ATOM_DEL: op.inverted.type = ui.Action.OPERATION.ATOM_ADD; op.inverted.params = { pos: ui.render.atomGetPos(ui.atomMap[op.params.id]), atom: ui.ctab.atoms.get(ui.atomMap[op.params.id]) }; ui.render.atomRemove(ui.atomMap[op.params.id]); break; case ui.Action.OPERATION.BOND_ATTR: op.inverted.type = ui.Action.OPERATION.BOND_ATTR; op.inverted.params = { id: op.params.id, attr_name: op.params.attr_name, attr_value: ui.render.bondGetAttr(ui.bondMap[op.params.id], op.params.attr_name) }; ui.render.bondSetAttr(ui.bondMap[op.params.id], op.params.attr_name, op.params.attr_value); break; case ui.Action.OPERATION.BOND_ADD: op.inverted.type = ui.Action.OPERATION.BOND_DEL; var id = ui.render.bondAdd(ui.atomMap[op.params.begin], ui.atomMap[op.params.end], op.params.bond); if (op.inverted.params == null) { op.inverted.params = { id: ui.bondMap.push(id) - 1 }; } else ui.bondMap[op.inverted.params.id] = id; break; case ui.Action.OPERATION.BOND_DEL: var bond = ui.ctab.bonds.get(ui.bondMap[op.params.id]); var begin = ui.atomMap.indexOf(bond.begin); var end = ui.atomMap.indexOf(bond.end); op.inverted.type = ui.Action.OPERATION.BOND_ADD; op.inverted.params = { begin: begin, end: end, bond: bond }; ui.render.bondRemove(ui.bondMap[op.params.id]); break; case ui.Action.OPERATION.BOND_FLIP: op.inverted.type = ui.Action.OPERATION.BOND_FLIP; op.inverted.params = { id: op.params.id }; ui.bondMap[op.params.id] = ui.render.bondFlip(ui.bondMap[op.params.id]); break; case ui.Action.OPERATION.CANVAS_LOAD: op.inverted.type = ui.Action.OPERATION.CANVAS_LOAD; if (op.params.atom_map == null) { op.params.atom_map = new Array(); ui.__fixMap(op.params.atom_map); op.params.bond_map = new Array(); ui.__fixMap(op.params.bond_map); op.params.sgroup_map = new Array(); op.params.ctab.atoms.each(function (aid) { op.params.atom_map.push(parseInt(aid)); }, this); op.params.ctab.bonds.each(function (bid) { op.params.bond_map.push(parseInt(bid)); }, this); op.params.ctab.sgroups.each(function (sid) { op.params.sgroup_map.push(parseInt(sid)); }, this); } op.inverted.params = { ctab: ui.ctab, atom_map: ui.atomMap, bond_map: ui.bondMap, sgroup_map: ui.sgroupMap }; ui.render.ctab.clearVisels(); ui.ctab = op.params.ctab; ui.render.setMolecule(ui.ctab); ui.atomMap = op.params.atom_map; ui.bondMap = op.params.bond_map; ui.sgroupMap = op.params.sgroup_map; break; case ui.Action.OPERATION.SGROUP_ATTR: op.inverted.type = ui.Action.OPERATION.SGROUP_ATTR; var id = ui.sgroupMap[op.params.id]; var cur_type = ui.render.sGroupGetType(id); op.inverted.params = { id: op.params.id, type: cur_type, attrs: { mul: ui.render.sGroupGetAttr(id, 'mul'), connectivity: ui.render.sGroupGetAttr(id, 'connectivity'), name: ui.render.sGroupGetAttr(id, 'name'), subscript: ui.render.sGroupGetAttr(id, 'subscript'), fieldName: ui.render.sGroupGetAttr(id, 'fieldName'), fieldValue: ui.render.sGroupGetAttr(id, 'fieldValue') } }; if (op.params.type != op.inverted.params.type) ui.render.sGroupSetType(id, op.params.type); var attrs_hash = new Hash(op.params.attrs); attrs_hash.each(function (attr) { ui.render.sGroupSetAttr(id, attr.key, attr.value); }, this); break; case ui.Action.OPERATION.SGROUP_ATOM_ADD: op.inverted.type = ui.Action.OPERATION.SGROUP_ATOM_DEL; op.inverted.params = { id: op.params.id, sid: op.params.sid }; ui.render.atomAddToSGroup(ui.atomMap[op.params.id], ui.sgroupMap[op.params.sid]); break; case ui.Action.OPERATION.SGROUP_ATOM_DEL: op.inverted.type = ui.Action.OPERATION.SGROUP_ATOM_ADD; op.inverted.params = { id: op.params.id, sid: op.params.sid }; ui.render.atomRemoveFromSGroup(ui.atomMap[op.params.id], ui.sgroupMap[op.params.sid]); break; case ui.Action.OPERATION.SGROUP_ADD: op.inverted.type = ui.Action.OPERATION.SGROUP_DEL; var id = ui.render.sGroupCreate(op.params.type); var attrs_hash = new Hash(op.params.attrs); attrs_hash.each(function (attr) { ui.render.sGroupSetAttr(id, attr.key, attr.value); }, this); op.params.atoms.each(function (aid) { ui.render.atomAddToSGroup(ui.atomMap[aid], id); }, this); if (op.inverted.params == null) { op.inverted.params = { id: ui.sgroupMap.push(id) - 1 }; } else ui.sgroupMap[op.inverted.params.id] = id; break; case ui.Action.OPERATION.SGROUP_DEL: var id = ui.sgroupMap[op.params.id]; var type = ui.render.sGroupGetType(id); var atoms = ui.render.sGroupGetAtoms(id).clone(); var i; for (i = 0; i < atoms.length; i++) atoms[i] = ui.atomMap.indexOf(atoms[i]); op.inverted.type = ui.Action.OPERATION.SGROUP_ADD; op.inverted.params = { type: type, attrs: { mul: ui.render.sGroupGetAttr(id, 'mul'), connectivity: ui.render.sGroupGetAttr(id, 'connectivity'), name: ui.render.sGroupGetAttr(id, 'name'), subscript: ui.render.sGroupGetAttr(id, 'subscript'), fieldName: ui.render.sGroupGetAttr(id, 'fieldName'), fieldValue: ui.render.sGroupGetAttr(id, 'fieldValue') }, atoms: atoms }; // remove highlighting // RB: this call seems to be obsolete // TODO Misha K. review, pls //BEGIN //ui.highlightSGroup(id, false); //END ui.render.sGroupDelete(id); break; case ui.Action.OPERATION.RXN_ARROW_DEL: op.inverted.type = ui.Action.OPERATION.RXN_ARROW_ADD; op.inverted.params = { pos: ui.render.rxnArrowGetPos(op.params.id) }; ui.render.rxnArrowRemove(op.params.id); break; case ui.Action.OPERATION.RXN_ARROW_ADD: op.inverted.type = ui.Action.OPERATION.RXN_ARROW_DEL; if (ui.ctab.rxnArrows.count() < 1) { var id = ui.render.rxnArrowAdd(op.params.pos); op.inverted.params = { id: id }; } break; case ui.Action.OPERATION.RXN_ARROW_POS: op.inverted.type = ui.Action.OPERATION.RXN_ARROW_POS; op.inverted.params = { id: op.params.id, // TODO: fix pos: ui.render.rxnArrowGetPos(op.params.id) }; ui.render.rxnArrowMove(op.params.id, op.params.pos); break; case ui.Action.OPERATION.RXN_PLUS_DEL: op.inverted.type = ui.Action.OPERATION.RXN_PLUS_ADD; op.inverted.params = { pos: ui.render.rxnPlusGetPos(op.params.id) }; ui.render.rxnPlusRemove(op.params.id); break; case ui.Action.OPERATION.RXN_PLUS_ADD: op.inverted.type = ui.Action.OPERATION.RXN_PLUS_DEL; var id = ui.render.rxnPlusAdd(op.params.pos); op.inverted.params = { id: id }; break; case ui.Action.OPERATION.RXN_PLUS_POS: op.inverted.type = ui.Action.OPERATION.RXN_PLUS_POS; op.inverted.params = { id: op.params.id, // TODO: fix pos: ui.render.rxnPlusGetPos(op.params.id) }; ui.render.rxnPlusMove(op.params.id, op.params.pos); break; default: return; } action.operations.push(op.inverted); idx++; }, this); action.operations.reverse(); return action; }; ui.Action.prototype.isDummy = function () { return this.operations.detect(function(op) { if ('isDummy' in op) return !op.isDummy(ui.editor); // TODO [RB] the condition is always true for ui.Action.Op* operations switch (op.type) { case ui.Action.OPERATION.ATOM_POS: return !ui.render.atomGetPos(ui.atomMap[op.params.id]).equals(op.params.pos); case ui.Action.OPERATION.ATOM_ATTR: return ui.render.atomGetAttr(ui.atomMap[op.params.id], op.params.attr_name) != op.params.attr_value; case ui.Action.OPERATION.BOND_ATTR: return ui.render.bondGetAttr(ui.bondMap[op.params.id], op.params.attr_name) != op.params.attr_value; case ui.Action.OPERATION.SGROUP_ATTR: if (ui.render.sGroupGetType(ui.sgroupMap[op.params.id]) == op.params.type) { var attr_hash = new Hash(op.params.attrs); if (Object.isUndefined(attr_hash.detect(function (attr) { return ui.render.sGroupGetAttr(ui.sgroupMap[op.params.id], attr.key) != attr.value; }, this))) return false; } return true; } return true; }, this) == null; }; ui.Action.fromAtomPos = function (id, pos) { var action = new ui.Action(); action.addOperation(ui.Action.OPERATION.ATOM_POS, { id: ui.atomMap.indexOf(id), pos: ui.render.atomGetPos(id) }); if (arguments.length > 1) ui.render.atomMove(id, pos); return action; }; ui.Action.fromSelectedAtomsPos = function(selection) { selection = selection || ui.selection; var action = new ui.Action(); selection.atoms.each( function(id) { action.addOperation( ui.Action.OPERATION.ATOM_POS, { id: ui.atomMap.indexOf(id), pos: ui.render.atomGetPos(id) } ); }, this ); return action; }; ui.Action.fromRxnArrowPos = function (id, pos) { var action = new ui.Action(); action.addOperation(ui.Action.OPERATION.RXN_ARROW_POS, { id: id, pos: ui.render.rxnArrowGetPos(id) }); if (arguments.length > 1) ui.render.rxnArrowMove(id, pos); return action; }; ui.Action.fromSelectedRxnArrowPos = function () { var action = new ui.Action(); ui.selection.rxnArrows.each(function (id) { action.addOperation(ui.Action.OPERATION.RXN_ARROW_POS, { id: id, pos: ui.render.rxnArrowGetPos(id) }); }, this); return action; }; ui.Action.fromRxnPlusPos = function (id, pos) { var action = new ui.Action(); action.addOperation(ui.Action.OPERATION.RXN_PLUS_POS, { id: id, pos: ui.render.rxnPlusGetPos(id) }); if (arguments.length > 1) ui.render.rxnPlusMove(id, pos); return action; }; ui.Action.fromSelectedRxnPlusPos = function () { var action = new ui.Action(); ui.selection.rxnPluses.each(function (id) { action.addOperation(ui.Action.OPERATION.RXN_PLUS_POS, { id: id, pos: ui.render.rxnPlusGetPos(id) }); }, this); return action; }; ui.Action.fromBondPos = function (id) { var action = new ui.Action(); var bond = ui.ctab.bonds.get(id); action.addOperation(ui.Action.OPERATION.ATOM_POS, { id: ui.atomMap.indexOf(bond.begin), pos: ui.render.atomGetPos(bond.begin) }); action.addOperation(ui.Action.OPERATION.ATOM_POS, { id: ui.atomMap.indexOf(bond.end), pos: ui.render.atomGetPos(bond.end) }); return action; }; ui.Action.fromAtomAttrs = function (id, attrs) { var action = new ui.Action(); new Hash(attrs).each(function (attr) { action.addOp(new ui.Action.OpAtomAttr(id, attr.key, attr.value)); }, this); return action.perform(); }; ui.Action.fromSelectedAtomsAttrs = function (attrs) { var action = new ui.Action(); new Hash(attrs).each(function(attr) { ui.selection.atoms.each(function(id) { action.addOp(new ui.Action.OpAtomAttr(id, attr.key, attr.value)); }, this) }, this); return action.perform(); }; ui.Action.fromBondAttrs = function (id, attrs, flip) { var action = new ui.Action(); new Hash(attrs).each(function(attr) { action.addOp(new ui.Action.OpBondAttr(id, attr.key, attr.value)); }, this); if (flip) { action.mergeWith(ui.Action.toBondFlipping(id)); } return action.perform(); }; ui.Action.fromSelectedBondsAttrs = function (attrs, flips) { var action = new ui.Action(); attrs = new Hash(attrs); ui.selection.bonds.each(function(id) { attrs.each(function(attr) { action.addOp(new ui.Action.OpBondAttr(id, attr.key, attr.value)); }, this); }, this); if (flips) flips.each(function (id) { action.mergeWith(ui.Action.toBondFlipping(id)); }, this); return action.perform(); }; ui.Action.fromAtomAddition = function (pos, atom) { atom = Object.clone(atom); var action = new ui.Action(); atom.fragment = action.addOp(new ui.Action.OpFragmentAdd().perform(ui.editor)).frid; action.addOp(new ui.Action.OpAtomAdd(atom, pos).perform(ui.editor)); return action; }; ui.Action.fromBondAddition = function (bond, begin, end, pos, pos2) { var action = new ui.Action(); var frid = null; if (!Object.isNumber(begin)) { if (Object.isNumber(end)) { frid = ui.render.atomGetAttr(end, 'fragment'); } } else { frid = ui.render.atomGetAttr(begin, 'fragment'); if (Object.isNumber(end)) { var frid2 = ui.render.atomGetAttr(end, 'fragment'); if (frid2 != frid && Object.isNumber(frid2)) { var rgid = chem.Struct.RGroup.findRGroupByFragment(ui.render.ctab.molecule.rgroups, frid2); if (!Object.isUndefined(rgid)) { action.mergeWith(ui.Action.fromRGroupFragment(null, frid2)); } ui.render.ctab.molecule.atoms.each(function(aid, atom) { if (atom.fragment == frid2) { action.addOp(new ui.Action.OpAtomAttr(aid, 'fragment', frid).perform(ui.editor)); } }); action.addOp(new ui.Action.OpFragmentDelete(frid2).perform(ui.editor)); } } } if (frid == null) { frid = action.addOp(new ui.Action.OpFragmentAdd().perform(ui.editor)).frid; } if (!Object.isNumber(begin)) { begin.fragment = frid; begin = action.addOp(new ui.Action.OpAtomAdd(begin, pos).perform(ui.editor)).data.aid; pos = pos2; } else { if (ui.render.atomGetAttr(begin, 'label') == '*') { action.addOp(new ui.Action.OpAtomAttr(begin, 'label', 'C').perform(ui.editor)); } } if (!Object.isNumber(end)) { end.fragment = frid; end = action.addOp(new ui.Action.OpAtomAdd(end, pos).perform(ui.editor)).data.aid; } else { if (ui.render.atomGetAttr(end, 'label') == '*') { action.addOp(new ui.Action.OpAtomAttr(end, 'label', 'C').perform(ui.editor)); } } action.addOp(new ui.Action.OpBondAdd(begin, end, bond).perform(ui.editor)); action.operations.reverse(); return [action, begin, end]; }; ui.Action.fromArrowAddition = function (pos) { var action = new ui.Action(); if (ui.ctab.rxnArrows.count() < 1) { action.addOp(new ui.Action.OpRxnArrowAdd(pos).perform(ui.editor)); } return action; }; ui.Action.fromArrowDeletion = function (id) { var action = new ui.Action(); action.addOp(new ui.Action.OpRxnArrowDelete(id)); return action.perform(); }; ui.Action.fromPlusAddition = function (pos) { var action = new ui.Action(); action.addOp(new ui.Action.OpRxnPlusAdd(pos).perform(ui.editor)); return action; }; ui.Action.fromPlusDeletion = function (id) { var action = new ui.Action(); action.addOp(new ui.Action.OpRxnPlusDelete(id)); return action.perform(); }; // Add action operation to remove atom from s-group if needed ui.Action.prototype.removeAtomFromSgroupIfNeeded = function (id) { var sgroups = ui.render.atomGetSGroups(id); if (sgroups.length > 0) { sgroups.each(function (sid) { this.addOperation(ui.Action.OPERATION.SGROUP_ATOM_DEL, { id: ui.atomMap.indexOf(id), sid: ui.sgroupMap.indexOf(sid) }); }, this); return true; } return false; }; // Add action operations to remove whole s-group if needed ui.Action.prototype.removeSgroupIfNeeded = function (atoms) { var sg_counts = new Hash(); atoms.each(function (id) { var sgroups = ui.render.atomGetSGroups(id); sgroups.each(function (sid) { var n = sg_counts.get(sid); if (Object.isUndefined(n)) n = 1; else n++; sg_counts.set(sid, n); }, this); }, this); sg_counts.each(function (sg) { var sid = parseInt(sg.key); var sg_atoms = ui.render.sGroupGetAtoms(sid); if (sg_atoms.length == sg.value) { // delete whole s-group this.addOperation(ui.Action.OPERATION.SGROUP_DEL, { id: ui.sgroupMap.indexOf(sid) }); } }, this); }; ui.Action.fromAtomDeletion = function (id) { var action = new ui.Action(); var atoms_to_remove = new Array(); var frid = ui.ctab.atoms.get(id).fragment; ui.render.atomGetNeighbors(id).each(function (nei) { action.addOp(new ui.Action.OpBondDelete(nei.bid));// [RB] !! if (ui.render.atomGetDegree(nei.aid) == 1) { if (action.removeAtomFromSgroupIfNeeded(nei.aid)) atoms_to_remove.push(nei.aid); action.addOp(new ui.Action.OpAtomDelete(nei.aid)); } }, this); if (action.removeAtomFromSgroupIfNeeded(id)) atoms_to_remove.push(id); action.addOp(new ui.Action.OpAtomDelete(id)); action.removeSgroupIfNeeded(atoms_to_remove); action = action.perform(); action.mergeWith(ui.Action.__fromFragmentSplit(frid)); return action; }; ui.Action.fromBondDeletion = function (id) { var action = new ui.Action(); var bond = ui.ctab.bonds.get(id); var frid = ui.ctab.atoms.get(bond.begin).fragment; var atoms_to_remove = new Array(); action.addOp(new ui.Action.OpBondDelete(id)); if (ui.render.atomGetDegree(bond.begin) == 1) { if (action.removeAtomFromSgroupIfNeeded(bond.begin)) atoms_to_remove.push(bond.begin); action.addOp(new ui.Action.OpAtomDelete(bond.begin)); } if (ui.render.atomGetDegree(bond.end) == 1) { if (action.removeAtomFromSgroupIfNeeded(bond.end)) atoms_to_remove.push(bond.end); action.addOp(new ui.Action.OpAtomDelete(bond.end)); } action.removeSgroupIfNeeded(atoms_to_remove); action = action.perform(); action.mergeWith(ui.Action.__fromFragmentSplit(frid)); return action; }; ui.Action.__fromFragmentSplit = function(frid) { // TODO [RB] the thing is too tricky :) need something else in future var action = new ui.Action(); var rgid = chem.Struct.RGroup.findRGroupByFragment(ui.ctab.rgroups, frid); ui.ctab.atoms.each(function(aid, atom) { if (atom.fragment == frid) { var newfrid = action.addOp(new ui.Action.OpFragmentAdd().perform(ui.editor)).frid; var processAtom = function(aid1) { action.addOp(new ui.Action.OpAtomAttr(aid1, 'fragment', newfrid).perform(ui.editor)); ui.render.atomGetNeighbors(aid1).each(function(nei) { if (ui.ctab.atoms.get(nei.aid).fragment == frid) { processAtom(nei.aid); } }); }; processAtom(aid); if (rgid) { action.mergeWith(ui.Action.fromRGroupFragment(rgid, newfrid)); } } }); if (frid != -1) { action.mergeWith(ui.Action.fromRGroupFragment(0, frid)); action.addOp(new ui.Action.OpFragmentDelete(frid).perform(ui.editor)); } return action; }; ui.Action.fromFragmentAddition = function (atoms, bonds, sgroups, rxnArrows, rxnPluses) { var action = new ui.Action(); /* atoms.each(function (aid) { ui.render.atomGetNeighbors(aid).each(function (nei) { if (ui.selection.bonds.indexOf(nei.bid) == -1) ui.selection.bonds = ui.selection.bonds.concat([nei.bid]); }, this); }, this); */ // TODO: merge close atoms and bonds sgroups.each(function (sid) { var idx = ui.sgroupMap.indexOf(sid); if (idx == -1) idx = ui.sgroupMap.push(sid) - 1; action.addOperation(ui.Action.OPERATION.SGROUP_DEL, { id: idx }); }, this); bonds.each(function (bid) { action.addOp(new ui.Action.OpBondDelete(bid)); }, this); atoms.each(function(aid) { action.addOp(new ui.Action.OpAtomDelete(aid)); }, this); rxnArrows.each(function (id) { action.addOp(new ui.Action.OpRxnArrowDelete(id)); }, this); rxnPluses.each(function (id) { action.addOp(new ui.Action.OpRxnPlusDelete(id)); }, this); action.mergeWith(new ui.Action.__fromFragmentSplit(-1)); return action; }; ui.Action.fromFragmentDeletion = function(selection) { selection = selection || ui.selection; var action = new ui.Action(); var atoms_to_remove = new Array(); var frids = []; selection.atoms.each(function (aid) { ui.render.atomGetNeighbors(aid).each(function (nei) { if (selection.bonds.indexOf(nei.bid) == -1) selection.bonds = selection.bonds.concat([nei.bid]); }, this); }, this); selection.bonds.each(function (bid) { action.addOp(new ui.Action.OpBondDelete(bid)); var bond = ui.ctab.bonds.get(bid); if (selection.atoms.indexOf(bond.begin) == -1 && ui.render.atomGetDegree(bond.begin) == 1) { var frid1 = ui.ctab.atoms.get(bond.begin).fragment; if (frids.indexOf(frid1) < 0) frids.push(frid1); if (action.removeAtomFromSgroupIfNeeded(bond.begin)) atoms_to_remove.push(bond.begin); action.addOp(new ui.Action.OpAtomDelete(bond.begin)); } if (selection.atoms.indexOf(bond.end) == -1 && ui.render.atomGetDegree(bond.end) == 1) { var frid2 = ui.ctab.atoms.get(bond.end).fragment; if (frids.indexOf(frid2) < 0) frids.push(frid2); if (action.removeAtomFromSgroupIfNeeded(bond.end)) atoms_to_remove.push(bond.end); action.addOp(new ui.Action.OpAtomDelete(bond.end)); } }, this); selection.atoms.each(function (aid) { var frid3 = ui.ctab.atoms.get(aid).fragment; if (frids.indexOf(frid3) < 0) frids.push(frid3); if (action.removeAtomFromSgroupIfNeeded(aid)) atoms_to_remove.push(aid); action.addOp(new ui.Action.OpAtomDelete(aid)); }, this); action.removeSgroupIfNeeded(atoms_to_remove); selection.rxnArrows.each(function (id) { action.addOp(new ui.Action.OpRxnArrowDelete(id)); }, this); selection.rxnPluses.each(function (id) { action.addOp(new ui.Action.OpRxnPlusDelete(id)); }, this); action = action.perform(); while (frids.length > 0) action.mergeWith(new ui.Action.__fromFragmentSplit(frids.pop())); return action; }; ui.Action.fromAtomMerge = function (src_id, dst_id) { var action = new ui.Action(); ui.render.atomGetNeighbors(src_id).each(function (nei) { var bond = ui.ctab.bonds.get(nei.bid); var begin, end; if (bond.begin == nei.aid) { begin = nei.aid; end = dst_id; } else { begin = dst_id; end = nei.aid; } if (dst_id != bond.begin && dst_id != bond.end && ui.ctab.findBondId(begin, end) == -1) // TODO: improve this { //TODO [RB] the trick to merge fragments, will find more stright way later //action.addOp(new ui.Action.OpBondAdd(begin, end, bond)); action.mergeWith(ui.Action.fromBondAddition(bond, begin, end)[0].perform()); } action.addOp(new ui.Action.OpBondDelete(nei.bid)); }, this); var attrs = chem.Struct.Atom.getAttrHash(ui.ctab.atoms.get(src_id)); if (ui.render.atomGetDegree(src_id) == 1 && attrs.get('label') == '*') attrs.set('label', 'C'); attrs.each(function(attr) { action.addOp(new ui.Action.OpAtomAttr(dst_id, attr.key, attr.value)); }, this); var sg_changed = action.removeAtomFromSgroupIfNeeded(src_id); action.addOp(new ui.Action.OpAtomDelete(src_id)); if (sg_changed) action.removeSgroupIfNeeded([src_id]); return action.perform(); }; ui.Action.toBondFlipping = function (id) { var bond = ui.ctab.bonds.get(id); var action = new ui.Action(); action.addOp(new ui.Action.OpBondDelete(id)); action.addOp(new ui.Action.OpBondAdd(bond.end, bond.begin, bond)).data.bid = id; return action; }; ui.Action.fromBondFlipping = function(bid) { return ui.Action.toBondFlipping(bid).perform(); }; ui.Action.fromPatternOnCanvas = function (pos, pattern) { var angle = 2 * Math.PI / pattern.length; var l = 1.0 / (2 * Math.sin(angle / 2)); var v = new util.Vec2(0, -l); var action = new ui.Action(); var fragAction = new ui.Action.OpFragmentAdd().perform(ui.editor); pattern.each(function() { action.addOp( new ui.Action.OpAtomAdd( { label: 'C', fragment: fragAction.frid }, util.Vec2.sum(pos, v) ).perform(ui.editor) ); v = v.rotate(angle); }, this); for (var i = 0, n = action.operations.length; i < n; i++) { action.addOp( new ui.Action.OpBondAdd( action.operations[i].data.aid, action.operations[(i + 1) % pattern.length].data.aid, { type: pattern[i] } ).perform(ui.editor) ); } action.operations.reverse(); action.addOp(fragAction); return action; }; ui.Action.fromChain = function (p0, v, nSect, atom_id) { var angle = Math.PI / 6; var dx = Math.cos(angle), dy = Math.sin(angle); var action = new ui.Action(); var frid; if (atom_id != null) { frid = ui.render.atomGetAttr(atom_id, 'fragment'); } else { frid = action.addOp(new ui.Action.OpFragmentAdd().perform(ui.editor)).frid; } var id0 = -1; if (atom_id != null) { id0 = atom_id; } else { id0 = action.addOp(new ui.Action.OpAtomAdd({ label: 'C', fragment : frid }, p0).perform(ui.editor)).data.aid; } nSect.times(function (i) { var pos = new util.Vec2(dx * (i + 1), i & 1 ? 0 : dy).rotate(v).add(p0); var a = ui.render.findClosestAtom(pos, 0.1); var id1 = -1; if (a == null) { id1 = action.addOp(new ui.Action.OpAtomAdd({ label: 'C', fragment : frid }, pos).perform(ui.editor)).data.aid; } else { //TODO [RB] need to merge fragments: is there a way to reuse fromBondAddition (which performs it) instead of using code below??? id1 = a.id; } if (!ui.render.checkBondExists(id0, id1)) { action.addOp(new ui.Action.OpBondAdd(id0, id1, {}).perform(ui.editor)); } id0 = id1; }, this); action.operations.reverse(); return action; }; ui.Action.fromPatternOnAtom = function (aid, pattern) { if (ui.render.atomGetDegree(aid) != 1) { var atom = ui.atomForNewBond(aid); atom.fragment = ui.render.atomGetAttr(aid, 'fragment'); var action_res = ui.Action.fromBondAddition({type: 1}, aid, atom.atom, atom.pos); var action = ui.Action.fromPatternOnElement(action_res[2], pattern, true); action.mergeWith(action_res[0]); return action; } return ui.Action.fromPatternOnElement(aid, pattern, true); }; ui.Action.fromPatternOnElement = function (id, pattern, on_atom) { var angle = (pattern.length - 2) * Math.PI / (2 * pattern.length); var first_idx = 0; //pattern.indexOf(bond.type) + 1; // 0 if there's no var pos = null; // center pos var v = null; // rotating vector from center if (on_atom) { var nei_id = ui.render.atomGetNeighbors(id)[0].aid; var atom_pos = ui.render.atomGetPos(id); pos = util.Vec2.diff(atom_pos, ui.render.atomGetPos(nei_id)); pos = pos.scaled(pos.length() / 2 / Math.cos(angle)); v = pos.negated(); pos.add_(atom_pos); angle = Math.PI - 2 * angle; } else { var bond = ui.ctab.bonds.get(id); var begin_pos = ui.render.atomGetPos(bond.begin); var end_pos = ui.render.atomGetPos(bond.end); v = util.Vec2.diff(end_pos, begin_pos); var l = v.length() / (2 * Math.cos(angle)); v = v.scaled(l / v.length()); var v_sym = v.rotate(-angle); v = v.rotate(angle); pos = util.Vec2.sum(begin_pos, v); var pos_sym = util.Vec2.sum(begin_pos, v_sym); var cnt = 0, bcnt = 0; var cnt_sym = 0, bcnt_sym = 0; // TODO: improve this enumeration ui.ctab.atoms.each(function (a_id) { if (util.Vec2.dist(pos, ui.render.atomGetPos(a_id)) < l * 1.1) { cnt++; bcnt += ui.render.atomGetDegree(a_id); } else if (util.Vec2.dist(pos_sym, ui.render.atomGetPos(a_id)) < l * 1.1) { cnt_sym++; bcnt_sym += ui.render.atomGetDegree(a_id); } }); angle = Math.PI - 2 * angle; if (cnt > cnt_sym || (cnt == cnt_sym && bcnt > bcnt_sym)) { pos = pos_sym; v = v_sym; } else angle = -angle; v = v.negated(); } ui.render.update(); var action = new ui.Action(); var atom_ids = new Array(pattern.length); if (!on_atom) { atom_ids[0] = bond.begin; atom_ids[pattern.length - 1] = bond.end; } var frid = ui.render.ctab.molecule.atoms.get(on_atom ? id : ui.render.ctab.molecule.bonds.get(id).begin).fragment; (pattern.length - (on_atom ? 0 : 1)).times(function(idx) { if (idx > 0 || on_atom) { var new_pos = util.Vec2.sum(pos, v); var a = ui.render.findClosestAtom(new_pos, 0.1); if (a == null) { atom_ids[idx] = action.addOp( new ui.Action.OpAtomAdd({ label: 'C', fragment : frid }, new_pos).perform(ui.editor) ).data.aid; } else { // TODO [RB] need to merge fragments? atom_ids[idx] = a.id; } } v = v.rotate(angle); }, this); var i = 0; pattern.length.times(function(idx) { var begin = atom_ids[idx]; var end = atom_ids[(idx + 1) % pattern.length]; var bond_type = pattern[(first_idx + idx) % pattern.length]; if (!ui.render.checkBondExists(begin, end)) { /* var bond_id = ui.render.bondAdd(begin, end, {type: bond_type}); action.addOperation( ui.Action.OPERATION.BOND_DEL, { id: ui.bondMap.push(bond_id) - 1 } ); */ action.addOp(new ui.Action.OpBondAdd(begin, end, { type: bond_type }).perform(ui.editor)); } else { if (bond_type == chem.Struct.BOND.TYPE.AROMATIC) { var nei = ui.render.atomGetNeighbors(begin); nei.find(function(n) { if (n.aid == end) { var src_type = ui.render.bondGetAttr(n.bid, 'type'); if (src_type != bond_type) { /* action.addOperation( ui.Action.OPERATION.BOND_ATTR, { id: ui.bondMap.indexOf(n.bid), attr_name: 'type', attr_value: src_type } ); ui.render.bondSetAttr(n.bid, 'type', bond_type); */ } return true; } return false; }, this); } } i++; }, this); action.operations.reverse(); return action; }; ui.Action.fromNewCanvas = function (ctab) { var action = new ui.Action(); action.addOperation(ui.Action.OPERATION.CANVAS_LOAD, { ctab: ctab, atom_map: null, bond_map: null, sgroup_map: null }); return action.perform(); }; ui.Action.fromSgroupAttrs = function (id, type, attrs) { var action = new ui.Action(); var id_map = ui.sgroupMap.indexOf(id); var cur_type = ui.render.sGroupGetType(id); action.addOperation(ui.Action.OPERATION.SGROUP_ATTR, { id: id_map, type: type, attrs: attrs }); if ((cur_type == 'SRU' || type == 'SRU') && cur_type != type) { ui.render.sGroupsFindCrossBonds(); var nei_atoms = ui.render.sGroupGetNeighborAtoms(id); if (cur_type == 'SRU') { nei_atoms.each(function(aid) { if (ui.render.atomGetAttr(aid, 'label') == '*') { action.addOp(new ui.Action.OpAtomAttr(aid, 'label', 'C')); } }, this); } else { nei_atoms.each(function (aid) { if (ui.render.atomGetDegree(aid) == 1 && ui.render.atomIsPlainCarbon(aid)) { action.addOp(new ui.Action.OpAtomAttr(aid, 'label', '*')); } }, this); } } return action.perform(); }; ui.Action.fromSgroupDeletion = function (id) { var action = new ui.Action(); if (ui.render.sGroupGetType(id) == 'SRU') { ui.render.sGroupsFindCrossBonds(); var nei_atoms = ui.render.sGroupGetNeighborAtoms(id); nei_atoms.each(function(aid) { if (ui.render.atomGetAttr(aid, 'label') == '*') { action.addOp(new ui.Action.OpAtomAttr(aid, 'label', 'C')); } }, this); } action.addOperation(ui.Action.OPERATION.SGROUP_DEL, { id: ui.sgroupMap.indexOf(id) }); return action.perform(); }; ui.Action.fromSgroupAddition = function (type, attrs, atoms) { var action = new ui.Action(); var i; for (i = 0; i < atoms.length; i++) atoms[i] = ui.atomMap.indexOf(atoms[i]); action.addOperation(ui.Action.OPERATION.SGROUP_ADD, { type: type, attrs: attrs, atoms: atoms }); action = action.perform(); if (type == 'SRU') { var sid = ui.sgroupMap[action.operations[0].params.id]; ui.render.sGroupsFindCrossBonds(); var nei_atoms = ui.render.sGroupGetNeighborAtoms(sid); var asterisk_action = new ui.Action(); nei_atoms.each(function(aid) { if (ui.render.atomGetDegree(aid) == 1 && ui.render.atomIsPlainCarbon(aid)) { asterisk_action.addOp(new ui.Action.OpAtomAttr(aid, 'label', 'C')); } }, this); asterisk_action = asterisk_action.perform(); asterisk_action.mergeWith(action); action = asterisk_action; } return action; }; ui.Action.fromRGroupAttrs = function(id, attrs) { var action = new ui.Action(); new Hash(attrs).each(function(attr) { action.addOp(new ui.Action.OpRGroupAttr(id, attr.key, attr.value)); }, this); return action.perform(); }; ui.Action.fromRGroupFragment = function(rgidNew, frid) { var action = new ui.Action(); action.addOp(new ui.Action.OpRGroupFragment(rgidNew, frid)); return action.perform(); }; ui.Action.fromPaste = function(objects, offset) { offset = offset || new util.Vec2(); var action = new ui.Action(), amap = {}, fmap = {}; // atoms for (var aid = 0; aid < objects.atoms.length; aid++) { var atom = Object.clone(objects.atoms[aid]); if (!(atom.fragment in fmap)) { fmap[atom.fragment] = action.addOp(new ui.Action.OpFragmentAdd().perform(ui.editor)).frid; } atom.fragment = fmap[atom.fragment]; amap[aid] = action.addOp(new ui.Action.OpAtomAdd(atom, atom.pos.add(offset)).perform(ui.editor)).data.aid; } //bonds for (var bid = 0; bid < objects.bonds.length; bid++) { var bond = Object.clone(objects.bonds[bid]); action.addOp(new ui.Action.OpBondAdd(amap[bond.begin], amap[bond.end], bond).perform(ui.editor)); } //sgroups for (var sgid = 0; sgid < objects.sgroups.length; sgid++) { var sgroup = Object.clone(objects.sgroups[sgid]), sgatoms = []; for (var sgaid = 0; sgaid < sgroup.atoms.length; sgaid++) { sgatoms.push(amap[sgroup.atoms[sgaid]]); } var sgaction = ui.Action.fromSgroupAddition(sgroup.type, sgroup, sgatoms); //action.mergeWith(sgaction); for (var iop = sgaction.operations.length - 1; iop >= 0; iop--) { action.addOp(sgaction.operations[iop]); } } //reaction arrows if (ui.editor.render.ctab.rxnArrows.count() < 1) { for (var raid = 0; raid < objects.rxnArrows.length; raid++) { action.addOp(new ui.Action.OpRxnArrowAdd(objects.rxnArrows[raid].pos.add(offset)).perform(ui.editor)); } } //reaction pluses for (var rpid = 0; rpid < objects.rxnPluses.length; rpid++) { action.addOp(new ui.Action.OpRxnPlusAdd(objects.rxnPluses[rpid].pos.add(offset)).perform(ui.editor)); } //thats all action.operations.reverse(); return action; }; ui.addUndoAction = function (action, check_dummy) { if (action == null) return; if (check_dummy != true || !action.isDummy()) { ui.undoStack.push(action); ui.redoStack.clear(); if (ui.undoStack.length > ui.HISTORY_LENGTH) ui.undoStack.splice(0, 1); ui.updateActionButtons(); } }; ui.removeDummyAction = function () { if (ui.undoStack.length != 0 && ui.undoStack.last().isDummy()) { ui.undoStack.pop(); ui.updateActionButtons(); } }; ui.updateActionButtons = function () { if (ui.undoStack.length == 0) $('undo').addClassName('buttonDisabled'); else $('undo').removeClassName('buttonDisabled'); if (ui.redoStack.length == 0) $('redo').addClassName('buttonDisabled'); else $('redo').removeClassName('buttonDisabled'); }; ui.undo = function () { ui.redoStack.push(ui.undoStack.pop().perform()); ui.updateActionButtons(); ui.updateSelection(); }; ui.redo = function () { ui.undoStack.push(ui.redoStack.pop().perform()); ui.updateActionButtons(); ui.updateSelection(); }; ui.Action.OpBase = function() {}; ui.Action.OpBase.prototype._execute = function() { throw new Error('Operation._execute() is not implemented'); }; ui.Action.OpBase.prototype._invert = function() { throw new Error('Operation._invert() is not implemented');}; ui.Action.OpBase.prototype.perform = function(editor) { this._execute(editor); if (!('__inverted' in this)) { this.__inverted = this._invert(); this.__inverted.__inverted = this; } return this.__inverted; }; ui.Action.OpBase.prototype.isDummy = function(editor) { return '_isDummy' in this ? this['_isDummy'](editor) : false; }; ui.Action.OpAtomAdd = function(atom, pos) { this.data = { aid : null, atom : atom, pos : pos }; this._execute = function(editor) { var R = editor.render, RS = R.ctab, DS = RS.molecule; var pp = {}; if (this.data.atom) for (var p in this.data.atom) pp[p] = this.data.atom[p]; pp.label = pp.label || 'C'; if (!Object.isNumber(this.data.aid)) { this.data.aid = DS.atoms.add(new chem.Struct.Atom(pp)); ui.atomMap.indexOf(this.data.aid); // TODO [RB] temporary kludge } else { DS.atoms.set(this.data.aid, new chem.Struct.Atom(pp)); } RS.notifyAtomAdded(this.data.aid); DS._atomSetPos(this.data.aid, new util.Vec2(this.data.pos)); }; this._invert = function() { var ret = new ui.Action.OpAtomDelete(); ret.data = this.data; return ret; }; }; ui.Action.OpAtomAdd.prototype = new ui.Action.OpBase(); ui.Action.OpAtomDelete = function(aid) { this.data = { aid : aid, atom : null, pos : null }; this._execute = function(editor) { var R = editor.render, RS = R.ctab, DS = RS.molecule; if (!this.data.atom) { this.data.atom = DS.atoms.get(this.data.aid); this.data.pos = R.atomGetPos(this.data.aid); } RS.notifyAtomRemoved(this.data.aid); DS.atoms.remove(this.data.aid); }; this._invert = function() { var ret = new ui.Action.OpAtomAdd(); ret.data = this.data; return ret; }; }; ui.Action.OpAtomDelete.prototype = new ui.Action.OpBase(); ui.Action.OpAtomAttr = function(aid, attribute, value) { this.data = { aid : aid, attribute : attribute, value : value }; this.data2 = null; this._execute = function(editor) { var atom = editor.render.ctab.molecule.atoms.get(this.data.aid); if (!this.data2) { this.data2 = { aid : this.data.aid, attribute : this.data.attribute, value : atom[this.data.attribute] }; } if (this.data.attribute == 'label' && this.data.value != null) // HACK TODO review atom['atomList'] = null; atom[this.data.attribute] = this.data.value; editor.render.invalidateAtom(this.data.aid); }; this._isDummy = function(editor) { return editor.render.ctab.molecule.atoms.get(this.data.aid)[this.data.attribute] == this.data.value; }; this._invert = function() { var ret = new ui.Action.OpAtomAttr(); ret.data = this.data2; ret.data2 = this.data; return ret; }; }; ui.Action.OpAtomAttr.prototype = new ui.Action.OpBase(); ui.Action.OpBondAdd = function(begin, end, bond) { this.data = { bid : null, bond : bond, begin : begin, end : end }; this._execute = function(editor) { var R = editor.render, RS = R.ctab, DS = RS.molecule; if (this.data.begin == this.data.end) throw new Error("Distinct atoms expected"); if (rnd.DEBUG && this.molecule.checkBondExists(this.data.begin, this.data.end)) throw new Error("Bond already exists"); R.invalidateAtom(this.data.begin, 1); R.invalidateAtom(this.data.end, 1); var pp = {}; if (this.data.bond) for (var p in this.data.bond) pp[p] = this.data.bond[p]; pp.type = pp.type || chem.Struct.BOND.TYPE.SINGLE; pp.begin = this.data.begin; pp.end = this.data.end; if (!Object.isNumber(this.data.bid)) { this.data.bid = DS.bonds.add(new chem.Struct.Bond(pp)); ui.bondMap.indexOf(this.data.bid); // TODO [RB] temporary kludge } else { DS.bonds.set(this.data.bid, new chem.Struct.Bond(pp)); } DS.bondInitHalfBonds(this.data.bid); DS.atomAddNeighbor(DS.bonds.get(this.data.bid).hb1); DS.atomAddNeighbor(DS.bonds.get(this.data.bid).hb2); RS.notifyBondAdded(this.data.bid); }; this._invert = function() { var ret = new ui.Action.OpBondDelete(); ret.data = this.data; return ret; }; }; ui.Action.OpBondAdd.prototype = new ui.Action.OpBase(); ui.Action.OpBondDelete = function(bid) { this.data = { bid : bid, bond : null, begin : null, end : null }; this._execute = function(editor) { var R = editor.render, RS = R.ctab, DS = RS.molecule; if (!this.data.bond) { this.data.bond = DS.bonds.get(this.data.bid); this.data.begin = this.data.bond.begin; this.data.end = this.data.bond.end; } R.invalidateBond(this.data.bid); RS.notifyBondRemoved(this.data.bid); var bond = DS.bonds.get(this.data.bid); [bond.hb1, bond.hb2].each(function(hbid) { var hb = DS.halfBonds.get(hbid); var atom = DS.atoms.get(hb.begin); var pos = atom.neighbors.indexOf(hbid); var prev = (pos + atom.neighbors.length - 1) % atom.neighbors.length; var next = (pos + 1) % atom.neighbors.length; DS.setHbNext(atom.neighbors[prev], atom.neighbors[next]); atom.neighbors.splice(pos, 1); }, this); DS.halfBonds.unset(bond.hb1); DS.halfBonds.unset(bond.hb2); DS.bonds.remove(this.data.bid); }; this._invert = function() { var ret = new ui.Action.OpBondAdd(); ret.data = this.data; return ret; }; }; ui.Action.OpBondDelete.prototype = new ui.Action.OpBase(); ui.Action.OpBondAttr = function(bid, attribute, value) { this.data = { bid : bid, attribute : attribute, value : value }; this.data2 = null; this._execute = function(editor) { var bond = editor.render.ctab.molecule.bonds.get(this.data.bid); if (!this.data2) { this.data2 = { bid : this.data.bid, attribute : this.data.attribute, value : bond[this.data.attribute] }; } bond[this.data.attribute] = this.data.value; editor.render.invalidateBond(this.data.bid, this.data.attribute == 'type' ? 1 : 0); }; this._isDummy = function(editor) { return editor.render.ctab.molecule.bonds.get(this.data.bid)[this.data.attribute] == this.data.value; }; this._invert = function() { var ret = new ui.Action.OpBondAttr(); ret.data = this.data2; ret.data2 = this.data; return ret; }; }; ui.Action.OpBondAttr.prototype = new ui.Action.OpBase(); ui.Action.OpFragmentAdd = function(frid) { this.frid = Object.isUndefined(frid) ? null : frid; this._execute = function(editor) { var RS = editor.render.ctab, DS = RS.molecule; var frag = new chem.Struct.Fragment(); if (this.frid == null) { this.frid = DS.frags.add(frag); } else { DS.frags.set(this.frid, frag); } RS.frags.set(this.frid, new rnd.ReFrag(frag)); // TODO add ReStruct.notifyFragmentAdded }; this._invert = function() { return new ui.Action.OpFragmentDelete(this.frid); }; }; ui.Action.OpFragmentAdd.prototype = new ui.Action.OpBase(); ui.Action.OpFragmentDelete = function(frid) { this.frid = frid; this._execute = function(editor) { var R = editor.render, RS = R.ctab, DS = RS.molecule; R.invalidateItem('frags', this.frid, 1); RS.frags.unset(this.frid); DS.frags.remove(this.frid); // TODO add ReStruct.notifyFragmentRemoved }; this._invert = function() { return new ui.Action.OpFragmentAdd(this.frid); }; }; ui.Action.OpFragmentDelete.prototype = new ui.Action.OpBase(); ui.Action.OpRGroupAttr = function(rgid, attribute, value) { this.data = { rgid : rgid, attribute : attribute, value : value }; this.data2 = null; this._execute = function(editor) { var rgp = editor.render.ctab.molecule.rgroups.get(this.data.rgid); if (!this.data2) { this.data2 = { rgid : this.data.rgid, attribute : this.data.attribute, value : rgp[this.data.attribute] }; } rgp[this.data.attribute] = this.data.value; editor.render.invalidateItem('rgroups', this.data.rgid); }; this._isDummy = function(editor) { return editor.render.ctab.molecule.rgroups.get(this.data.rgid)[this.data.attribute] == this.data.value; }; this._invert = function() { var ret = new ui.Action.OpRGroupAttr(); ret.data = this.data2; ret.data2 = this.data; return ret; }; }; ui.Action.OpRGroupAttr.prototype = new ui.Action.OpBase(); ui.Action.OpRGroupFragment = function(rgid, frid) { this.rgid_new = rgid; this.rgid_old = null; this.frid = frid; this._execute = function(editor) { var RS = editor.render.ctab, DS = RS.molecule; this.rgid_old = this.rgid_old || chem.Struct.RGroup.findRGroupByFragment(DS.rgroups, this.frid); var rgOld = (this.rgid_old ? DS.rgroups.get(this.rgid_old) : null); if (rgOld) { rgOld.frags.remove(rgOld.frags.keyOf(this.frid)); RS.clearVisel(RS.rgroups.get(this.rgid_old).visel); if (rgOld.frags.count() == 0) { RS.rgroups.unset(this.rgid_old); DS.rgroups.unset(this.rgid_old); RS.markItemRemoved(); } else { RS.markItem('rgroups', this.rgid_old, 1); } } if (this.rgid_new) { var rgNew = DS.rgroups.get(this.rgid_new); if (!rgNew) { rgNew = new chem.Struct.RGroup(); DS.rgroups.set(this.rgid_new, rgNew); RS.rgroups.set(this.rgid_new, new rnd.ReRGroup(rgNew)); } else { RS.markItem('rgroups', this.rgid_new, 1); } rgNew.frags.add(this.frid); } }; this._invert = function() { return new ui.Action.OpRGroupFragment(this.rgid_old, this.frid); }; }; ui.Action.OpRGroupFragment.prototype = new ui.Action.OpBase(); ui.Action.OpRxnArrowAdd = function(pos) { this.data = { arid : null, pos : pos }; this._execute = function(editor) { var R = editor.render, RS = R.ctab, DS = RS.molecule; if (!Object.isNumber(this.data.arid)) { this.data.arid = DS.rxnArrows.add(new chem.Struct.RxnArrow()); } else { DS.rxnArrows.set(this.data.arid, new chem.Struct.RxnArrow()); } RS.notifyRxnArrowAdded(this.data.arid); DS._rxnArrowSetPos(this.data.arid, new util.Vec2(this.data.pos)); R.invalidateItem('rxnArrows', this.data.arid, 1); }; this._invert = function() { var ret = new ui.Action.OpRxnArrowDelete(); ret.data = this.data; return ret; }; }; ui.Action.OpRxnArrowAdd.prototype = new ui.Action.OpBase(); ui.Action.OpRxnArrowDelete = function(arid) { this.data = { arid : arid, pos : null }; this._execute = function(editor) { var R = editor.render, RS = R.ctab, DS = RS.molecule; if (!this.data.pos) { this.data.pos = R.rxnArrowGetPos(this.data.arid); } RS.notifyRxnArrowRemoved(this.data.arid); DS.rxnArrows.remove(this.data.arid); }; this._invert = function() { var ret = new ui.Action.OpRxnArrowAdd(); ret.data = this.data; return ret; }; }; ui.Action.OpRxnArrowDelete.prototype = new ui.Action.OpBase(); ui.Action.OpRxnPlusAdd = function(pos) { this.data = { plid : null, pos : pos }; this._execute = function(editor) { var R = editor.render, RS = R.ctab, DS = RS.molecule; if (!Object.isNumber(this.data.plid)) { this.data.plid = DS.rxnPluses.add(new chem.Struct.RxnPlus()); } else { DS.rxnPluses.set(this.data.plid, new chem.Struct.RxnPlus()); } RS.notifyRxnPlusAdded(this.data.plid); DS._rxnPlusSetPos(this.data.plid, new util.Vec2(this.data.pos)); R.invalidateItem('rxnPluses', this.data.plid, 1); }; this._invert = function() { var ret = new ui.Action.OpRxnPlusDelete(); ret.data = this.data; return ret; }; }; ui.Action.OpRxnPlusAdd.prototype = new ui.Action.OpBase(); ui.Action.OpRxnPlusDelete = function(plid) { this.data = { plid : plid, pos : null }; this._execute = function(editor) { var R = editor.render, RS = R.ctab, DS = RS.molecule; if (!this.data.pos) { this.data.pos = R.rxnPlusGetPos(this.data.plid); } RS.notifyRxnPlusRemoved(this.data.plid); DS.rxnPluses.remove(this.data.plid); }; this._invert = function() { var ret = new ui.Action.OpRxnPlusAdd(); ret.data = this.data; return ret; }; }; ui.Action.OpRxnPlusDelete.prototype = new ui.Action.OpBase();
OpSGroupAtomAdd/Remove
ui/actions.js
OpSGroupAtomAdd/Remove
<ide><path>i/actions.js <ide> }; <ide> ui.Action.OpAtomAttr.prototype = new ui.Action.OpBase(); <ide> <add>ui.Action.OpSGroupAtomAdd = function(sgid, aid) { <add> this.data = { 'aid' : aid, 'sgid' : sgid }; <add> this._execute = function(editor) { <add> var R = editor.render, RS = R.ctab, DS = RS.molecule; <add> var aid = this.data.aid; <add> var sgid = this.data.sgid; <add> var atom = DS.atoms.get(aid); <add> var sg = DS.sgroups.get(sgid); <add> chem.SGroup.addAtom(sg, aid); <add> util.Set.add(atom.sgs, sgid); <add> R.invalidateAtom(aid); <add> }; <add> this._invert = function() { <add> var ret = new ui.Action.OpAtomDelete(); ret.data = this.data; return ret; <add> }; <add>}; <add>ui.Action.OpSGroupAtomAdd.prototype = new ui.Action.OpBase(); <add> <add>ui.Action.OpSGroupAtomRemove = function(sgid, aid) { <add> this.data = { 'aid' : aid, 'sgid' : sgid }; <add> this._execute = function(editor) { <add> var aid = this.data.aid; <add> var sgid = this.data.sgid; <add> var R = editor.render, RS = R.ctab, DS = RS.molecule; <add> var atom = DS.atoms.get(aid); <add> var sg = DS.sgroups.get(sgid); <add> chem.SGroup.removeAtom(sg, aid); <add> util.Set.remove(atom.sgs, sgid); <add> R.invalidateAtom(aid); <add> }; <add> this._invert = function() { <add> var ret = new ui.Action.OpSGroupAtomAdd(); ret.data = this.data; return ret; <add> }; <add>}; <add>ui.Action.OpSGroupAtomRemove.prototype = new ui.Action.OpBase(); <add> <ide> ui.Action.OpBondAdd = function(begin, end, bond) { <ide> this.data = { bid : null, bond : bond, begin : begin, end : end }; <ide> this._execute = function(editor) {
Java
apache-2.0
936e488ef9dab945e68404c11051b884566a83a2
0
dracusds123/carbon-multitenancy,damithsenanayake/carbon-multitenancy,cdwijayarathna/carbon-multitenancy,madusankapremaratne/carbon-multitenancy,chanakaudaya/carbon-multitenancy,callkalpa/carbon-multitenancy,dracusds123/carbon-multitenancy,jsdjayanga/carbon-multitenancy,thusithathilina/carbon-multitenancy,madusankapremaratne/carbon-multitenancy,daneshk/carbon-multitenancy,DMHP/carbon-multitenancy,manoj-kumara/carbon-multitenancy,darshanasbg/carbon-multitenancy,madusankapremaratne/carbon-multitenancy,prabathariyaratna/carbon-multitenancy,callkalpa/carbon-multitenancy,daneshk/carbon-multitenancy,GayanM/carbon-multitenancy,cdwijayarathna/carbon-multitenancy,chanakaudaya/carbon-multitenancy,manoj-kumara/carbon-multitenancy,chanakaudaya/carbon-multitenancy,wso2/carbon-multitenancy,arunasujith/carbon-multitenancy,DMHP/carbon-multitenancy,thusithathilina/carbon-multitenancy,GayanM/carbon-multitenancy,prabathariyaratna/carbon-multitenancy,arunasujith/carbon-multitenancy,shashikap/carbon-multitenancy,damithsenanayake/carbon-multitenancy,cdwijayarathna/carbon-multitenancy,lasanthaS/carbon-multitenancy,manoj-kumara/carbon-multitenancy,darshanasbg/carbon-multitenancy,malithie/carbon-multitenancy,wso2/carbon-multitenancy,prabathariyaratna/carbon-multitenancy,GayanM/carbon-multitenancy,DMHP/carbon-multitenancy,thusithathilina/carbon-multitenancy,jsdjayanga/carbon-multitenancy,malithie/carbon-multitenancy,callkalpa/carbon-multitenancy,imesh/carbon-multitenancy,arunasujith/carbon-multitenancy,jsdjayanga/carbon-multitenancy,daneshk/carbon-multitenancy,shashikap/carbon-multitenancy,dracusds123/carbon-multitenancy,wso2/carbon-multitenancy,shashikap/carbon-multitenancy,damithsenanayake/carbon-multitenancy,malithie/carbon-multitenancy,darshanasbg/carbon-multitenancy
/* * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) 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. */ package org.wso2.carbon.tenant.mgt.util; import org.apache.axis2.clustering.ClusteringAgent; import org.apache.axis2.clustering.ClusteringFault; import org.apache.axis2.context.ConfigurationContext; import org.apache.commons.dbcp.BasicDataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.registry.core.RegistryConstants; import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.jdbc.dataaccess.JDBCDataAccessManager; import org.wso2.carbon.registry.core.session.UserRegistry; import org.wso2.carbon.registry.core.utils.UUIDGenerator; import org.wso2.carbon.stratos.common.beans.TenantInfoBean; import org.wso2.carbon.stratos.common.constants.StratosConstants; import org.wso2.carbon.stratos.common.exception.StratosException; import org.wso2.carbon.stratos.common.listeners.TenantMgtListener; import org.wso2.carbon.stratos.common.util.ClaimsMgtUtil; import org.wso2.carbon.stratos.common.util.CommonUtil; import org.wso2.carbon.tenant.mgt.internal.TenantMgtServiceComponent; import org.wso2.carbon.tenant.mgt.message.TenantDeleteClusterMessage; import org.wso2.carbon.user.api.RealmConfiguration; import org.wso2.carbon.user.api.TenantMgtConfiguration; import org.wso2.carbon.user.core.UserCoreConstants; import org.wso2.carbon.user.core.UserRealm; import org.wso2.carbon.user.core.UserStoreException; import org.wso2.carbon.user.core.UserStoreManager; import org.wso2.carbon.user.core.config.multitenancy.MultiTenantRealmConfigBuilder; import org.wso2.carbon.user.core.jdbc.JDBCRealmConstants; import org.wso2.carbon.user.core.tenant.Tenant; import org.wso2.carbon.user.core.tenant.TenantManager; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import javax.naming.InitialContext; import javax.sql.DataSource; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * Utility methods for tenant management. */ public class TenantMgtUtil { private static final Log log = LogFactory.getLog(TenantMgtUtil.class); private static final String ILLEGAL_CHARACTERS_FOR_TENANT_DOMAIN = ".*[^a-zA-Z0-9\\._\\-].*"; /** * Prepares string to show theme management page. * * @param tenantId - tenant id * @return UUID * @throws RegistryException, if failed. */ public static String prepareStringToShowThemeMgtPage(int tenantId) throws RegistryException { // first we generate a UUID UserRegistry systemRegistry = TenantMgtServiceComponent.getRegistryService().getGovernanceSystemRegistry(); String uuid = UUIDGenerator.generateUUID(); // store it in the registry. Resource resource = systemRegistry.newResource(); String tenantIdStr = Integer.toString(tenantId); resource.setProperty(MultitenantConstants.TENANT_ID, tenantIdStr); String uuidPath = StratosConstants.TENANT_CREATION_THEME_PAGE_TOKEN + RegistryConstants.PATH_SEPARATOR + uuid; systemRegistry.put(uuidPath, resource); // restrict access CommonUtil.denyAnonAuthorization(uuidPath, systemRegistry.getUserRealm()); return uuid; } /** * Triggers adding the tenant for TenantMgtListener * * @param tenantInfo tenant * @throws StratosException, trigger failed */ public static void triggerAddTenant(TenantInfoBean tenantInfo) throws StratosException { // initializeRegistry(tenantInfoBean.getTenantId()); for (TenantMgtListener tenantMgtListener : TenantMgtServiceComponent.getTenantMgtListeners()) { tenantMgtListener.onTenantCreate(tenantInfo); } } /** * Triggers pre tenant delete for TenantMgtListener * * @param tenantId int * @throws StratosException , trigger failed */ public static void triggerPreTenantDelete(int tenantId) throws StratosException { for (TenantMgtListener tenantMgtListener : TenantMgtServiceComponent .getTenantMgtListeners()) { log.debug("Executing OnPreDelete on Listener Impl Class Name : " + tenantMgtListener.getClass().getName()); tenantMgtListener.onPreDelete(tenantId); } } /** * Triggers an update for the tenant for TenantMgtListener * * @param tenantInfoBean tenantInfoBean * @throws org.wso2.carbon.stratos.common.exception.StratosException, if update failed */ public static void triggerUpdateTenant( TenantInfoBean tenantInfoBean) throws StratosException { for (TenantMgtListener tenantMgtListener : TenantMgtServiceComponent.getTenantMgtListeners()) { tenantMgtListener.onTenantUpdate(tenantInfoBean); } } public static void triggerTenantInitialActivation( TenantInfoBean tenantInfoBean) throws StratosException { for (TenantMgtListener tenantMgtListener : TenantMgtServiceComponent.getTenantMgtListeners()) { tenantMgtListener.onTenantInitialActivation(tenantInfoBean.getTenantId()); } } public static void triggerTenantActivation(int tenantId) throws StratosException { for (TenantMgtListener tenantMgtListener : TenantMgtServiceComponent.getTenantMgtListeners()) { tenantMgtListener.onTenantActivation(tenantId); } } public static void triggerTenantDeactivation(int tenantId) throws StratosException { for (TenantMgtListener tenantMgtListener : TenantMgtServiceComponent.getTenantMgtListeners()) { tenantMgtListener.onTenantDeactivation(tenantId); } } /** * Validate the tenant domain * * @param domainName tenant domain * @throws Exception , if invalid tenant domain name is given */ public static void validateDomain(String domainName) throws Exception { if (domainName == null || domainName.equals("")) { String msg = "Provided domain name is empty."; log.error(msg); throw new Exception(msg); } // ensures the .ext for the public clouds. if (CommonUtil.isPublicCloudSetup()) { int lastIndexOfDot = domainName.lastIndexOf("."); if (lastIndexOfDot <= 0) { String msg = "You should have an extension to your domain."; log.error(msg); throw new Exception(msg); } } int indexOfDot = domainName.indexOf("."); if (indexOfDot == 0) { // can't start a domain starting with "."; String msg = "Invalid domain, starting with '.'"; log.error(msg); throw new Exception(msg); } // check the tenant domain contains any illegal characters if (domainName.matches(ILLEGAL_CHARACTERS_FOR_TENANT_DOMAIN)) { String msg = "The tenant domain ' " + domainName + " ' contains one or more illegal characters. the valid characters are " + "letters, numbers, '.', '-' and '_'"; log.error(msg); throw new Exception(msg); } } /** * gets the UserStoreManager for a tenant * * @param tenant - a tenant * @param tenantId - tenant Id. To avoid the sequences where tenant.getId() may * produce the super tenant's tenant Id. * @return UserStoreManager * @throws Exception UserStoreException */ public static UserStoreManager getUserStoreManager(Tenant tenant, int tenantId) throws Exception { // get the system registry for the tenant RealmConfiguration realmConfig = TenantMgtServiceComponent.getBootstrapRealmConfiguration(); TenantMgtConfiguration tenantMgtConfiguration = TenantMgtServiceComponent.getRealmService().getTenantMgtConfiguration(); UserRealm userRealm; try { MultiTenantRealmConfigBuilder builder = TenantMgtServiceComponent.getRealmService(). getMultiTenantRealmConfigBuilder(); RealmConfiguration realmConfigToPersist = builder. getRealmConfigForTenantToPersist(realmConfig, tenantMgtConfiguration, tenant, tenantId); RealmConfiguration realmConfigToCreate = builder.getRealmConfigForTenantToCreateRealmOnTenantCreation( realmConfig, realmConfigToPersist, tenantId); userRealm = TenantMgtServiceComponent.getRealmService(). getUserRealm(realmConfigToCreate); } catch (UserStoreException e) { String msg = "Error in creating Realm for tenant, tenant domain: " + tenant.getDomain(); log.error(msg, e); throw new Exception(msg, e); } UserStoreManager userStoreManager; try { userStoreManager = userRealm.getUserStoreManager(); return userStoreManager; } catch (UserStoreException e) { String msg = "Error in getting the userstore/authorization manager for tenant: " + tenant.getDomain(); log.error(msg); throw new Exception(msg, e); } } /** * initializes tenant from the user input (tenant info bean) * * @param tenantInfoBean input * @return tenant */ public static Tenant initializeTenant(TenantInfoBean tenantInfoBean) { Tenant tenant = new Tenant(); tenant.setDomain(tenantInfoBean.getTenantDomain()); tenant.setEmail(tenantInfoBean.getEmail()); tenant.setAdminName(tenantInfoBean.getAdmin()); // set tenantId given in tenantInfoBean, if it is set, // underline tenant manager will try to create the tenant with given tenant Id. tenant.setId(tenantInfoBean.getTenantId()); // we are duplicating the params stored in the claims here as well; they // are in Tenant class // to make it work with LDAP; but they do not make it to the databases. tenant.setAdminFirstName(tenantInfoBean.getFirstname()); tenant.setAdminLastName(tenantInfoBean.getLastname()); tenant.setAdminPassword(tenantInfoBean.getAdminPassword()); // sets created date. Calendar createdDateCal = tenantInfoBean.getCreatedDate(); long createdDate; if (createdDateCal != null) { createdDate = createdDateCal.getTimeInMillis(); } else { createdDate = System.currentTimeMillis(); } tenant.setCreatedDate(new Date(createdDate)); if (log.isDebugEnabled()) { log.debug("Tenant object Initialized from the TenantInfoBean"); } return tenant; } /** * Initializes a tenantInfoBean object for a given tenant. * * @param tenantId tenant id. * @param tenant a tenant. * @return tenantInfoBean * @throws Exception , exception in getting the adminUserName from tenantId */ public static TenantInfoBean initializeTenantInfoBean( int tenantId, Tenant tenant) throws Exception { TenantInfoBean bean = getTenantInfoBeanfromTenant(tenantId, tenant); if (tenant != null) { bean.setAdmin(ClaimsMgtUtil.getAdminUserNameFromTenantId( TenantMgtServiceComponent.getRealmService(), tenantId)); } return bean; } /** * initializes a TenantInfoBean object from the tenant * @param tenantId, tenant id * @param tenant, tenant * @return TenantInfoBean. */ public static TenantInfoBean getTenantInfoBeanfromTenant(int tenantId, Tenant tenant) { TenantInfoBean bean = new TenantInfoBean(); if (tenant != null) { bean.setTenantId(tenantId); bean.setTenantDomain(tenant.getDomain()); bean.setEmail(tenant.getEmail()); /*gets the created date*/ Calendar createdDate = Calendar.getInstance(); createdDate.setTimeInMillis(tenant.getCreatedDate().getTime()); bean.setCreatedDate(createdDate); bean.setActive(tenant.isActive()); if(log.isDebugEnabled()) { log.debug("The TenantInfoBean object has been created from the tenant."); } } else { if(log.isDebugEnabled()) { log.debug("The tenant is null."); } } return bean; } /** * Adds claims to UserStoreManager * * @param tenant a tenant * @throws Exception if error in adding claims to the user. */ public static void addClaimsToUserStoreManager(Tenant tenant) throws Exception { try { Map<String, String> claimsMap = new HashMap<String, String>(); claimsMap.put(UserCoreConstants.ClaimTypeURIs.GIVEN_NAME, tenant.getAdminFirstName()); claimsMap.put(UserCoreConstants.ClaimTypeURIs.SURNAME, tenant.getAdminLastName()); // can be extended to store other user information. UserStoreManager userStoreManager = (UserStoreManager) TenantMgtServiceComponent.getRealmService(). getTenantUserRealm(tenant.getId()).getUserStoreManager(); userStoreManager.setUserClaimValues(tenant.getAdminName(), claimsMap, UserCoreConstants.DEFAULT_PROFILE); } catch (Exception e) { String msg = "Error in adding claims to the user."; log.error(msg, e); throw new Exception(msg, e); } } /** * Activate a tenant during the time of the tenant creation. * * @param tenantInfoBean tenant information * @param tenantId tenant Id * @throws Exception UserStoreException. */ public static void activateTenantInitially(TenantInfoBean tenantInfoBean, int tenantId) throws Exception { TenantManager tenantManager = TenantMgtServiceComponent.getTenantManager(); String tenantDomain = tenantInfoBean.getTenantDomain(); TenantMgtUtil.activateTenant(tenantDomain, tenantManager, tenantId); if (log.isDebugEnabled()) { log.debug("Activated the tenant " + tenantDomain + " at the time of tenant creation"); } //Notify tenant activation try { TenantMgtUtil.triggerTenantInitialActivation(tenantInfoBean); } catch (StratosException e) { String msg = "Error in notifying tenant initial activation."; log.error(msg, e); throw new Exception(msg, e); } } /** * Activate the given tenant, either at the time of tenant creation, or later by super admin. * * @param tenantDomain tenant domain * @param tenantManager TenantManager object * @param tenantId tenant Id * @throws Exception UserStoreException. */ public static void activateTenant(String tenantDomain, TenantManager tenantManager, int tenantId) throws Exception { try { tenantManager.activateTenant(tenantId); } catch (UserStoreException e) { String msg = "Error in activating the tenant for tenant domain: " + tenantDomain + "."; log.error(msg, e); throw new Exception(msg, e); } //activating the subscription /*try { if (TenantMgtServiceComponent.getBillingService() != null) { TenantMgtServiceComponent.getBillingService().activateUsagePlan(tenantDomain); } } catch (Exception e) { String msg = "Error while activating subscription for domain: " + tenantDomain + "."; log.error(msg, e); throw new Exception(msg, e); }*/ } /** * Deactivate the given tenant, by super admin. * * @param tenantDomain tenant domain * @param tenantManager TenantManager object * @param tenantId tenant Id * @throws Exception UserStoreException. */ public static void deactivateTenant(String tenantDomain, TenantManager tenantManager, int tenantId) throws Exception { try { tenantManager.deactivateTenant(tenantId); } catch (UserStoreException e) { String msg = "Error in deactivating tenant for tenant domain: " + tenantDomain + "."; log.error(msg, e); throw new Exception(msg, e); } //deactivating the subscription /*try { if (TenantMgtServiceComponent.getBillingService() != null) { TenantMgtServiceComponent.getBillingService().deactivateActiveUsagePlan(tenantDomain); } } catch (Exception e) { String msg = "Error while deactivating subscription for domain: " + tenantDomain + "."; log.error(msg, e); throw new Exception(msg, e); }*/ } public static void deleteTenantRegistryData(int tenantId) throws Exception { // delete data from mounted config registry database JDBCDataAccessManager configMgr = (JDBCDataAccessManager) TenantMgtServiceComponent.getRegistryService(). getConfigUserRegistry().getRegistryContext().getDataAccessManager(); TenantRegistryDataDeletionUtil.deleteTenantRegistryData(tenantId, configMgr.getDataSource().getConnection()); // delete data from mounted governance registry database JDBCDataAccessManager govMgr = (JDBCDataAccessManager) TenantMgtServiceComponent.getRegistryService(). getGovernanceUserRegistry().getRegistryContext().getDataAccessManager(); TenantRegistryDataDeletionUtil.deleteTenantRegistryData(tenantId, govMgr.getDataSource().getConnection()); } public static void deleteTenantUMData(int tenantId) throws Exception { RealmConfiguration realmConfig = TenantMgtServiceComponent.getRealmService(). getBootstrapRealmConfiguration(); BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(realmConfig.getRealmProperty(JDBCRealmConstants.DRIVER_NAME)); dataSource.setUrl(realmConfig.getRealmProperty(JDBCRealmConstants.URL)); dataSource.setUsername(realmConfig.getRealmProperty(JDBCRealmConstants.USER_NAME)); dataSource.setPassword(realmConfig.getRealmProperty(JDBCRealmConstants.PASSWORD)); dataSource.setMaxActive(Integer.parseInt(realmConfig.getRealmProperty(JDBCRealmConstants.MAX_ACTIVE))); dataSource.setMinIdle(Integer.parseInt(realmConfig.getRealmProperty(JDBCRealmConstants.MIN_IDLE))); dataSource.setMaxWait(Integer.parseInt(realmConfig.getRealmProperty(JDBCRealmConstants.MAX_WAIT))); TenantUMDataDeletionUtil.deleteTenantUMData(tenantId, dataSource.getConnection()); } /** * Broadcast TenantDeleteClusterMessage to all worker nodes * * @param tenantId * @throws Exception */ public static void deleteWorkernodesTenant(int tenantId) throws Exception { TenantDeleteClusterMessage clustermessage = new TenantDeleteClusterMessage( tenantId); ConfigurationContext configContext = TenantMgtServiceComponent.getConfigurationContext(); ClusteringAgent agent = configContext.getAxisConfiguration() .getClusteringAgent(); try { agent.sendMessage(clustermessage, true); } catch (ClusteringFault e) { log.error("Error occurred while broadcasting TenantDeleteClusterMessage : " + e.getMessage()); } } /** * Delete tenant data specific to product from database. * * @param dataSourceName * @param tableName * @param tenantId */ public static void deleteProductSpecificTenantData(String dataSourceName, String tableName, int tenantId) { try { TenantDataDeletionUtil.deleteProductSpecificTenantData(((DataSource) InitialContext.doLookup(dataSourceName)). getConnection(), tableName, tenantId); } catch (Exception e) { throw new RuntimeException("Error in looking up data source: " + e.getMessage(), e); } } }
components/tenant-mgt/org.wso2.carbon.tenant.mgt/src/main/java/org/wso2/carbon/tenant/mgt/util/TenantMgtUtil.java
/* * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) 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. */ package org.wso2.carbon.tenant.mgt.util; import org.apache.axis2.clustering.ClusteringAgent; import org.apache.axis2.clustering.ClusteringFault; import org.apache.axis2.context.ConfigurationContext; import org.apache.commons.dbcp.BasicDataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.registry.core.RegistryConstants; import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.jdbc.dataaccess.JDBCDataAccessManager; import org.wso2.carbon.registry.core.session.UserRegistry; import org.wso2.carbon.registry.core.utils.UUIDGenerator; import org.wso2.carbon.stratos.common.beans.TenantInfoBean; import org.wso2.carbon.stratos.common.constants.StratosConstants; import org.wso2.carbon.stratos.common.exception.StratosException; import org.wso2.carbon.stratos.common.listeners.TenantMgtListener; import org.wso2.carbon.stratos.common.util.ClaimsMgtUtil; import org.wso2.carbon.stratos.common.util.CommonUtil; import org.wso2.carbon.tenant.mgt.internal.TenantMgtServiceComponent; import org.wso2.carbon.tenant.mgt.message.TenantDeleteClusterMessage; import org.wso2.carbon.user.api.RealmConfiguration; import org.wso2.carbon.user.api.TenantMgtConfiguration; import org.wso2.carbon.user.core.UserCoreConstants; import org.wso2.carbon.user.core.UserRealm; import org.wso2.carbon.user.core.UserStoreException; import org.wso2.carbon.user.core.UserStoreManager; import org.wso2.carbon.user.core.config.multitenancy.MultiTenantRealmConfigBuilder; import org.wso2.carbon.user.core.jdbc.JDBCRealmConstants; import org.wso2.carbon.user.core.tenant.Tenant; import org.wso2.carbon.user.core.tenant.TenantManager; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import javax.naming.InitialContext; import javax.sql.DataSource; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * Utility methods for tenant management. */ public class TenantMgtUtil { private static final Log log = LogFactory.getLog(TenantMgtUtil.class); private static final String ILLEGAL_CHARACTERS_FOR_TENANT_DOMAIN = ".*[^a-zA-Z0-9\\._\\-].*"; /** * Prepares string to show theme management page. * * @param tenantId - tenant id * @return UUID * @throws RegistryException, if failed. */ public static String prepareStringToShowThemeMgtPage(int tenantId) throws RegistryException { // first we generate a UUID UserRegistry systemRegistry = TenantMgtServiceComponent.getRegistryService().getGovernanceSystemRegistry(); String uuid = UUIDGenerator.generateUUID(); // store it in the registry. Resource resource = systemRegistry.newResource(); String tenantIdStr = Integer.toString(tenantId); resource.setProperty(MultitenantConstants.TENANT_ID, tenantIdStr); String uuidPath = StratosConstants.TENANT_CREATION_THEME_PAGE_TOKEN + RegistryConstants.PATH_SEPARATOR + uuid; systemRegistry.put(uuidPath, resource); // restrict access CommonUtil.denyAnonAuthorization(uuidPath, systemRegistry.getUserRealm()); return uuid; } /** * Triggers adding the tenant for TenantMgtListener * * @param tenantInfo tenant * @throws StratosException, trigger failed */ public static void triggerAddTenant(TenantInfoBean tenantInfo) throws StratosException { // initializeRegistry(tenantInfoBean.getTenantId()); for (TenantMgtListener tenantMgtListener : TenantMgtServiceComponent.getTenantMgtListeners()) { tenantMgtListener.onTenantCreate(tenantInfo); } } /** * Triggers pre tenant delete for TenantMgtListener * * @param tenantId int * @throws StratosException , trigger failed */ public static void triggerPreTenantDelete(int tenantId) throws StratosException { for (TenantMgtListener tenantMgtListener : TenantMgtServiceComponent .getTenantMgtListeners()) { log.debug("Executing OnPreDelete on Listener Impl Class Name : " + tenantMgtListener.getClass().getName()); tenantMgtListener.onPreDelete(tenantId); } } /** * Triggers an update for the tenant for TenantMgtListener * * @param tenantInfoBean tenantInfoBean * @throws org.wso2.carbon.stratos.common.exception.StratosException, if update failed */ public static void triggerUpdateTenant( TenantInfoBean tenantInfoBean) throws StratosException { for (TenantMgtListener tenantMgtListener : TenantMgtServiceComponent.getTenantMgtListeners()) { tenantMgtListener.onTenantUpdate(tenantInfoBean); } } public static void triggerTenantInitialActivation( TenantInfoBean tenantInfoBean) throws StratosException { for (TenantMgtListener tenantMgtListener : TenantMgtServiceComponent.getTenantMgtListeners()) { tenantMgtListener.onTenantInitialActivation(tenantInfoBean.getTenantId()); } } public static void triggerTenantActivation(int tenantId) throws StratosException { for (TenantMgtListener tenantMgtListener : TenantMgtServiceComponent.getTenantMgtListeners()) { tenantMgtListener.onTenantActivation(tenantId); } } public static void triggerTenantDeactivation(int tenantId) throws StratosException { for (TenantMgtListener tenantMgtListener : TenantMgtServiceComponent.getTenantMgtListeners()) { tenantMgtListener.onTenantDeactivation(tenantId); } } /** * Validate the tenant domain * * @param domainName tenant domain * @throws Exception , if invalid tenant domain name is given */ public static void validateDomain(String domainName) throws Exception { if (domainName == null || domainName.equals("")) { String msg = "Provided domain name is empty."; log.error(msg); throw new Exception(msg); } // ensures the .ext for the public clouds. if (CommonUtil.isPublicCloudSetup()) { int lastIndexOfDot = domainName.lastIndexOf("."); if (lastIndexOfDot <= 0) { String msg = "You should have an extension to your domain."; log.error(msg); throw new Exception(msg); } } int indexOfDot = domainName.indexOf("."); if (indexOfDot == 0) { // can't start a domain starting with "."; String msg = "Invalid domain, starting with '.'"; log.error(msg); throw new Exception(msg); } // check the tenant domain contains any illegal characters if (domainName.matches(ILLEGAL_CHARACTERS_FOR_TENANT_DOMAIN)) { String msg = "The tenant domain ' " + domainName + " ' contains one or more illegal characters. the valid characters are " + "letters, numbers, '.', '-' and '_'"; log.error(msg); throw new Exception(msg); } } /** * gets the UserStoreManager for a tenant * * @param tenant - a tenant * @param tenantId - tenant Id. To avoid the sequences where tenant.getId() may * produce the super tenant's tenant Id. * @return UserStoreManager * @throws Exception UserStoreException */ public static UserStoreManager getUserStoreManager(Tenant tenant, int tenantId) throws Exception { // get the system registry for the tenant RealmConfiguration realmConfig = TenantMgtServiceComponent.getBootstrapRealmConfiguration(); TenantMgtConfiguration tenantMgtConfiguration = TenantMgtServiceComponent.getRealmService().getTenantMgtConfiguration(); UserRealm userRealm; try { MultiTenantRealmConfigBuilder builder = TenantMgtServiceComponent.getRealmService(). getMultiTenantRealmConfigBuilder(); RealmConfiguration realmConfigToPersist = builder. getRealmConfigForTenantToPersist(realmConfig, tenantMgtConfiguration, tenant, tenantId); RealmConfiguration realmConfigToCreate = builder.getRealmConfigForTenantToCreateRealmOnTenantCreation( realmConfig, realmConfigToPersist, tenantId); userRealm = TenantMgtServiceComponent.getRealmService(). getUserRealm(realmConfigToCreate); } catch (UserStoreException e) { String msg = "Error in creating Realm for tenant, tenant domain: " + tenant.getDomain(); log.error(msg, e); throw new Exception(msg, e); } UserStoreManager userStoreManager; try { userStoreManager = userRealm.getUserStoreManager(); return userStoreManager; } catch (UserStoreException e) { String msg = "Error in getting the userstore/authorization manager for tenant: " + tenant.getDomain(); log.error(msg); throw new Exception(msg, e); } } /** * initializes tenant from the user input (tenant info bean) * * @param tenantInfoBean input * @return tenant */ public static Tenant initializeTenant(TenantInfoBean tenantInfoBean) { Tenant tenant = new Tenant(); tenant.setDomain(tenantInfoBean.getTenantDomain()); tenant.setEmail(tenantInfoBean.getEmail()); tenant.setAdminName(tenantInfoBean.getAdmin()); // set tenantId given in tenantInfoBean, if it is set, // underline tenant manager will try to create the tenant with given tenant Id. tenant.setId(tenantInfoBean.getTenantId()); // we are duplicating the params stored in the claims here as well; they // are in Tenant class // to make it work with LDAP; but they do not make it to the databases. tenant.setAdminFirstName(tenantInfoBean.getFirstname()); tenant.setAdminLastName(tenantInfoBean.getLastname()); tenant.setAdminPassword(tenantInfoBean.getAdminPassword()); // sets created date. Calendar createdDateCal = tenantInfoBean.getCreatedDate(); long createdDate; if (createdDateCal != null) { createdDate = createdDateCal.getTimeInMillis(); } else { createdDate = System.currentTimeMillis(); } tenant.setCreatedDate(new Date(createdDate)); if (log.isDebugEnabled()) { log.debug("Tenant object Initialized from the TenantInfoBean"); } return tenant; } /** * Initializes a tenantInfoBean object for a given tenant. * * @param tenantId tenant id. * @param tenant a tenant. * @return tenantInfoBean * @throws Exception , exception in getting the adminUserName from tenantId */ public static TenantInfoBean initializeTenantInfoBean( int tenantId, Tenant tenant) throws Exception { TenantInfoBean bean = getTenantInfoBeanfromTenant(tenantId, tenant); if (tenant != null) { bean.setAdmin(ClaimsMgtUtil.getAdminUserNameFromTenantId( TenantMgtServiceComponent.getRealmService(), tenantId)); } return bean; } /** * initializes a TenantInfoBean object from the tenant * @param tenantId, tenant id * @param tenant, tenant * @return TenantInfoBean. */ public static TenantInfoBean getTenantInfoBeanfromTenant(int tenantId, Tenant tenant) { TenantInfoBean bean = new TenantInfoBean(); if (tenant != null) { bean.setTenantId(tenantId); bean.setTenantDomain(tenant.getDomain()); bean.setEmail(tenant.getEmail()); /*gets the created date*/ Calendar createdDate = Calendar.getInstance(); createdDate.setTimeInMillis(tenant.getCreatedDate().getTime()); bean.setCreatedDate(createdDate); bean.setActive(tenant.isActive()); if(log.isDebugEnabled()) { log.debug("The TenantInfoBean object has been created from the tenant."); } } else { if(log.isDebugEnabled()) { log.debug("The tenant is null."); } } return bean; } /** * Adds claims to UserStoreManager * * @param tenant a tenant * @throws Exception if error in adding claims to the user. */ public static void addClaimsToUserStoreManager(Tenant tenant) throws Exception { try { Map<String, String> claimsMap = new HashMap<String, String>(); claimsMap.put(UserCoreConstants.ClaimTypeURIs.GIVEN_NAME, tenant.getAdminFirstName()); claimsMap.put(UserCoreConstants.ClaimTypeURIs.SURNAME, tenant.getAdminLastName()); // can be extended to store other user information. UserStoreManager userStoreManager = (UserStoreManager) TenantMgtServiceComponent.getRealmService(). getTenantUserRealm(tenant.getId()).getUserStoreManager(); userStoreManager.setUserClaimValues(tenant.getAdminName(), claimsMap, UserCoreConstants.DEFAULT_PROFILE); } catch (Exception e) { String msg = "Error in adding claims to the user."; log.error(msg, e); throw new Exception(msg, e); } } /** * Activate a tenant during the time of the tenant creation. * * @param tenantInfoBean tenant information * @param tenantId tenant Id * @throws Exception UserStoreException. */ public static void activateTenantInitially(TenantInfoBean tenantInfoBean, int tenantId) throws Exception { TenantManager tenantManager = TenantMgtServiceComponent.getTenantManager(); String tenantDomain = tenantInfoBean.getTenantDomain(); TenantMgtUtil.activateTenant(tenantDomain, tenantManager, tenantId); if (log.isDebugEnabled()) { log.debug("Activated the tenant " + tenantDomain + " at the time of tenant creation"); } //Notify tenant activation try { TenantMgtUtil.triggerTenantInitialActivation(tenantInfoBean); } catch (StratosException e) { String msg = "Error in notifying tenant initial activation."; log.error(msg, e); throw new Exception(msg, e); } } /** * Activate the given tenant, either at the time of tenant creation, or later by super admin. * * @param tenantDomain tenant domain * @param tenantManager TenantManager object * @param tenantId tenant Id * @throws Exception UserStoreException. */ public static void activateTenant(String tenantDomain, TenantManager tenantManager, int tenantId) throws Exception { try { tenantManager.activateTenant(tenantId); } catch (UserStoreException e) { String msg = "Error in activating the tenant for tenant domain: " + tenantDomain + "."; log.error(msg, e); throw new Exception(msg, e); } //activating the subscription /*try { if (TenantMgtServiceComponent.getBillingService() != null) { TenantMgtServiceComponent.getBillingService().activateUsagePlan(tenantDomain); } } catch (Exception e) { String msg = "Error while activating subscription for domain: " + tenantDomain + "."; log.error(msg, e); throw new Exception(msg, e); }*/ } /** * Deactivate the given tenant, by super admin. * * @param tenantDomain tenant domain * @param tenantManager TenantManager object * @param tenantId tenant Id * @throws Exception UserStoreException. */ public static void deactivateTenant(String tenantDomain, TenantManager tenantManager, int tenantId) throws Exception { try { tenantManager.deactivateTenant(tenantId); } catch (UserStoreException e) { String msg = "Error in deactivating tenant for tenant domain: " + tenantDomain + "."; log.error(msg, e); throw new Exception(msg, e); } //deactivating the subscription /*try { if (TenantMgtServiceComponent.getBillingService() != null) { TenantMgtServiceComponent.getBillingService().deactivateActiveUsagePlan(tenantDomain); } } catch (Exception e) { String msg = "Error while deactivating subscription for domain: " + tenantDomain + "."; log.error(msg, e); throw new Exception(msg, e); }*/ } public static void deleteTenantRegistryData(int tenantId) throws Exception { // delete data from mounted config registry database JDBCDataAccessManager configMgr = (JDBCDataAccessManager) TenantMgtServiceComponent.getRegistryService(). getConfigUserRegistry().getRegistryContext().getDataAccessManager(); TenantRegistryDataDeletionUtil.deleteTenantRegistryData(tenantId, configMgr.getDataSource().getConnection()); // delete data from mounted governance registry database JDBCDataAccessManager govMgr = (JDBCDataAccessManager) TenantMgtServiceComponent.getRegistryService(). getGovernanceUserRegistry().getRegistryContext().getDataAccessManager(); TenantRegistryDataDeletionUtil.deleteTenantRegistryData(tenantId, govMgr.getDataSource().getConnection()); } public static void deleteTenantUMData(int tenantId) throws Exception { RealmConfiguration realmConfig = TenantMgtServiceComponent.getRealmService(). getBootstrapRealmConfiguration(); BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(realmConfig.getRealmProperty(JDBCRealmConstants.DRIVER_NAME)); dataSource.setUrl(realmConfig.getRealmProperty(JDBCRealmConstants.URL)); dataSource.setUsername(realmConfig.getRealmProperty(JDBCRealmConstants.USER_NAME)); dataSource.setPassword(realmConfig.getRealmProperty(JDBCRealmConstants.PASSWORD)); dataSource.setMaxActive(Integer.parseInt(realmConfig.getRealmProperty(JDBCRealmConstants.MAX_ACTIVE))); dataSource.setMinIdle(Integer.parseInt(realmConfig.getRealmProperty(JDBCRealmConstants.MIN_IDLE))); dataSource.setMaxWait(Integer.parseInt(realmConfig.getRealmProperty(JDBCRealmConstants.MAX_WAIT))); TenantUMDataDeletionUtil.deleteTenantUMData(tenantId, dataSource.getConnection()); } /** * Broadcast TenantDeleteClusterMessage to all worker nodes * * @param tenantId * @throws Exception */ public static void deleteWorkernodesTenant(int tenantId) throws Exception { TenantDeleteClusterMessage clustermessage = new TenantDeleteClusterMessage( tenantId); ConfigurationContext configContext = TenantMgtServiceComponent.getConfigurationContext(); ClusteringAgent agent = configContext.getAxisConfiguration() .getClusteringAgent(); try { agent.sendMessage(clustermessage, true); } catch (ClusteringFault e) { log.error("Error occurred while broadcasting TenantDeleteClusterMessage : " + e.getMessage()); } } /** * Delete tenant data specific to product from database. * * @param dataSourceName * @param tableName * @param tenantId */ public static void deleteProductSpecificTenantData(String dataSourceName, String tableName, int tenantId) { try { TenantDataDeletionUtil.deleteProductSpecificTenantData(((DataSource) InitialContext.doLookup(dataSourceName)).getConnection(), tableName, tenantId); } catch (Exception e) { throw new RuntimeException("Error in looking up data source: " + e.getMessage(), e); } } }
corrected some formatting
components/tenant-mgt/org.wso2.carbon.tenant.mgt/src/main/java/org/wso2/carbon/tenant/mgt/util/TenantMgtUtil.java
corrected some formatting
<ide><path>omponents/tenant-mgt/org.wso2.carbon.tenant.mgt/src/main/java/org/wso2/carbon/tenant/mgt/util/TenantMgtUtil.java <ide> */ <ide> public static void deleteProductSpecificTenantData(String dataSourceName, String tableName, int tenantId) { <ide> try { <del> TenantDataDeletionUtil.deleteProductSpecificTenantData(((DataSource) InitialContext.doLookup(dataSourceName)).getConnection(), tableName, tenantId); <add> TenantDataDeletionUtil.deleteProductSpecificTenantData(((DataSource) InitialContext.doLookup(dataSourceName)). <add> getConnection(), tableName, tenantId); <ide> } catch (Exception e) { <ide> throw new RuntimeException("Error in looking up data source: " + e.getMessage(), e); <ide> }
Java
apache-2.0
92200a5f1feff2bea850a750b189b6b15b96c2fa
0
gzsombor/ranger,gzsombor/ranger,gzsombor/ranger,gzsombor/ranger,gzsombor/ranger,gzsombor/ranger
/* * 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.ranger.server.tomcat; import java.io.File; import java.io.IOException; import java.net.URL; import java.security.PrivilegedAction; import java.util.Date; import java.util.Iterator; import java.util.Properties; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.catalina.Context; import org.apache.catalina.LifecycleException; import org.apache.catalina.connector.Connector; import org.apache.catalina.startup.Tomcat; import org.apache.catalina.valves.AccessLogValve; import org.apache.hadoop.security.SecureClientLogin; import javax.security.auth.Subject; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class EmbeddedServer { private static final Logger LOG = Logger.getLogger(EmbeddedServer.class .getName()); private static final String DEFAULT_CONFIG_FILENAME = "ranger-admin-site.xml"; private static final String CORE_SITE_CONFIG_FILENAME = "core-site.xml"; private static final String DEFAULT_WEBAPPS_ROOT_FOLDER = "webapps"; private static String configFile = DEFAULT_CONFIG_FILENAME; private static final String AUTH_TYPE_KERBEROS = "kerberos"; private static final String AUTHENTICATION_TYPE = "hadoop.security.authentication"; private static final String ADMIN_USER_PRINCIPAL = "ranger.admin.kerberos.principal"; private static final String ADMIN_USER_KEYTAB = "ranger.admin.kerberos.keytab"; private static final String ADMIN_NAME_RULES = "hadoop.security.auth_to_local"; private Properties serverConfigProperties = new Properties(); public static void main(String[] args) { new EmbeddedServer(args).start(); } public EmbeddedServer(String[] args) { if (args.length > 0) { configFile = args[0]; } loadConfig(CORE_SITE_CONFIG_FILENAME); loadConfig(configFile); } public static int DEFAULT_SHUTDOWN_PORT = 6185; public static String DEFAULT_SHUTDOWN_COMMAND = "SHUTDOWN"; public void start() { final Tomcat server = new Tomcat(); String logDir = null; logDir = getConfig("logdir"); if(logDir == null) { logDir = getConfig("kms.log.dir"); } String hostName = getConfig("ranger.service.host"); int serverPort = getIntConfig("ranger.service.http.port", 6181); int sslPort = getIntConfig("ranger.service.https.port", -1); int shutdownPort = getIntConfig("ranger.service.shutdown.port",DEFAULT_SHUTDOWN_PORT); String shutdownCommand = getConfig("ranger.service.shutdown.command",DEFAULT_SHUTDOWN_COMMAND); server.setHostname(hostName); server.setPort(serverPort); server.getServer().setPort(shutdownPort); server.getServer().setShutdown(shutdownCommand); boolean isHttpsEnabled = Boolean.valueOf(getConfig("ranger.service.https.attrib.ssl.enabled", "false")); boolean ajpEnabled = Boolean.valueOf(getConfig("ajp.enabled", "false")); if (ajpEnabled) { Connector ajpConnector = new Connector( "org.apache.coyote.ajp.AjpNioProtocol"); ajpConnector.setPort(serverPort); ajpConnector.setProperty("protocol", "AJP/1.3"); server.getService().addConnector(ajpConnector); // Making this as a default connector server.setConnector(ajpConnector); LOG.info("Created AJP Connector"); } else if ((sslPort > 0) && isHttpsEnabled) { Connector ssl = new Connector(); ssl.setPort(sslPort); ssl.setSecure(true); ssl.setScheme("https"); ssl.setAttribute("SSLEnabled", "true"); ssl.setAttribute("sslProtocol", getConfig("ranger.service.https.attrib.ssl.protocol", "TLS")); ssl.setAttribute("clientAuth", getConfig("ranger.service.https.attrib.clientAuth", "false")); ssl.setAttribute("keyAlias", getConfig("ranger.service.https.attrib.keystore.keyalias")); ssl.setAttribute("keystorePass", getConfig("ranger.service.https.attrib.keystore.pass")); ssl.setAttribute("keystoreFile", getKeystoreFile()); String enabledProtocols = "SSLv2Hello, TLSv1, TLSv1.1, TLSv1.2"; ssl.setAttribute("sslEnabledProtocols", enabledProtocols); server.getService().addConnector(ssl); // // Making this as a default connector // server.setConnector(ssl); } updateHttpConnectorAttribConfig(server); File logDirectory = new File(logDir); if (!logDirectory.exists()) { logDirectory.mkdirs(); } AccessLogValve valve = new AccessLogValve(); valve.setRotatable(true); valve.setAsyncSupported(true); valve.setBuffered(false); valve.setEnabled(true); valve.setFileDateFormat(getConfig("ranger.accesslog.dateformat", "yyyy-MM-dd.HH")); valve.setDirectory(logDirectory.getAbsolutePath()); valve.setSuffix(".log"); String logPattern = getConfig("ranger.accesslog.pattern", "%h %l %u %t \"%r\" %s %b"); valve.setPattern(logPattern); server.getHost().getPipeline().addValve(valve); try { String webapp_dir = getConfig("xa.webapp.dir"); if (webapp_dir == null || webapp_dir.trim().isEmpty()) { // If webapp location property is not set, then let's derive // from catalina_base String catalina_base = getConfig("catalina.base"); if (catalina_base == null || catalina_base.trim().isEmpty()) { LOG.severe("Tomcat Server failed to start: catalina.base and/or xa.webapp.dir is not set"); System.exit(1); } webapp_dir = catalina_base + File.separator + "webapp"; LOG.info("Deriving webapp folder from catalina.base property. folder=" + webapp_dir); } //String webContextName = getConfig("xa.webapp.contextName", "/"); String webContextName = getConfig("ranger.contextName", "/"); if (webContextName == null) { webContextName = "/"; } else if (!webContextName.startsWith("/")) { LOG.info("Context Name [" + webContextName + "] is being loaded as [ /" + webContextName + "]"); webContextName = "/" + webContextName; } File wad = new File(webapp_dir); if (wad.isDirectory()) { LOG.info("Webapp file =" + webapp_dir + ", webAppName = " + webContextName); } else if (wad.isFile()) { File webAppDir = new File(DEFAULT_WEBAPPS_ROOT_FOLDER); if (!webAppDir.exists()) { webAppDir.mkdirs(); } LOG.info("Webapp file =" + webapp_dir + ", webAppName = " + webContextName); } LOG.info("Adding webapp [" + webContextName + "] = path [" + webapp_dir + "] ....."); Context webappCtx = server.addWebapp(webContextName, new File( webapp_dir).getAbsolutePath()); webappCtx.init(); LOG.info("Finished init of webapp [" + webContextName + "] = path [" + webapp_dir + "]."); } catch (ServletException e1) { LOG.severe("Tomcat Server failed to add webapp:" + e1.toString()); e1.printStackTrace(); } catch (LifecycleException lce) { LOG.severe("Tomcat Server failed to start webapp:" + lce.toString()); lce.printStackTrace(); } if(getConfig("logdir") != null){ String keytab = getConfig(ADMIN_USER_KEYTAB); // String principal = getConfig(ADMIN_USER_PRINCIPAL); String principal = null; try { principal = SecureClientLogin.getPrincipal(getConfig(ADMIN_USER_PRINCIPAL), hostName); } catch (IOException ignored) { // do nothing } String nameRules = getConfig(ADMIN_NAME_RULES); if(getConfig(AUTHENTICATION_TYPE) != null && getConfig(AUTHENTICATION_TYPE).trim().equalsIgnoreCase(AUTH_TYPE_KERBEROS) && SecureClientLogin.isKerberosCredentialExists(principal, keytab)){ try{ LOG.info("Provided Kerberos Credential : Principal = "+principal+" and Keytab = "+keytab); Subject sub = SecureClientLogin.loginUserFromKeytab(principal, keytab, nameRules); Subject.doAs(sub, new PrivilegedAction<Void>() { @Override public Void run() { LOG.info("Starting Server using kerberos crendential"); startServer(server); return null; } }); }catch(Exception e){ LOG.severe("Tomcat Server failed to start:" + e.toString()); e.printStackTrace(); } }else{ startServer(server); } }else{ startServer(server); } } private void startServer(final Tomcat server) { try{ server.start(); server.getServer().await(); shutdownServer(); } catch (LifecycleException e) { LOG.severe("Tomcat Server failed to start:" + e.toString()); e.printStackTrace(); } catch (Exception e) { LOG.severe("Tomcat Server failed to start:" + e.toString()); e.printStackTrace(); } } private String getKeystoreFile() { String keystoreFile=getConfig("ranger.service.https.attrib.keystore.file"); if (keystoreFile == null || keystoreFile.trim().isEmpty()) { // new property not configured, lets use the old property keystoreFile = getConfig("ranger.https.attrib.keystore.file"); } return keystoreFile; } protected String getConfig(String key) { String value = serverConfigProperties.getProperty(key); if (value == null || value.trim().isEmpty()) { // Value not found in properties file, let's try to get from // System's property value = System.getProperty(key); } return value; } protected String getConfig(String key, String defaultValue) { String ret = getConfig(key); if (ret == null) { ret = defaultValue; } return ret; } protected int getIntConfig(String key, int defaultValue) { int ret = 0; String retStr = getConfig(key); if (retStr == null) { ret = defaultValue; } else { ret = Integer.parseInt(retStr); } return ret; } private String getResourceFileName(String aResourceName) { String ret = aResourceName; ClassLoader cl = getClass().getClassLoader(); for (String path : new String[] { aResourceName, "/" + aResourceName }) { try { URL lurl = cl.getResource(path); if (lurl != null) { ret = lurl.getFile(); } } catch (Throwable t) { ret = null; } if (ret != null) { break; } } if (ret == null) { ret = aResourceName; } return ret; } public void shutdownServer() { int timeWaitForShutdownInSeconds = getIntConfig( "service.waitTimeForForceShutdownInSeconds", 0); if (timeWaitForShutdownInSeconds > 0) { long endTime = System.currentTimeMillis() + (timeWaitForShutdownInSeconds * 1000L); LOG.info("Will wait for all threads to shutdown gracefully. Final shutdown Time: " + new Date(endTime)); while (System.currentTimeMillis() < endTime) { int activeCount = Thread.activeCount(); if (activeCount == 0) { LOG.info("Number of active threads = " + activeCount + "."); break; } else { LOG.info("Number of active threads = " + activeCount + ". Waiting for all threads to shutdown ..."); try { Thread.sleep(5000L); } catch (InterruptedException e) { LOG.warning("shutdownServer process is interrupted with exception: " + e); break; } } } } LOG.info("Shuting down the Server."); System.exit(0); } public void loadConfig(String configFileName) { String path = getResourceFileName(configFileName); try { DocumentBuilderFactory xmlDocumentBuilderFactory = DocumentBuilderFactory .newInstance(); xmlDocumentBuilderFactory.setIgnoringComments(true); xmlDocumentBuilderFactory.setNamespaceAware(true); DocumentBuilder xmlDocumentBuilder = xmlDocumentBuilderFactory .newDocumentBuilder(); Document xmlDocument = xmlDocumentBuilder.parse(new File(path)); xmlDocument.getDocumentElement().normalize(); NodeList nList = xmlDocument.getElementsByTagName("property"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; String propertyName = ""; String propertyValue = ""; if (eElement.getElementsByTagName("name").item(0) != null) { propertyName = eElement.getElementsByTagName("name") .item(0).getTextContent().trim(); } if (eElement.getElementsByTagName("value").item(0) != null) { propertyValue = eElement.getElementsByTagName("value") .item(0).getTextContent().trim(); } serverConfigProperties.put(propertyName, propertyValue); } } } catch (Exception e) { e.printStackTrace(); } } protected long getLongConfig(String key, long defaultValue) { long ret = 0; String retStr = getConfig(key); if (retStr == null) { ret = defaultValue; } else { ret = Long.parseLong(retStr); } return ret; } public void updateHttpConnectorAttribConfig(Tomcat server) { server.getConnector().setAllowTrace(Boolean.valueOf(getConfig("ranger.service.http.connector.attrib.allowTrace","false"))); server.getConnector().setAsyncTimeout(getLongConfig("ranger.service.http.connector.attrib.asyncTimeout", 10000)); server.getConnector().setEnableLookups(Boolean.valueOf(getConfig("ranger.service.http.connector.attrib.enableLookups","false"))); server.getConnector().setMaxHeaderCount(getIntConfig("ranger.service.http.connector.attrib.maxHeaderCount", 100)); server.getConnector().setMaxParameterCount(getIntConfig("ranger.service.http.connector.attrib.maxParameterCount", 10000)); server.getConnector().setMaxPostSize(getIntConfig("ranger.service.http.connector.attrib.maxPostSize", 2097152)); server.getConnector().setMaxSavePostSize(getIntConfig("ranger.service.http.connector.attrib.maxSavePostSize", 4096)); server.getConnector().setParseBodyMethods(getConfig("ranger.service.http.connector.attrib.methods", "POST")); Iterator<Object> iterator=serverConfigProperties.keySet().iterator(); String key=null; String property=null; while (iterator.hasNext()){ key=iterator.next().toString(); if(key!=null && key.startsWith("ranger.service.http.connector.property.")){ property=key.replace("ranger.service.http.connector.property.",""); server.getConnector().setProperty(property,getConfig(key)); LOG.info(property+":"+server.getConnector().getProperty(property)); } } } }
embeddedwebserver/src/main/java/org/apache/ranger/server/tomcat/EmbeddedServer.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.ranger.server.tomcat; import java.io.File; import java.io.IOException; import java.net.URL; import java.security.PrivilegedAction; import java.util.Date; import java.util.Iterator; import java.util.Properties; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.catalina.Context; import org.apache.catalina.LifecycleException; import org.apache.catalina.connector.Connector; import org.apache.catalina.startup.Tomcat; import org.apache.catalina.valves.AccessLogValve; import org.apache.hadoop.security.SecureClientLogin; import javax.security.auth.Subject; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class EmbeddedServer { private static final Logger LOG = Logger.getLogger(EmbeddedServer.class .getName()); private static final String DEFAULT_CONFIG_FILENAME = "ranger-admin-site.xml"; private static final String CORE_SITE_CONFIG_FILENAME = "core-site.xml"; private static final String DEFAULT_WEBAPPS_ROOT_FOLDER = "webapps"; private static String configFile = DEFAULT_CONFIG_FILENAME; private static final String AUTH_TYPE_KERBEROS = "kerberos"; private static final String AUTHENTICATION_TYPE = "hadoop.security.authentication"; private static final String ADMIN_USER_PRINCIPAL = "ranger.admin.kerberos.principal"; private static final String ADMIN_USER_KEYTAB = "ranger.admin.kerberos.keytab"; private static final String ADMIN_NAME_RULES = "hadoop.security.auth_to_local"; private Properties serverConfigProperties = new Properties(); public static void main(String[] args) { new EmbeddedServer(args).start(); } public EmbeddedServer(String[] args) { if (args.length > 0) { configFile = args[0]; } loadConfig(CORE_SITE_CONFIG_FILENAME); loadConfig(configFile); } public static int DEFAULT_SHUTDOWN_PORT = 6185; public static String DEFAULT_SHUTDOWN_COMMAND = "SHUTDOWN"; public void start() { final Tomcat server = new Tomcat(); String logDir = null; logDir = getConfig("logdir"); if(logDir == null) { logDir = getConfig("kms.log.dir"); } String hostName = getConfig("ranger.service.host"); int serverPort = getIntConfig("ranger.service.http.port", 6181); int sslPort = getIntConfig("ranger.service.https.port", -1); int shutdownPort = getIntConfig("ranger.service.shutdown.port",DEFAULT_SHUTDOWN_PORT); String shutdownCommand = getConfig("ranger.service.shutdown.command",DEFAULT_SHUTDOWN_COMMAND); server.setHostname(hostName); server.setPort(serverPort); server.getServer().setPort(shutdownPort); server.getServer().setShutdown(shutdownCommand); boolean isHttpsEnabled = Boolean.valueOf(getConfig("ranger.service.https.attrib.ssl.enabled", "false")); boolean ajpEnabled = Boolean.valueOf(getConfig("ajp.enabled", "false")); if (ajpEnabled) { Connector ajpConnector = new Connector( "org.apache.coyote.ajp.AjpNioProtocol"); ajpConnector.setPort(serverPort); ajpConnector.setProperty("protocol", "AJP/1.3"); server.getService().addConnector(ajpConnector); // Making this as a default connector server.setConnector(ajpConnector); LOG.info("Created AJP Connector"); } else if ((sslPort > 0) && isHttpsEnabled) { Connector ssl = new Connector(); ssl.setPort(sslPort); ssl.setSecure(true); ssl.setScheme("https"); ssl.setAttribute("SSLEnabled", "true"); ssl.setAttribute("sslProtocol", getConfig("ranger.service.https.attrib.ssl.protocol", "TLS")); ssl.setAttribute("clientAuth", getConfig("ranger.service.https.attrib.clientAuth", "false")); ssl.setAttribute("keyAlias", getConfig("ranger.service.https.attrib.keystore.keyalias")); ssl.setAttribute("keystorePass", getConfig("ranger.service.https.attrib.keystore.pass")); ssl.setAttribute("keystoreFile", getKeystoreFile()); String enabledProtocols = "SSLv2Hello, TLSv1, TLSv1.1, TLSv1.2"; ssl.setAttribute("sslEnabledProtocols", enabledProtocols); server.getService().addConnector(ssl); // // Making this as a default connector // server.setConnector(ssl); } updateHttpConnectorAttribConfig(server); File logDirectory = new File(logDir); if (!logDirectory.exists()) { logDirectory.mkdirs(); } AccessLogValve valve = new AccessLogValve(); valve.setRotatable(true); valve.setAsyncSupported(true); valve.setBuffered(false); valve.setEnabled(true); valve.setFileDateFormat(getConfig("ranger.accesslog.dateformat", "yyyy-MM-dd.HH")); valve.setDirectory(logDirectory.getAbsolutePath()); valve.setRotatable(true); valve.setSuffix(".log"); String logPattern = getConfig("ranger.accesslog.pattern", "%h %l %u %t \"%r\" %s %b"); valve.setPattern(logPattern); server.getHost().getPipeline().addValve(valve); try { String webapp_dir = getConfig("xa.webapp.dir"); if (webapp_dir == null || webapp_dir.trim().isEmpty()) { // If webapp location property is not set, then let's derive // from catalina_base String catalina_base = getConfig("catalina.base"); if (catalina_base == null || catalina_base.trim().isEmpty()) { LOG.severe("Tomcat Server failed to start: catalina.base and/or xa.webapp.dir is not set"); System.exit(1); } webapp_dir = catalina_base + File.separator + "webapp"; LOG.info("Deriving webapp folder from catalina.base property. folder=" + webapp_dir); } //String webContextName = getConfig("xa.webapp.contextName", "/"); String webContextName = getConfig("ranger.contextName", "/"); if (webContextName == null) { webContextName = "/"; } else if (!webContextName.startsWith("/")) { LOG.info("Context Name [" + webContextName + "] is being loaded as [ /" + webContextName + "]"); webContextName = "/" + webContextName; } File wad = new File(webapp_dir); if (wad.isDirectory()) { LOG.info("Webapp file =" + webapp_dir + ", webAppName = " + webContextName); } else if (wad.isFile()) { File webAppDir = new File(DEFAULT_WEBAPPS_ROOT_FOLDER); if (!webAppDir.exists()) { webAppDir.mkdirs(); } LOG.info("Webapp file =" + webapp_dir + ", webAppName = " + webContextName); } LOG.info("Adding webapp [" + webContextName + "] = path [" + webapp_dir + "] ....."); Context webappCtx = server.addWebapp(webContextName, new File( webapp_dir).getAbsolutePath()); webappCtx.init(); LOG.info("Finished init of webapp [" + webContextName + "] = path [" + webapp_dir + "]."); } catch (ServletException e1) { LOG.severe("Tomcat Server failed to add webapp:" + e1.toString()); e1.printStackTrace(); } catch (LifecycleException lce) { LOG.severe("Tomcat Server failed to start webapp:" + lce.toString()); lce.printStackTrace(); } if(getConfig("logdir") != null){ String keytab = getConfig(ADMIN_USER_KEYTAB); // String principal = getConfig(ADMIN_USER_PRINCIPAL); String principal = null; try { principal = SecureClientLogin.getPrincipal(getConfig(ADMIN_USER_PRINCIPAL), hostName); } catch (IOException ignored) { // do nothing } String nameRules = getConfig(ADMIN_NAME_RULES); if(getConfig(AUTHENTICATION_TYPE) != null && getConfig(AUTHENTICATION_TYPE).trim().equalsIgnoreCase(AUTH_TYPE_KERBEROS) && SecureClientLogin.isKerberosCredentialExists(principal, keytab)){ try{ LOG.info("Provided Kerberos Credential : Principal = "+principal+" and Keytab = "+keytab); Subject sub = SecureClientLogin.loginUserFromKeytab(principal, keytab, nameRules); Subject.doAs(sub, new PrivilegedAction<Void>() { @Override public Void run() { try{ LOG.info("Starting Server using kerberos crendential"); server.start(); server.getServer().await(); shutdownServer(); }catch (LifecycleException e) { LOG.severe("Tomcat Server failed to start:" + e.toString()); e.printStackTrace(); }catch (Exception e) { LOG.severe("Tomcat Server failed to start:" + e.toString()); e.printStackTrace(); } return null; } }); }catch(Exception e){ LOG.severe("Tomcat Server failed to start:" + e.toString()); e.printStackTrace(); } }else{ try{ server.start(); server.getServer().await(); shutdownServer(); } catch (LifecycleException e) { LOG.severe("Tomcat Server failed to start:" + e.toString()); e.printStackTrace(); } catch (Exception e) { LOG.severe("Tomcat Server failed to start:" + e.toString()); e.printStackTrace(); } } }else{ try{ server.start(); server.getServer().await(); shutdownServer(); } catch (LifecycleException e) { LOG.severe("Tomcat Server failed to start:" + e.toString()); e.printStackTrace(); } catch (Exception e) { LOG.severe("Tomcat Server failed to start:" + e.toString()); e.printStackTrace(); } } } private String getKeystoreFile() { String keystoreFile=getConfig("ranger.service.https.attrib.keystore.file"); if (keystoreFile == null || keystoreFile.trim().isEmpty()) { // new property not configured, lets use the old property keystoreFile = getConfig("ranger.https.attrib.keystore.file"); } return keystoreFile; } protected String getConfig(String key) { String value = serverConfigProperties.getProperty(key); if (value == null || value.trim().isEmpty()) { // Value not found in properties file, let's try to get from // System's property value = System.getProperty(key); } return value; } protected String getConfig(String key, String defaultValue) { String ret = getConfig(key); if (ret == null) { ret = defaultValue; } return ret; } protected int getIntConfig(String key, int defaultValue) { int ret = 0; String retStr = getConfig(key); if (retStr == null) { ret = defaultValue; } else { ret = Integer.parseInt(retStr); } return ret; } private String getResourceFileName(String aResourceName) { String ret = aResourceName; ClassLoader cl = getClass().getClassLoader(); for (String path : new String[] { aResourceName, "/" + aResourceName }) { try { URL lurl = cl.getResource(path); if (lurl != null) { ret = lurl.getFile(); } } catch (Throwable t) { ret = null; } if (ret != null) { break; } } if (ret == null) { ret = aResourceName; } return ret; } public void shutdownServer() { int timeWaitForShutdownInSeconds = getIntConfig( "service.waitTimeForForceShutdownInSeconds", 0); if (timeWaitForShutdownInSeconds > 0) { long endTime = System.currentTimeMillis() + (timeWaitForShutdownInSeconds * 1000L); LOG.info("Will wait for all threads to shutdown gracefully. Final shutdown Time: " + new Date(endTime)); while (System.currentTimeMillis() < endTime) { int activeCount = Thread.activeCount(); if (activeCount == 0) { LOG.info("Number of active threads = " + activeCount + "."); break; } else { LOG.info("Number of active threads = " + activeCount + ". Waiting for all threads to shutdown ..."); try { Thread.sleep(5000L); } catch (InterruptedException e) { LOG.warning("shutdownServer process is interrupted with exception: " + e); break; } } } } LOG.info("Shuting down the Server."); System.exit(0); } public void loadConfig(String configFileName) { String path = getResourceFileName(configFileName); try { DocumentBuilderFactory xmlDocumentBuilderFactory = DocumentBuilderFactory .newInstance(); xmlDocumentBuilderFactory.setIgnoringComments(true); xmlDocumentBuilderFactory.setNamespaceAware(true); DocumentBuilder xmlDocumentBuilder = xmlDocumentBuilderFactory .newDocumentBuilder(); Document xmlDocument = xmlDocumentBuilder.parse(new File(path)); xmlDocument.getDocumentElement().normalize(); NodeList nList = xmlDocument.getElementsByTagName("property"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; String propertyName = ""; String propertyValue = ""; if (eElement.getElementsByTagName("name").item(0) != null) { propertyName = eElement.getElementsByTagName("name") .item(0).getTextContent().trim(); } if (eElement.getElementsByTagName("value").item(0) != null) { propertyValue = eElement.getElementsByTagName("value") .item(0).getTextContent().trim(); } serverConfigProperties.put(propertyName, propertyValue); } } } catch (Exception e) { e.printStackTrace(); } } protected long getLongConfig(String key, long defaultValue) { long ret = 0; String retStr = getConfig(key); if (retStr == null) { ret = defaultValue; } else { ret = Long.parseLong(retStr); } return ret; } public void updateHttpConnectorAttribConfig(Tomcat server) { server.getConnector().setAllowTrace(Boolean.valueOf(getConfig("ranger.service.http.connector.attrib.allowTrace","false"))); server.getConnector().setAsyncTimeout(getLongConfig("ranger.service.http.connector.attrib.asyncTimeout", 10000)); server.getConnector().setEnableLookups(Boolean.valueOf(getConfig("ranger.service.http.connector.attrib.enableLookups","false"))); server.getConnector().setMaxHeaderCount(getIntConfig("ranger.service.http.connector.attrib.maxHeaderCount", 100)); server.getConnector().setMaxParameterCount(getIntConfig("ranger.service.http.connector.attrib.maxParameterCount", 10000)); server.getConnector().setMaxPostSize(getIntConfig("ranger.service.http.connector.attrib.maxPostSize", 2097152)); server.getConnector().setMaxSavePostSize(getIntConfig("ranger.service.http.connector.attrib.maxSavePostSize", 4096)); server.getConnector().setParseBodyMethods(getConfig("ranger.service.http.connector.attrib.methods", "POST")); Iterator<Object> iterator=serverConfigProperties.keySet().iterator(); String key=null; String property=null; while (iterator.hasNext()){ key=iterator.next().toString(); if(key!=null && key.startsWith("ranger.service.http.connector.property.")){ property=key.replace("ranger.service.http.connector.property.",""); server.getConnector().setProperty(property,getConfig(key)); LOG.info(property+":"+server.getConnector().getProperty(property)); } } } }
RANGER-1287:Remove code duplication from EmbeddedServer start method Signed-off-by: Colm O hEigeartaigh <[email protected]>
embeddedwebserver/src/main/java/org/apache/ranger/server/tomcat/EmbeddedServer.java
RANGER-1287:Remove code duplication from EmbeddedServer start method
<ide><path>mbeddedwebserver/src/main/java/org/apache/ranger/server/tomcat/EmbeddedServer.java <ide> valve.setEnabled(true); <ide> valve.setFileDateFormat(getConfig("ranger.accesslog.dateformat", "yyyy-MM-dd.HH")); <ide> valve.setDirectory(logDirectory.getAbsolutePath()); <del> valve.setRotatable(true); <ide> valve.setSuffix(".log"); <ide> <ide> String logPattern = getConfig("ranger.accesslog.pattern", "%h %l %u %t \"%r\" %s %b"); <ide> Subject.doAs(sub, new PrivilegedAction<Void>() { <ide> @Override <ide> public Void run() { <del> try{ <del> LOG.info("Starting Server using kerberos crendential"); <del> server.start(); <del> server.getServer().await(); <del> shutdownServer(); <del> }catch (LifecycleException e) { <del> LOG.severe("Tomcat Server failed to start:" + e.toString()); <del> e.printStackTrace(); <del> }catch (Exception e) { <del> LOG.severe("Tomcat Server failed to start:" + e.toString()); <del> e.printStackTrace(); <del> } <add> LOG.info("Starting Server using kerberos crendential"); <add> startServer(server); <ide> return null; <ide> } <ide> }); <ide> e.printStackTrace(); <ide> } <ide> }else{ <del> try{ <del> server.start(); <del> server.getServer().await(); <del> shutdownServer(); <del> } catch (LifecycleException e) { <del> LOG.severe("Tomcat Server failed to start:" + e.toString()); <del> e.printStackTrace(); <del> } catch (Exception e) { <del> LOG.severe("Tomcat Server failed to start:" + e.toString()); <del> e.printStackTrace(); <del> } <add> startServer(server); <ide> } <ide> }else{ <del> try{ <del> server.start(); <del> server.getServer().await(); <del> shutdownServer(); <del> } catch (LifecycleException e) { <del> LOG.severe("Tomcat Server failed to start:" + e.toString()); <del> e.printStackTrace(); <del> } catch (Exception e) { <del> LOG.severe("Tomcat Server failed to start:" + e.toString()); <del> e.printStackTrace(); <del> } <add> startServer(server); <add> } <add> } <add> <add> private void startServer(final Tomcat server) { <add> try{ <add> server.start(); <add> server.getServer().await(); <add> shutdownServer(); <add> } catch (LifecycleException e) { <add> LOG.severe("Tomcat Server failed to start:" + e.toString()); <add> e.printStackTrace(); <add> } catch (Exception e) { <add> LOG.severe("Tomcat Server failed to start:" + e.toString()); <add> e.printStackTrace(); <ide> } <ide> } <ide>
Java
mit
b0abf9fc11971868f5d590b987348b1804d9111e
0
MilanNz/Radix,mstojcevich/Radix
package sx.lambda.voxel.client.gui.screens; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.GlyphLayout; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.FrameBuffer; import com.badlogic.gdx.math.Rectangle; import sx.lambda.voxel.RadixClient; import sx.lambda.voxel.client.gui.GuiScreen; public class MainMenu implements GuiScreen { private static final int TARGET_BUTTON_SIZE = 150; private static final int BUTTON_SPACING = 4; private final MainMenuButton[] buttons; private boolean initialized; private SpriteBatch batch; private FrameBuffer mmPrerenderFbo; private Texture mmPrerender; private BitmapFont buttonFont; private Texture mmButtonTexture; private OrthographicCamera camera; public MainMenu() { buttons = new MainMenuButton[] { new MainMenuButton("Multiplayer (Local)", this::enterMPLocal, TARGET_BUTTON_SIZE), new MainMenuButton("Settings", () -> System.out.println("Settings pressed!"), TARGET_BUTTON_SIZE), new MainMenuButton("Quit Game", () -> RadixClient.getInstance().startShutdown(), TARGET_BUTTON_SIZE), }; } private void enterMPLocal() { System.out.println("Entering local mp"); RadixClient.getInstance().enterRemoteWorld("127.0.0.1", (short) 25565); } private void resize() { camera.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); camera.update(); if (mmPrerenderFbo != null) mmPrerenderFbo.dispose(); mmPrerenderFbo = new FrameBuffer(Pixmap.Format.RGB888, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false); mmPrerender = mmPrerenderFbo.getColorBufferTexture(); int dWidth = Gdx.graphics.getWidth(); int buttonsPerRow = dWidth / (TARGET_BUTTON_SIZE + BUTTON_SPACING); int currentButtonNum = 0; for (MainMenuButton button : buttons) { int btnX = BUTTON_SPACING + (currentButtonNum % buttonsPerRow) * (TARGET_BUTTON_SIZE + BUTTON_SPACING); int btnY = Gdx.graphics.getHeight() - (BUTTON_SPACING + ((int) (currentButtonNum / buttonsPerRow) + 1) * (TARGET_BUTTON_SIZE + BUTTON_SPACING)); button.setPosition(btnX, btnY); currentButtonNum++; } } public void init() { if (!initialized) { camera = new OrthographicCamera(); batch = new SpriteBatch(); batch.setTransformMatrix(RadixClient.getInstance().getHudCamera().combined); batch.setTransformMatrix(camera.combined); mmButtonTexture = new Texture(Gdx.files.internal("textures/gui/mmBtn.png")); buttonFont = new BitmapFont(); resize(); rerender(); initialized = true; } } protected void rerender() { mmPrerenderFbo.begin(); batch.begin(); Gdx.gl.glClearColor(0, 0, 0, 1); for (MainMenuButton button : buttons) { button.drawLabel(); button.render(); } batch.end(); mmPrerenderFbo.end(); } @Override public void render(boolean ingame, SpriteBatch guiBatch) { guiBatch.draw(mmPrerender, 0, Gdx.graphics.getHeight(), Gdx.graphics.getWidth(), -Gdx.graphics.getHeight()); } @Override public void onMouseClick(int clickType) { int mouseX = Gdx.input.getX(); int mouseY = Gdx.graphics.getHeight() - Gdx.input.getY(); if (clickType == 0) { for (MainMenuButton b : buttons) { if (b.bounds.contains(mouseX, mouseY)) { b.click(); } } } } @Override public void keyTyped(char c) { } @Override public void finish() { if (mmPrerenderFbo != null) mmPrerenderFbo.dispose(); if (batch != null) batch.dispose(); initialized = false; } class MainMenuButton { private final String title; private final Runnable onClick; private final Rectangle bounds; private GlyphLayout labelLayout; MainMenuButton(String title, Runnable onClick, int size) { this.title = title; this.onClick = onClick; this.bounds = new Rectangle(0, 0, size, size); } Rectangle getBounds() { return this.bounds; } void click() { onClick.run(); } void setSize(int size) { this.bounds.setSize(size, size); if (buttonFont != null) { rerenderLabel(); } } void setPosition(int x, int y) { this.bounds.setPosition(x, y); if (buttonFont != null) { rerenderLabel(); } } private void render() { batch.draw(mmButtonTexture, bounds.x, bounds.y, bounds.width, bounds.height); } void drawLabel() { if (buttonFont != null) { if (labelLayout == null) { labelLayout = buttonFont.draw(batch, title, -1000, -1000); } int textStartX = (int)(bounds.x + (bounds.width / 2.0f - labelLayout.width / 2.0f)); int textStartY = (int)(bounds.y + (bounds.height / 2.0f + labelLayout.height / 2.0f)); buttonFont.draw(batch, title, textStartX, textStartY); } } void rerenderLabel() { labelLayout = null; // force redraw next frame } } }
core/src/sx/lambda/voxel/client/gui/screens/MainMenu.java
package sx.lambda.voxel.client.gui.screens; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.GlyphLayout; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.FrameBuffer; import com.badlogic.gdx.math.Rectangle; import sx.lambda.voxel.RadixClient; import sx.lambda.voxel.client.gui.GuiScreen; public class MainMenu implements GuiScreen { private static final int TARGET_BUTTON_SIZE = 150; private static final int BUTTON_SPACING = 4; private final MainMenuButton[] buttons; private boolean initialized; private SpriteBatch batch; private FrameBuffer mmPrerenderFbo; private Texture mmPrerender; private BitmapFont buttonFont; private Texture mmButtonTexture; private OrthographicCamera camera; public MainMenu() { buttons = new MainMenuButton[] { new MainMenuButton("Multiplayer (Local)", this::enterMPLocal, TARGET_BUTTON_SIZE), new MainMenuButton("Multiplayer (Lambda)", this::enterMPLambda, TARGET_BUTTON_SIZE), new MainMenuButton("Settings", () -> System.out.println("Settings pressed!"), TARGET_BUTTON_SIZE), new MainMenuButton("Quit Game", () -> RadixClient.getInstance().startShutdown(), TARGET_BUTTON_SIZE), }; } private void enterMPLocal() { System.out.println("Entering local mp"); RadixClient.getInstance().enterRemoteWorld("127.0.0.1", (short) 25565); } private void enterMPLambda() { System.out.println("Entering lambda mp"); RadixClient.getInstance().enterRemoteWorld("mc.stoj.pw", (short) 31173); } private void resize() { camera.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); camera.update(); if (mmPrerenderFbo != null) mmPrerenderFbo.dispose(); mmPrerenderFbo = new FrameBuffer(Pixmap.Format.RGB888, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false); mmPrerender = mmPrerenderFbo.getColorBufferTexture(); int dWidth = Gdx.graphics.getWidth(); int buttonsPerRow = dWidth / (TARGET_BUTTON_SIZE + BUTTON_SPACING); int currentButtonNum = 0; for (MainMenuButton button : buttons) { int btnX = BUTTON_SPACING + (currentButtonNum % buttonsPerRow) * (TARGET_BUTTON_SIZE + BUTTON_SPACING); int btnY = Gdx.graphics.getHeight() - (BUTTON_SPACING + ((int) (currentButtonNum / buttonsPerRow) + 1) * (TARGET_BUTTON_SIZE + BUTTON_SPACING)); button.setPosition(btnX, btnY); currentButtonNum++; } } public void init() { if (!initialized) { camera = new OrthographicCamera(); batch = new SpriteBatch(); batch.setTransformMatrix(RadixClient.getInstance().getHudCamera().combined); batch.setTransformMatrix(camera.combined); mmButtonTexture = new Texture(Gdx.files.internal("textures/gui/mmBtn.png")); buttonFont = new BitmapFont(); resize(); rerender(); initialized = true; } } protected void rerender() { mmPrerenderFbo.begin(); batch.begin(); Gdx.gl.glClearColor(0, 0, 0, 1); for (MainMenuButton button : buttons) { button.drawLabel(); button.render(); } batch.end(); mmPrerenderFbo.end(); } @Override public void render(boolean ingame, SpriteBatch guiBatch) { guiBatch.draw(mmPrerender, 0, Gdx.graphics.getHeight(), Gdx.graphics.getWidth(), -Gdx.graphics.getHeight()); } @Override public void onMouseClick(int clickType) { int mouseX = Gdx.input.getX(); int mouseY = Gdx.graphics.getHeight() - Gdx.input.getY(); if (clickType == 0) { for (MainMenuButton b : buttons) { if (b.bounds.contains(mouseX, mouseY)) { b.click(); } } } } @Override public void keyTyped(char c) { } @Override public void finish() { if (mmPrerenderFbo != null) mmPrerenderFbo.dispose(); if (batch != null) batch.dispose(); initialized = false; } class MainMenuButton { private final String title; private final Runnable onClick; private final Rectangle bounds; private GlyphLayout labelLayout; MainMenuButton(String title, Runnable onClick, int size) { this.title = title; this.onClick = onClick; this.bounds = new Rectangle(0, 0, size, size); } Rectangle getBounds() { return this.bounds; } void click() { onClick.run(); } void setSize(int size) { this.bounds.setSize(size, size); if (buttonFont != null) { rerenderLabel(); } } void setPosition(int x, int y) { this.bounds.setPosition(x, y); if (buttonFont != null) { rerenderLabel(); } } private void render() { batch.draw(mmButtonTexture, bounds.x, bounds.y, bounds.width, bounds.height); } void drawLabel() { if (buttonFont != null) { if (labelLayout == null) { labelLayout = buttonFont.draw(batch, title, -1000, -1000); } int textStartX = (int)(bounds.x + (bounds.width / 2.0f - labelLayout.width / 2.0f)); int textStartY = (int)(bounds.y + (bounds.height / 2.0f + labelLayout.height / 2.0f)); buttonFont.draw(batch, title, textStartX, textStartY); } } void rerenderLabel() { labelLayout = null; // force redraw next frame } } }
Remove lambda multiplayer button
core/src/sx/lambda/voxel/client/gui/screens/MainMenu.java
Remove lambda multiplayer button
<ide><path>ore/src/sx/lambda/voxel/client/gui/screens/MainMenu.java <ide> public MainMenu() { <ide> buttons = new MainMenuButton[] { <ide> new MainMenuButton("Multiplayer (Local)", this::enterMPLocal, TARGET_BUTTON_SIZE), <del> new MainMenuButton("Multiplayer (Lambda)", this::enterMPLambda, TARGET_BUTTON_SIZE), <ide> new MainMenuButton("Settings", () -> System.out.println("Settings pressed!"), TARGET_BUTTON_SIZE), <ide> new MainMenuButton("Quit Game", () -> RadixClient.getInstance().startShutdown(), TARGET_BUTTON_SIZE), <ide> }; <ide> private void enterMPLocal() { <ide> System.out.println("Entering local mp"); <ide> RadixClient.getInstance().enterRemoteWorld("127.0.0.1", (short) 25565); <del> } <del> <del> private void enterMPLambda() { <del> System.out.println("Entering lambda mp"); <del> RadixClient.getInstance().enterRemoteWorld("mc.stoj.pw", (short) 31173); <ide> } <ide> <ide> private void resize() {
Java
mit
6dd71355ff9dacb9e46062172557213153683993
0
cacheflowe/haxademic,cacheflowe/haxademic,cacheflowe/haxademic,cacheflowe/haxademic,cacheflowe/haxademic,cacheflowe/haxademic
package com.haxademic.demo.hardware.webcam; import java.util.ArrayList; import com.haxademic.core.app.P; import com.haxademic.core.app.PAppletHax; import com.haxademic.core.constants.AppSettings; import com.haxademic.core.constants.PBlendModes; import com.haxademic.core.constants.PRenderers; import com.haxademic.core.draw.context.DrawUtil; import com.haxademic.core.draw.filters.pshader.BlurHFilter; import com.haxademic.core.draw.filters.pshader.BlurVFilter; import com.haxademic.core.draw.filters.pshader.SaturationFilter; import com.haxademic.core.draw.image.BufferMotionDetectionMap; import com.haxademic.core.draw.image.ImageUtil; import com.haxademic.core.draw.particle.ParticleLauncher; import com.haxademic.core.hardware.webcam.IWebCamCallback; import com.haxademic.core.math.MathUtil; import processing.core.PGraphics; import processing.core.PImage; public class Demo_WebcamGPUParticles extends PAppletHax implements IWebCamCallback { public static void main(String args[]) { PAppletHax.main(Thread.currentThread().getStackTrace()[1].getClassName()); } protected PGraphics flippedCamera; protected BufferMotionDetectionMap motionDetectionMap; protected PGraphics motionBuffer; protected PGraphics renderedParticles; protected ArrayList<ParticleLauncher> particleLaunchers; protected void overridePropsFile() { p.appConfig.setProperty(AppSettings.WIDTH, 800 ); p.appConfig.setProperty(AppSettings.HEIGHT, 600 ); p.appConfig.setProperty(AppSettings.WEBCAM_INDEX, 5 ); // 18 p.appConfig.setProperty(AppSettings.SHOW_DEBUG, true ); } public void setupFirstFrame () { // capture webcam frames p.webCamWrapper.setDelegate(this); // build final draw buffer renderedParticles = p.createGraphics(p.width, p.height, PRenderers.P3D); renderedParticles.smooth(8); p.debugView.setTexture(renderedParticles); // build multiple particles launchers particleLaunchers = new ArrayList<ParticleLauncher>(); int totalVertices = 0; for (int i = 0; i < 40; i++) { ParticleLauncher particles = new ParticleLauncher(); particleLaunchers.add(particles); totalVertices += particles.vertices(); } p.debugView.setValue("totalVertices", totalVertices); p.debugView.setTexture(particleLaunchers.get(0).progressBuffer()); } @Override public void newFrame(PImage frame) { // lazy-init flipped camera buffer if(flippedCamera == null) { int cameraW = 800; // frame.width (these are jacked up on OS X) int cameraH = 600; // frame.height flippedCamera = p.createGraphics(cameraW, cameraH, PRenderers.P2D); motionBuffer = p.createGraphics(cameraW, cameraH, PRenderers.P2D); } // copy flipped ImageUtil.copyImageFlipH(frame, flippedCamera); // lazy-init motion detection if(motionDetectionMap == null) { motionDetectionMap = new BufferMotionDetectionMap(flippedCamera, 0.05f); } ImageUtil.cropFillCopyImage(flippedCamera, motionBuffer, true); BlurHFilter.instance(P.p).setBlurByPercent(0.5f, motionBuffer.width); BlurHFilter.instance(P.p).applyTo(motionBuffer); BlurVFilter.instance(P.p).setBlurByPercent(0.5f, motionBuffer.height); BlurVFilter.instance(P.p).applyTo(motionBuffer); motionDetectionMap.setBlendLerp(0.25f); motionDetectionMap.setDiffThresh(0.025f); motionDetectionMap.setFalloffBW(0.25f); motionDetectionMap.setThresholdCutoff(0.5f); motionDetectionMap.setBlur(1f); motionDetectionMap.updateSource(motionBuffer); p.debugView.setTexture(flippedCamera); p.debugView.setTexture(motionDetectionMap.backplate()); p.debugView.setTexture(motionDetectionMap.differenceBuffer()); p.debugView.setTexture(motionDetectionMap.bwBuffer()); } public void drawApp() { // clear the screen if(motionDetectionMap == null) return; background(0); // launch particles from random places within the motion detection zones motionDetectionMap.loadPixels(); int particleLauncherIndex = p.frameCount % particleLaunchers.size(); particleLaunchers.get(particleLauncherIndex).beginLaunch(); int FRAME_LAUNCH_INTERVAL = 1; int MAX_LAUNCHED_PER_FRAME = 300; int LAUNCH_ATTEMPTS = 1500; if(p.frameCount % FRAME_LAUNCH_INTERVAL == 0) { int numLaunched = 0; for (int i = 0; i < LAUNCH_ATTEMPTS; i++) { if(numLaunched < MAX_LAUNCHED_PER_FRAME) { int checkX = MathUtil.randRange(0, motionBuffer.width); int checkY = MathUtil.randRange(0, motionBuffer.height); if(motionDetectionMap.pixelActive(checkX, checkY)) { particleLaunchers.get(particleLauncherIndex).launch(checkX, checkY); numLaunched++; } } } } particleLaunchers.get(particleLauncherIndex).endLaunch(); // update particles launcher buffers for (int i = 0; i < particleLaunchers.size(); i++) { particleLaunchers.get(i).update(); } // render! renderedParticles.beginDraw(); DrawUtil.setDrawFlat2d(renderedParticles, true); renderedParticles.background(0); renderedParticles.fill(255); renderedParticles.blendMode(PBlendModes.ADD); for (int i = 0; i < particleLaunchers.size(); i++) { particleLaunchers.get(i).renderTo(renderedParticles); } renderedParticles.endDraw(); // draw buffer to screen renderedParticles.blendMode(PBlendModes.BLEND); DrawUtil.setPImageAlpha(p, 0.9f); p.image(flippedCamera, 0, 0); DrawUtil.setPImageAlpha(p, 0.1f); p.image(motionDetectionMap.bwBuffer(), 0, 0, flippedCamera.width, flippedCamera.height); DrawUtil.setPImageAlpha(p, 1f); renderedParticles.blendMode(PBlendModes.ADD); p.image(renderedParticles, 0, 0); // desaturate // SaturationFilter.instance(p).setSaturation(0); // SaturationFilter.instance(p).applyTo(p); } }
src/com/haxademic/demo/hardware/webcam/Demo_WebcamGPUParticles.java
package com.haxademic.demo.hardware.webcam; import java.util.ArrayList; import com.haxademic.core.app.P; import com.haxademic.core.app.PAppletHax; import com.haxademic.core.constants.AppSettings; import com.haxademic.core.constants.PBlendModes; import com.haxademic.core.constants.PRenderers; import com.haxademic.core.draw.context.DrawUtil; import com.haxademic.core.draw.filters.pshader.BlurHFilter; import com.haxademic.core.draw.filters.pshader.BlurVFilter; import com.haxademic.core.draw.filters.pshader.SaturationFilter; import com.haxademic.core.draw.image.BufferMotionDetectionMap; import com.haxademic.core.draw.image.ImageUtil; import com.haxademic.core.draw.particle.ParticleLauncher; import com.haxademic.core.hardware.webcam.IWebCamCallback; import com.haxademic.core.math.MathUtil; import processing.core.PGraphics; import processing.core.PImage; public class Demo_WebcamGPUParticles extends PAppletHax implements IWebCamCallback { public static void main(String args[]) { PAppletHax.main(Thread.currentThread().getStackTrace()[1].getClassName()); } protected PGraphics flippedCamera; protected BufferMotionDetectionMap motionDetectionMap; protected PGraphics motionBuffer; protected PGraphics renderedParticles; protected ArrayList<ParticleLauncher> particleLaunchers; protected void overridePropsFile() { p.appConfig.setProperty(AppSettings.WIDTH, 1600 ); p.appConfig.setProperty(AppSettings.HEIGHT, 600 ); p.appConfig.setProperty(AppSettings.WEBCAM_INDEX, 5 ); // 18 p.appConfig.setProperty(AppSettings.SHOW_DEBUG, true ); } public void setupFirstFrame () { // capture webcam frames p.webCamWrapper.setDelegate(this); // build final draw buffer renderedParticles = p.createGraphics(800, 600, PRenderers.P3D); renderedParticles.smooth(8); p.debugView.setTexture(renderedParticles); // build multiple particles launchers particleLaunchers = new ArrayList<ParticleLauncher>(); int totalVertices = 0; for (int i = 0; i < 40; i++) { ParticleLauncher particles = new ParticleLauncher(); particleLaunchers.add(particles); totalVertices += particles.vertices(); } p.debugView.setValue("totalVertices", totalVertices); p.debugView.setTexture(particleLaunchers.get(0).progressBuffer()); } @Override public void newFrame(PImage frame) { // lazy-init flipped camera buffer if(flippedCamera == null) { int cameraW = 800; // frame.width (these are jacked up on OS X) int cameraH = 600; // frame.height flippedCamera = p.createGraphics(cameraW, cameraH, PRenderers.P2D); motionBuffer = p.createGraphics(cameraW, cameraH, PRenderers.P2D); } // copy flipped flippedCamera.copy(frame, 0, 0, frame.width, frame.height, flippedCamera.width, 0, -flippedCamera.width, flippedCamera.height); // lazy-init motion detection to pass Kinect into if(motionDetectionMap == null) { motionDetectionMap = new BufferMotionDetectionMap(flippedCamera, 0.05f); } ImageUtil.cropFillCopyImage(flippedCamera, motionBuffer, true); BlurHFilter.instance(P.p).setBlurByPercent(0.5f, motionBuffer.width); BlurHFilter.instance(P.p).applyTo(motionBuffer); BlurVFilter.instance(P.p).setBlurByPercent(0.5f, motionBuffer.height); BlurVFilter.instance(P.p).applyTo(motionBuffer); motionDetectionMap.setBlendLerp(0.25f); motionDetectionMap.setDiffThresh(0.025f); motionDetectionMap.setFalloffBW(0.25f); motionDetectionMap.setThresholdCutoff(0.5f); motionDetectionMap.setBlur(1f); motionDetectionMap.updateSource(motionBuffer); p.debugView.setTexture(flippedCamera); p.debugView.setTexture(motionDetectionMap.backplate()); p.debugView.setTexture(motionDetectionMap.differenceBuffer()); p.debugView.setTexture(motionDetectionMap.bwBuffer()); } public void drawApp() { // clear the screen background(0); if(motionDetectionMap == null) return; // launch! motionDetectionMap.loadPixels(); int particleLauncherIndex = p.frameCount % particleLaunchers.size(); particleLaunchers.get(particleLauncherIndex).beginLaunch(); int FRAME_LAUNCH_INTERVAL = 1; int MAX_LAUNCHED_PER_FRAME = 300; int LAUNCH_ATTEMPTS = 1500; if(p.frameCount % FRAME_LAUNCH_INTERVAL == 0) { int numLaunched = 0; for (int i = 0; i < LAUNCH_ATTEMPTS; i++) { if(numLaunched < MAX_LAUNCHED_PER_FRAME) { int checkX = MathUtil.randRange(0, motionBuffer.width); int checkY = MathUtil.randRange(0, motionBuffer.height); if(motionDetectionMap.pixelActive(checkX, checkY)) { particleLaunchers.get(particleLauncherIndex).launch(checkX, checkY); numLaunched++; } } } } particleLaunchers.get(particleLauncherIndex).endLaunch(); // update particles launcher buffers for (int i = 0; i < particleLaunchers.size(); i++) { particleLaunchers.get(i).update(); } // render! renderedParticles.beginDraw(); DrawUtil.setDrawFlat2d(renderedParticles, true); renderedParticles.background(0); renderedParticles.fill(255); renderedParticles.blendMode(PBlendModes.ADD); for (int i = 0; i < particleLaunchers.size(); i++) { particleLaunchers.get(i).renderTo(renderedParticles); } renderedParticles.endDraw(); // draw buffer to screen renderedParticles.blendMode(PBlendModes.BLEND); DrawUtil.setPImageAlpha(p, 0.9f); p.image(flippedCamera, 0, 0); DrawUtil.setPImageAlpha(p, 0.4f); p.image(motionDetectionMap.bwBuffer(), flippedCamera.width, 0, flippedCamera.width, flippedCamera.height); DrawUtil.setPImageAlpha(p, 1f); renderedParticles.blendMode(PBlendModes.ADD); p.image(renderedParticles, flippedCamera.width, 0); // desaturate SaturationFilter.instance(p).setSaturation(0); SaturationFilter.instance(p).applyTo(p); } public void keyPressed() { super.keyPressed(); } }
Cleanup webcam GPU particles demo
src/com/haxademic/demo/hardware/webcam/Demo_WebcamGPUParticles.java
Cleanup webcam GPU particles demo
<ide><path>rc/com/haxademic/demo/hardware/webcam/Demo_WebcamGPUParticles.java <ide> protected ArrayList<ParticleLauncher> particleLaunchers; <ide> <ide> protected void overridePropsFile() { <del> p.appConfig.setProperty(AppSettings.WIDTH, 1600 ); <add> p.appConfig.setProperty(AppSettings.WIDTH, 800 ); <ide> p.appConfig.setProperty(AppSettings.HEIGHT, 600 ); <ide> p.appConfig.setProperty(AppSettings.WEBCAM_INDEX, 5 ); // 18 <ide> p.appConfig.setProperty(AppSettings.SHOW_DEBUG, true ); <ide> p.webCamWrapper.setDelegate(this); <ide> <ide> // build final draw buffer <del> renderedParticles = p.createGraphics(800, 600, PRenderers.P3D); <add> renderedParticles = p.createGraphics(p.width, p.height, PRenderers.P3D); <ide> renderedParticles.smooth(8); <ide> p.debugView.setTexture(renderedParticles); <ide> <ide> motionBuffer = p.createGraphics(cameraW, cameraH, PRenderers.P2D); <ide> } <ide> // copy flipped <del> flippedCamera.copy(frame, 0, 0, frame.width, frame.height, flippedCamera.width, 0, -flippedCamera.width, flippedCamera.height); <add> ImageUtil.copyImageFlipH(frame, flippedCamera); <ide> <del> // lazy-init motion detection to pass Kinect into <add> // lazy-init motion detection <ide> if(motionDetectionMap == null) { <ide> motionDetectionMap = new BufferMotionDetectionMap(flippedCamera, 0.05f); <ide> } <ide> <ide> public void drawApp() { <ide> // clear the screen <add> if(motionDetectionMap == null) return; <ide> background(0); <ide> <del> if(motionDetectionMap == null) return; <del> <del> // launch! <add> // launch particles from random places within the motion detection zones <ide> motionDetectionMap.loadPixels(); <ide> <ide> int particleLauncherIndex = p.frameCount % particleLaunchers.size(); <ide> <ide> particleLaunchers.get(particleLauncherIndex).endLaunch(); <ide> <del> <ide> // update particles launcher buffers <ide> for (int i = 0; i < particleLaunchers.size(); i++) { <ide> particleLaunchers.get(i).update(); <ide> renderedParticles.blendMode(PBlendModes.BLEND); <ide> DrawUtil.setPImageAlpha(p, 0.9f); <ide> p.image(flippedCamera, 0, 0); <del> DrawUtil.setPImageAlpha(p, 0.4f); <del> p.image(motionDetectionMap.bwBuffer(), flippedCamera.width, 0, flippedCamera.width, flippedCamera.height); <add> DrawUtil.setPImageAlpha(p, 0.1f); <add> p.image(motionDetectionMap.bwBuffer(), 0, 0, flippedCamera.width, flippedCamera.height); <ide> DrawUtil.setPImageAlpha(p, 1f); <ide> renderedParticles.blendMode(PBlendModes.ADD); <del> p.image(renderedParticles, flippedCamera.width, 0); <add> p.image(renderedParticles, 0, 0); <ide> <ide> // desaturate <del> SaturationFilter.instance(p).setSaturation(0); <del> SaturationFilter.instance(p).applyTo(p); <del> } <del> <del> public void keyPressed() { <del> super.keyPressed(); <add>// SaturationFilter.instance(p).setSaturation(0); <add>// SaturationFilter.instance(p).applyTo(p); <ide> } <ide> <ide> }
Java
apache-2.0
65daf8dfc9b05cd1243ae3da26d37372abfb3827
0
nla/tinycdxserver,nla/outbackcdx,nla/outbackcdx,nla/outbackcdx,nla/tinycdxserver,nla/tinycdxserver,nla/tinycdxserver,nla/outbackcdx
package outbackcdx; import org.rocksdb.*; import org.rocksdb.Options; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.util.*; import java.util.Comparator; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import static java.nio.charset.StandardCharsets.UTF_8; public class DataStore implements Closeable { public static final String COLLECTION_PATTERN = "[A-Za-z0-9_-]+"; private final File dataDir; private final Map<String, Index> indexes = new ConcurrentHashMap<String, Index>(); public long replicationWindow; public DataStore(File dataDir, long replicationWindow) { this.dataDir = dataDir; this.replicationWindow = replicationWindow; } public Index getIndex(String collection) throws IOException { return getIndex(collection, false); } public Index getIndex(String collection, boolean createAllowed) throws IOException { Index index = indexes.get(collection); if (index != null) { return index; } return openDb(collection, createAllowed); } private synchronized Index openDb(String collection, boolean createAllowed) throws IOException { if (!isValidCollectionName(collection)) { throw new IllegalArgumentException("Invalid collection name"); } Index index = indexes.get(collection); if (index != null) { return index; } File path = new File(dataDir, collection); if (!createAllowed && !path.isDirectory()) { return null; } try { Options options = new Options(); options.setCreateIfMissing(createAllowed); configureColumnFamily(options); DBOptions dbOptions = new DBOptions(); dbOptions.setCreateIfMissing(createAllowed); dbOptions.setMaxBackgroundCompactions(Math.min(8, Runtime.getRuntime().availableProcessors())); dbOptions.setAvoidFlushDuringRecovery(true); dbOptions.setWalSizeLimitMB(Long.MAX_VALUE); dbOptions.setMaxTotalWalSize(Long.MAX_VALUE); if(replicationWindow <= 0) { dbOptions.setManualWalFlush(true); dbOptions.setWalTtlSeconds(Long.MAX_VALUE); } else { dbOptions.setManualWalFlush(false); dbOptions.setWalTtlSeconds(replicationWindow); } ColumnFamilyOptions cfOptions = new ColumnFamilyOptions(); configureColumnFamily(cfOptions); List<ColumnFamilyDescriptor> cfDescriptors; if (FeatureFlags.experimentalAccessControl()) { cfDescriptors = Arrays.asList( new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY, cfOptions), new ColumnFamilyDescriptor("alias".getBytes(UTF_8), cfOptions), new ColumnFamilyDescriptor("access-rule".getBytes(UTF_8), cfOptions), new ColumnFamilyDescriptor("access-policy".getBytes(UTF_8), cfOptions) ); } else { cfDescriptors = Arrays.asList( new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY, cfOptions), new ColumnFamilyDescriptor("alias".getBytes(UTF_8), cfOptions)); } createColumnFamiliesIfNotExists(options, dbOptions, path.toString(), cfDescriptors); List<ColumnFamilyHandle> cfHandles = new ArrayList<>(cfDescriptors.size()); RocksDB db = RocksDB.open(dbOptions, path.toString(), cfDescriptors, cfHandles); AccessControl accessControl = null; if (FeatureFlags.experimentalAccessControl()) { accessControl = new AccessControl(db, cfHandles.get(2), cfHandles.get(3)); } index = new Index(collection, db, cfHandles.get(0), cfHandles.get(1), accessControl); indexes.put(collection, index); return index; } catch (RocksDBException e) { throw new IOException(e); } } private void configureColumnFamily(Options cfOptions) throws RocksDBException { BlockBasedTableConfig tableConfig = new BlockBasedTableConfig(); tableConfig.setBlockSize(22 * 1024); // approximately compresses to < 8 kB cfOptions.setCompactionStyle(CompactionStyle.LEVEL); cfOptions.setWriteBufferSize(64 * 1024 * 1024); cfOptions.setTargetFileSizeBase(64 * 1024 * 1024); cfOptions.setMaxBytesForLevelBase(512 * 1024 * 1024); cfOptions.setTargetFileSizeMultiplier(2); cfOptions.setCompressionType(CompressionType.SNAPPY_COMPRESSION); cfOptions.setTableFormatConfig(tableConfig); } private void configureColumnFamily(ColumnFamilyOptions cfOptions) throws RocksDBException { BlockBasedTableConfig tableConfig = new BlockBasedTableConfig(); tableConfig.setBlockSize(22 * 1024); // approximately compresses to < 8 kB cfOptions.setCompactionStyle(CompactionStyle.LEVEL); cfOptions.setWriteBufferSize(64 * 1024 * 1024); cfOptions.setTargetFileSizeBase(64 * 1024 * 1024); cfOptions.setMaxBytesForLevelBase(512 * 1024 * 1024); cfOptions.setTargetFileSizeMultiplier(2); cfOptions.setCompressionType(CompressionType.SNAPPY_COMPRESSION); cfOptions.setTableFormatConfig(tableConfig); } private void createColumnFamiliesIfNotExists(Options options, DBOptions dbOptions, String path, List<ColumnFamilyDescriptor> cfDescriptors) throws RocksDBException { List<ColumnFamilyDescriptor> existing = new ArrayList<>(); List<ColumnFamilyDescriptor> toCreate = new ArrayList<>(); Set<String> cfNames = RocksDB.listColumnFamilies(options, path) .stream().map(bytes -> new String(bytes, UTF_8)) .collect(Collectors.toSet()); for (ColumnFamilyDescriptor cfDesc : cfDescriptors) { if (cfNames.remove(new String(cfDesc.columnFamilyName(), UTF_8))) { existing.add(cfDesc); } else { toCreate.add(cfDesc); } } if (!cfNames.isEmpty()) { throw new RuntimeException("database may be too new: unexpected column family: " + cfNames.iterator().next()); } // default CF is created automatically in empty db, exclude it if (existing.isEmpty()) { ColumnFamilyDescriptor defaultCf = cfDescriptors.get(0); existing.add(defaultCf); toCreate.remove(defaultCf); } List<ColumnFamilyHandle> handles = new ArrayList<>(existing.size()); try (RocksDB db = RocksDB.open(dbOptions, path, existing, handles);) { for (ColumnFamilyDescriptor descriptor : toCreate) { try (ColumnFamilyHandle cf = db.createColumnFamily(descriptor)) { } } } } private static boolean isValidCollectionName(String collection) { return collection.matches("^" + COLLECTION_PATTERN + "$"); } public synchronized void close() { for (Index index : indexes.values()) { index.db.close(); } indexes.clear(); } public List<String> listCollections() { List<String> collections = new ArrayList<String>(); for (File f : dataDir.listFiles()) { if (f.isDirectory() && isValidCollectionName(f.getName())) { collections.add(f.getName()); } } collections.sort(Comparator.naturalOrder()); return collections; } }
src/outbackcdx/DataStore.java
package outbackcdx; import org.rocksdb.*; import org.rocksdb.Options; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.util.*; import java.util.Comparator; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import static java.nio.charset.StandardCharsets.UTF_8; public class DataStore implements Closeable { public static final String COLLECTION_PATTERN = "[A-Za-z0-9_-]+"; private final File dataDir; private final Map<String, Index> indexes = new ConcurrentHashMap<String, Index>(); public long replicationWindow; public DataStore(File dataDir, long replicationWindow) { this.dataDir = dataDir; this.replicationWindow = replicationWindow; } public Index getIndex(String collection) throws IOException { return getIndex(collection, false); } public Index getIndex(String collection, boolean createAllowed) throws IOException { Index index = indexes.get(collection); if (index != null) { return index; } return openDb(collection, createAllowed); } private synchronized Index openDb(String collection, boolean createAllowed) throws IOException { if (!isValidCollectionName(collection)) { throw new IllegalArgumentException("Invalid collection name"); } Index index = indexes.get(collection); if (index != null) { return index; } File path = new File(dataDir, collection); if (!createAllowed && !path.isDirectory()) { return null; } try { Options options = new Options(); options.setCreateIfMissing(createAllowed); configureColumnFamily(options); DBOptions dbOptions = new DBOptions(); dbOptions.setCreateIfMissing(createAllowed); dbOptions.setMaxBackgroundCompactions(Math.min(8, Runtime.getRuntime().availableProcessors())); dbOptions.setAvoidFlushDuringRecovery(true); if(replicationWindow == 0) { dbOptions.setManualWalFlush(true); } else { dbOptions.setManualWalFlush(false); dbOptions.setWalTtlSeconds(replicationWindow); } ColumnFamilyOptions cfOptions = new ColumnFamilyOptions(); configureColumnFamily(cfOptions); List<ColumnFamilyDescriptor> cfDescriptors; if (FeatureFlags.experimentalAccessControl()) { cfDescriptors = Arrays.asList( new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY, cfOptions), new ColumnFamilyDescriptor("alias".getBytes(UTF_8), cfOptions), new ColumnFamilyDescriptor("access-rule".getBytes(UTF_8), cfOptions), new ColumnFamilyDescriptor("access-policy".getBytes(UTF_8), cfOptions) ); } else { cfDescriptors = Arrays.asList( new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY, cfOptions), new ColumnFamilyDescriptor("alias".getBytes(UTF_8), cfOptions)); } createColumnFamiliesIfNotExists(options, dbOptions, path.toString(), cfDescriptors); List<ColumnFamilyHandle> cfHandles = new ArrayList<>(cfDescriptors.size()); RocksDB db = RocksDB.open(dbOptions, path.toString(), cfDescriptors, cfHandles); AccessControl accessControl = null; if (FeatureFlags.experimentalAccessControl()) { accessControl = new AccessControl(db, cfHandles.get(2), cfHandles.get(3)); } index = new Index(collection, db, cfHandles.get(0), cfHandles.get(1), accessControl); indexes.put(collection, index); return index; } catch (RocksDBException e) { throw new IOException(e); } } private void configureColumnFamily(Options cfOptions) throws RocksDBException { BlockBasedTableConfig tableConfig = new BlockBasedTableConfig(); tableConfig.setBlockSize(22 * 1024); // approximately compresses to < 8 kB cfOptions.setCompactionStyle(CompactionStyle.LEVEL); cfOptions.setWriteBufferSize(64 * 1024 * 1024); cfOptions.setTargetFileSizeBase(64 * 1024 * 1024); cfOptions.setMaxBytesForLevelBase(512 * 1024 * 1024); cfOptions.setTargetFileSizeMultiplier(2); cfOptions.setCompressionType(CompressionType.SNAPPY_COMPRESSION); cfOptions.setTableFormatConfig(tableConfig); } private void configureColumnFamily(ColumnFamilyOptions cfOptions) throws RocksDBException { BlockBasedTableConfig tableConfig = new BlockBasedTableConfig(); tableConfig.setBlockSize(22 * 1024); // approximately compresses to < 8 kB cfOptions.setCompactionStyle(CompactionStyle.LEVEL); cfOptions.setWriteBufferSize(64 * 1024 * 1024); cfOptions.setTargetFileSizeBase(64 * 1024 * 1024); cfOptions.setMaxBytesForLevelBase(512 * 1024 * 1024); cfOptions.setTargetFileSizeMultiplier(2); cfOptions.setCompressionType(CompressionType.SNAPPY_COMPRESSION); cfOptions.setTableFormatConfig(tableConfig); } private void createColumnFamiliesIfNotExists(Options options, DBOptions dbOptions, String path, List<ColumnFamilyDescriptor> cfDescriptors) throws RocksDBException { List<ColumnFamilyDescriptor> existing = new ArrayList<>(); List<ColumnFamilyDescriptor> toCreate = new ArrayList<>(); Set<String> cfNames = RocksDB.listColumnFamilies(options, path) .stream().map(bytes -> new String(bytes, UTF_8)) .collect(Collectors.toSet()); for (ColumnFamilyDescriptor cfDesc : cfDescriptors) { if (cfNames.remove(new String(cfDesc.columnFamilyName(), UTF_8))) { existing.add(cfDesc); } else { toCreate.add(cfDesc); } } if (!cfNames.isEmpty()) { throw new RuntimeException("database may be too new: unexpected column family: " + cfNames.iterator().next()); } // default CF is created automatically in empty db, exclude it if (existing.isEmpty()) { ColumnFamilyDescriptor defaultCf = cfDescriptors.get(0); existing.add(defaultCf); toCreate.remove(defaultCf); } List<ColumnFamilyHandle> handles = new ArrayList<>(existing.size()); try (RocksDB db = RocksDB.open(dbOptions, path, existing, handles);) { for (ColumnFamilyDescriptor descriptor : toCreate) { try (ColumnFamilyHandle cf = db.createColumnFamily(descriptor)) { } } } } private static boolean isValidCollectionName(String collection) { return collection.matches("^" + COLLECTION_PATTERN + "$"); } public synchronized void close() { for (Index index : indexes.values()) { index.db.close(); } indexes.clear(); } public List<String> listCollections() { List<String> collections = new ArrayList<String>(); for (File f : dataDir.listFiles()) { if (f.isDirectory() && isValidCollectionName(f.getName())) { collections.add(f.getName()); } } collections.sort(Comparator.naturalOrder()); return collections; } }
replication window <= 0 :: really don't flush wal
src/outbackcdx/DataStore.java
replication window <= 0 :: really don't flush wal
<ide><path>rc/outbackcdx/DataStore.java <ide> dbOptions.setCreateIfMissing(createAllowed); <ide> dbOptions.setMaxBackgroundCompactions(Math.min(8, Runtime.getRuntime().availableProcessors())); <ide> dbOptions.setAvoidFlushDuringRecovery(true); <del> if(replicationWindow == 0) { <add> dbOptions.setWalSizeLimitMB(Long.MAX_VALUE); <add> dbOptions.setMaxTotalWalSize(Long.MAX_VALUE); <add> if(replicationWindow <= 0) { <ide> dbOptions.setManualWalFlush(true); <add> dbOptions.setWalTtlSeconds(Long.MAX_VALUE); <ide> } else { <ide> dbOptions.setManualWalFlush(false); <ide> dbOptions.setWalTtlSeconds(replicationWindow);
Java
mit
839961fa36a7d1f6128b6ca6998364cbfcb9a3d4
0
zxy198717/QMBForm
package com.quemb.qmbform.view; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Resources; import android.support.annotation.LayoutRes; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.Toast; import com.quemb.qmbform.R; import com.quemb.qmbform.descriptor.FormItemDescriptor; import com.quemb.qmbform.descriptor.SectionDescriptor; /** * Created by tonimoeckel on 14.07.14. */ public abstract class Cell extends LinearLayout { private FormItemDescriptor mFormItemDescriptor; private View mDividerView; private boolean mWaitingActivityResult; BroadcastReceiver NewWaitingBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String tag = intent.getStringExtra("row_tag"); if (mFormItemDescriptor.getTag() !=null &&!mFormItemDescriptor.getTag().equals(tag)) { setWaitingActivityResult(false); } } }; public Cell(Context context, FormItemDescriptor formItemDescriptor) { super(context); setFormItemDescriptor(formItemDescriptor); init(); update(); afterInit(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("new_waiting_activity_result"); getContext().registerReceiver(NewWaitingBroadcastReceiver, intentFilter); } protected void afterInit() { } protected void init() { setOrientation(LinearLayout.VERTICAL); setGravity(Gravity.CENTER); @LayoutRes int resource = mFormItemDescriptor.getResourceId() > 0 ? mFormItemDescriptor.getResourceId() : getResource(); if (resource > 0) { View v = inflate(getContext(), resource, getSuperViewForLayoutInflation()); if(null != v.getBackground()) { setBackgroundDrawable(v.getBackground()); } } if (shouldAddDivider()) { addView(getDividerView()); } } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); getContext().unregisterReceiver(NewWaitingBroadcastReceiver); } protected ViewGroup getSuperViewForLayoutInflation() { return this; } protected abstract int getResource(); protected abstract void update(); public FormItemDescriptor getFormItemDescriptor() { return mFormItemDescriptor; } public void setFormItemDescriptor(FormItemDescriptor formItemDescriptor) { mFormItemDescriptor = formItemDescriptor; mFormItemDescriptor.setCell(this); } public void onCellSelected() { } protected View getDividerView() { if (mDividerView == null) { mDividerView = new View(getContext()); configDivider(mDividerView); } return mDividerView; } private void configDivider(View dividerView) { LinearLayout.LayoutParams params = new LayoutParams( LayoutParams.MATCH_PARENT, 1 ); if ( !(getFormItemDescriptor() instanceof SectionDescriptor) && !(this instanceof SeperatorSectionCell) && !getFormItemDescriptor().isLastInSection()) { params.setMargins(getResources().getDimensionPixelSize(R.dimen.cell_padding), 0, 0, 0); } dividerView.setLayoutParams(params); dividerView.setBackgroundColor(getThemeValue(android.R.attr.listDivider)); } protected int getThemeValue(int resource) { TypedValue typedValue = new TypedValue(); Resources.Theme theme = getContext().getTheme(); theme.resolveAttribute(resource, typedValue, true); return typedValue.data; } public boolean shouldAddDivider() { return true; } public void lastInSection() { } protected void setDividerView(View dividerView) { mDividerView = dividerView; } protected void startActivityForResult(Intent intent, int requestCode) { setWaitingActivityResult(true); if (mFormItemDescriptor.getFragment() != null) { mFormItemDescriptor.getFragment().startActivityForResult(intent, requestCode); } else { if (getContext() instanceof Activity) { ((Activity)getContext()).startActivityForResult(intent, requestCode); } } } protected void setWaitingActivityResult(boolean mWaitingActivityResult) { this.mWaitingActivityResult = mWaitingActivityResult; if (mWaitingActivityResult) { Intent intent = new Intent("new_waiting_activity_result"); intent.putExtra("row_tag", mFormItemDescriptor.getTag()); getContext().sendBroadcast(intent); } } public boolean isWaitingActivityResult() { return mWaitingActivityResult; } public void onActivityResult(int requestCode, int resultCode, Intent data){ if(mWaitingActivityResult) { activityResult(requestCode, resultCode, data); } } protected void activityResult(int requestCode, int resultCode, Intent data){ } protected void showToast(final String message) { post(new Runnable() { @Override public void run() { Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show(); } }); } }
lib/QMBForm/src/main/java/com/quemb/qmbform/view/Cell.java
package com.quemb.qmbform.view; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Resources; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.Toast; import com.quemb.qmbform.R; import com.quemb.qmbform.descriptor.FormItemDescriptor; import com.quemb.qmbform.descriptor.SectionDescriptor; /** * Created by tonimoeckel on 14.07.14. */ public abstract class Cell extends LinearLayout { private FormItemDescriptor mFormItemDescriptor; private View mDividerView; private boolean mWaitingActivityResult; BroadcastReceiver NewWaitingBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String tag = intent.getStringExtra("row_tag"); if (mFormItemDescriptor.getTag() !=null &&!mFormItemDescriptor.getTag().equals(tag)) { setWaitingActivityResult(false); } } }; public Cell(Context context, FormItemDescriptor formItemDescriptor) { super(context); setFormItemDescriptor(formItemDescriptor); init(); update(); afterInit(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("new_waiting_activity_result"); getContext().registerReceiver(NewWaitingBroadcastReceiver, intentFilter); } protected void afterInit() { } protected void init() { setOrientation(LinearLayout.VERTICAL); setGravity(Gravity.CENTER); int resource = mFormItemDescriptor.getResourceId() > 0 ? mFormItemDescriptor.getResourceId() : getResource(); if (resource > 0) { inflate(getContext(), resource, getSuperViewForLayoutInflation()); } if (shouldAddDivider()) { addView(getDividerView()); } } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); getContext().unregisterReceiver(NewWaitingBroadcastReceiver); } protected ViewGroup getSuperViewForLayoutInflation() { return this; } protected abstract int getResource(); protected abstract void update(); public FormItemDescriptor getFormItemDescriptor() { return mFormItemDescriptor; } public void setFormItemDescriptor(FormItemDescriptor formItemDescriptor) { mFormItemDescriptor = formItemDescriptor; mFormItemDescriptor.setCell(this); } public void onCellSelected() { } protected View getDividerView() { if (mDividerView == null) { mDividerView = new View(getContext()); configDivider(mDividerView); } return mDividerView; } private void configDivider(View dividerView) { LinearLayout.LayoutParams params = new LayoutParams( LayoutParams.MATCH_PARENT, 1 ); if ( !(getFormItemDescriptor() instanceof SectionDescriptor) && !(this instanceof SeperatorSectionCell) && !getFormItemDescriptor().isLastInSection()) { params.setMargins(getResources().getDimensionPixelSize(R.dimen.cell_padding), 0, 0, 0); } dividerView.setLayoutParams(params); dividerView.setBackgroundColor(getThemeValue(android.R.attr.listDivider)); } protected int getThemeValue(int resource) { TypedValue typedValue = new TypedValue(); Resources.Theme theme = getContext().getTheme(); theme.resolveAttribute(resource, typedValue, true); return typedValue.data; } public boolean shouldAddDivider() { return true; } public void lastInSection() { } protected void setDividerView(View dividerView) { mDividerView = dividerView; } protected void startActivityForResult(Intent intent, int requestCode) { setWaitingActivityResult(true); if (mFormItemDescriptor.getFragment() != null) { mFormItemDescriptor.getFragment().startActivityForResult(intent, requestCode); } else { if (getContext() instanceof Activity) { ((Activity)getContext()).startActivityForResult(intent, requestCode); } } } protected void setWaitingActivityResult(boolean mWaitingActivityResult) { this.mWaitingActivityResult = mWaitingActivityResult; if (mWaitingActivityResult) { Intent intent = new Intent("new_waiting_activity_result"); intent.putExtra("row_tag", mFormItemDescriptor.getTag()); getContext().sendBroadcast(intent); } } public boolean isWaitingActivityResult() { return mWaitingActivityResult; } public void onActivityResult(int requestCode, int resultCode, Intent data){ if(mWaitingActivityResult) { activityResult(requestCode, resultCode, data); } } protected void activityResult(int requestCode, int resultCode, Intent data){ } protected void showToast(final String message) { post(new Runnable() { @Override public void run() { Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show(); } }); } }
backgroud refine
lib/QMBForm/src/main/java/com/quemb/qmbform/view/Cell.java
backgroud refine
<ide><path>ib/QMBForm/src/main/java/com/quemb/qmbform/view/Cell.java <ide> import android.content.Intent; <ide> import android.content.IntentFilter; <ide> import android.content.res.Resources; <add>import android.support.annotation.LayoutRes; <ide> import android.util.TypedValue; <ide> import android.view.Gravity; <ide> import android.view.View; <ide> setOrientation(LinearLayout.VERTICAL); <ide> setGravity(Gravity.CENTER); <ide> <del> int resource = mFormItemDescriptor.getResourceId() > 0 ? mFormItemDescriptor.getResourceId() : getResource(); <add> @LayoutRes int resource = mFormItemDescriptor.getResourceId() > 0 ? mFormItemDescriptor.getResourceId() : getResource(); <ide> if (resource > 0) { <del> inflate(getContext(), resource, getSuperViewForLayoutInflation()); <add> View v = inflate(getContext(), resource, getSuperViewForLayoutInflation()); <add> if(null != v.getBackground()) { <add> setBackgroundDrawable(v.getBackground()); <add> } <ide> } <ide> <ide> if (shouldAddDivider()) {
Java
apache-2.0
error: pathspec 'annis-gui/src/main/java/annis/gui/flatquerybuilder/ValueField.java' did not match any file(s) known to git
6523d699e6440fff6ff2acc2dbd1f7ff1f55a18c
1
amir-zeldes/ANNIS,zangsir/ANNIS,korpling/ANNIS,pixeldrama/ANNIS,amir-zeldes/ANNIS,korpling/ANNIS,korpling/ANNIS,zangsir/ANNIS,zangsir/ANNIS,amir-zeldes/ANNIS,zangsir/ANNIS,amir-zeldes/ANNIS,pixeldrama/ANNIS,korpling/ANNIS,zangsir/ANNIS,pixeldrama/ANNIS,zangsir/ANNIS,pixeldrama/ANNIS,pixeldrama/ANNIS,korpling/ANNIS,amir-zeldes/ANNIS,amir-zeldes/ANNIS,pixeldrama/ANNIS
/* * Copyright 2013 Corpuslinguistic working group Humboldt University Berlin. * * 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 annis.gui.flatquerybuilder; import com.vaadin.data.Property.ValueChangeEvent; import com.vaadin.data.Property.ValueChangeListener; import com.vaadin.event.FieldEvents.TextChangeEvent; import com.vaadin.event.FieldEvents.TextChangeListener; import com.vaadin.shared.ui.combobox.FilteringMode; import com.vaadin.ui.AbstractSelect; import com.vaadin.ui.AbstractSelect.ItemCaptionMode; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Panel; import com.vaadin.ui.themes.ChameleonTheme; import java.text.Normalizer; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.ConcurrentSkipListSet; import org.apache.commons.lang3.StringUtils; /** * * @author Martin */ public class ValueField extends Panel implements TextChangeListener, Button.ClickListener { /*BASIC ELEMENTS*/ private HorizontalLayout frame; private SensitiveComboBox scb; private Button bt; /*ADDITIONAL ATTRIBUTES*/ private FlatQueryBuilder sq; private String level; private SearchBox sb; private ConcurrentSkipListMap<String, String> values; private ValueMode vm; /*LABELS AND STRINGS*/ private static final String BUTTON_LABEL_REMOVE = "X"; private static final String SCB_STYLE_NAME = "corpus-font-force"; private static final String SCB_WIDTH = "130px"; public ValueField(FlatQueryBuilder sq, SearchBox sb, String level) { /*INIT VALUES*/ this.sq = sq; this.sb = sb; this.level = level; vm = (sb.isRegEx()) ? ValueMode.REGEX : ValueMode.NORMAL; values = new ConcurrentSkipListMap<String, String>(); for(String v : sq.getAvailableAnnotationLevels(level)) { values.put(v, sq.escapeRegexCharacters(v)); } /*SENSITIVE COMBOBOX*/ scb = new SensitiveComboBox(); scb.setImmediate(true); scb.setNewItemsAllowed(true); scb.setTextInputAllowed(true); scb.setFilteringMode(FilteringMode.OFF); scb.addListener((TextChangeListener)this); scb.setItemCaptionMode(ItemCaptionMode.ID); buildValues(vm); scb.addStyleName(SCB_STYLE_NAME); scb.setWidth(SCB_WIDTH); /*BUTTON*/ bt = new Button(BUTTON_LABEL_REMOVE); bt.addClickListener((Button.ClickListener)this); bt.setStyleName(ChameleonTheme.BUTTON_SMALL); /*HORIZONTAL LAYOUT*/ frame = new HorizontalLayout(); frame.setSpacing(true);//used to be true frame.setCaption(level); /*VISUALIZE*/ frame.addComponent(scb); frame.addComponent(bt); frame.setComponentAlignment(bt, Alignment.BOTTOM_RIGHT); setContent(frame); } @Deprecated /*ever seen this? ^^ just wrote it and it's already deprecated*/ public ValueField(FlatQueryBuilder sq, SearchBox sb, String level, String value) { this(sq, sb, level); scb.setValue(value); } @Override public void buttonClick(Button.ClickEvent event) { if(event.getButton()==bt) { sb.removeValueField(this); } } @Override public void textChange(TextChangeEvent event) { reducingStringComparator rsc = sq.getRSC(); String fm = sq.getFilterMechanism(); if (!"generic".equals(fm)) { ConcurrentSkipListSet<String> notInYet = new ConcurrentSkipListSet<String>(); String txt = event.getText(); if (!txt.equals("")) { scb.removeAllItems(); for (Iterator<String> it = values.keySet().iterator(); it.hasNext();) { String s = it.next(); if(rsc.compare(s, txt, fm)==0) { scb.addItem(s); } else {notInYet.add(s);} } //startsWith for(String s : notInYet) { if(rsc.startsWith(s, txt, fm)) { scb.addItem(s); notInYet.remove(s); } } //contains for(String s : notInYet) { if(rsc.contains(s, txt, fm)) { scb.addItem(s); } } } else { buildValues(this.vm); } } else { String txt = event.getText(); HashMap<Integer, Collection> levdistvals = new HashMap<Integer, Collection>(); if (txt.length() > 1) { scb.removeAllItems(); for(String s : values.keySet()) { Integer d = StringUtils.getLevenshteinDistance(removeAccents(txt).toLowerCase(), removeAccents(s).toLowerCase()); if (levdistvals.containsKey(d)){ levdistvals.get(d).add(s); } if (!levdistvals.containsKey(d)){ Set<String> newc = new TreeSet<String>(); newc.add(s); levdistvals.put(d, newc); } } SortedSet<Integer> keys = new TreeSet<Integer>(levdistvals.keySet()); for(Integer k : keys.subSet(0, 10)){ List<String> valueList = new ArrayList(levdistvals.get(k)); Collections.sort(valueList, String.CASE_INSENSITIVE_ORDER); for(String v : valueList){ scb.addItem(v); } } } } } public String getValue() { return (String)scb.getValue(); /*ATTENTION: scb.getValue().toString() causes NullPointerException*/ } public void setValue(String value) { if((vm.equals(ValueMode.REGEX))&(!scb.containsId(value))) { scb.addItem(value); scb.setItemCaption(value, value+" (user defined)"); } scb.setValue(value); } public boolean isRegex() { return (vm==ValueMode.REGEX); } public void setValueMode(ValueMode vm) { if(!vm.equals(this.vm)) { buildValues(vm); } } private void buildValues(ValueMode vm) { this.vm = vm; if(vm.equals(ValueMode.REGEX)) { scb.removeAllItems(); //scb.setItemCaptionMode(ItemCaptionMode.EXPLICIT); for(String v : values.keySet()) { String item = values.get(v); //String itemCaption = v; scb.addItem(item); //scb.setItemCaption(item, itemCaption); } } else { scb.removeAllItems(); scb.setItemCaptionMode(ItemCaptionMode.ID); for(String v : values.keySet()) { scb.addItem(v); } } } public Button getButton() { return bt; } public SensitiveComboBox getSCB() { return scb; } public static String removeAccents(String text) { return text == null ? null : Normalizer.normalize(text, Normalizer.Form.NFD) .replaceAll("\\p{InCombiningDiacriticalMarks}+", ""); } public enum ValueMode { NORMAL, REGEX; } }
annis-gui/src/main/java/annis/gui/flatquerybuilder/ValueField.java
these are the InputFields on SearchBoxes
annis-gui/src/main/java/annis/gui/flatquerybuilder/ValueField.java
these are the InputFields on SearchBoxes
<ide><path>nnis-gui/src/main/java/annis/gui/flatquerybuilder/ValueField.java <add>/* <add> * Copyright 2013 Corpuslinguistic working group Humboldt University Berlin. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add>package annis.gui.flatquerybuilder; <add> <add>import com.vaadin.data.Property.ValueChangeEvent; <add>import com.vaadin.data.Property.ValueChangeListener; <add>import com.vaadin.event.FieldEvents.TextChangeEvent; <add>import com.vaadin.event.FieldEvents.TextChangeListener; <add>import com.vaadin.shared.ui.combobox.FilteringMode; <add>import com.vaadin.ui.AbstractSelect; <add>import com.vaadin.ui.AbstractSelect.ItemCaptionMode; <add>import com.vaadin.ui.Alignment; <add>import com.vaadin.ui.Button; <add>import com.vaadin.ui.HorizontalLayout; <add>import com.vaadin.ui.Panel; <add>import com.vaadin.ui.themes.ChameleonTheme; <add>import java.text.Normalizer; <add>import java.util.ArrayList; <add>import java.util.Collection; <add>import java.util.Collections; <add>import java.util.HashMap; <add>import java.util.Iterator; <add>import java.util.List; <add>import java.util.Set; <add>import java.util.SortedSet; <add>import java.util.TreeSet; <add>import java.util.concurrent.ConcurrentSkipListMap; <add>import java.util.concurrent.ConcurrentSkipListSet; <add>import org.apache.commons.lang3.StringUtils; <add> <add>/** <add> * <add> * @author Martin <add> */ <add>public class ValueField extends Panel implements TextChangeListener, Button.ClickListener <add>{ <add> /*BASIC ELEMENTS*/ <add> private HorizontalLayout frame; <add> private SensitiveComboBox scb; <add> private Button bt; <add> <add> /*ADDITIONAL ATTRIBUTES*/ <add> private FlatQueryBuilder sq; <add> private String level; <add> private SearchBox sb; <add> private ConcurrentSkipListMap<String, String> values; <add> private ValueMode vm; <add> <add> /*LABELS AND STRINGS*/ <add> private static final String BUTTON_LABEL_REMOVE = "X"; <add> private static final String SCB_STYLE_NAME = "corpus-font-force"; <add> private static final String SCB_WIDTH = "130px"; <add> <add> public ValueField(FlatQueryBuilder sq, SearchBox sb, String level) <add> { <add> /*INIT VALUES*/ <add> this.sq = sq; <add> this.sb = sb; <add> this.level = level; <add> vm = (sb.isRegEx()) ? ValueMode.REGEX : ValueMode.NORMAL; <add> values = new ConcurrentSkipListMap<String, String>(); <add> for(String v : sq.getAvailableAnnotationLevels(level)) <add> { <add> values.put(v, sq.escapeRegexCharacters(v)); <add> } <add> <add> /*SENSITIVE COMBOBOX*/ <add> scb = new SensitiveComboBox(); <add> scb.setImmediate(true); <add> scb.setNewItemsAllowed(true); <add> scb.setTextInputAllowed(true); <add> scb.setFilteringMode(FilteringMode.OFF); <add> scb.addListener((TextChangeListener)this); <add> scb.setItemCaptionMode(ItemCaptionMode.ID); <add> buildValues(vm); <add> scb.addStyleName(SCB_STYLE_NAME); <add> scb.setWidth(SCB_WIDTH); <add> <add> /*BUTTON*/ <add> bt = new Button(BUTTON_LABEL_REMOVE); <add> bt.addClickListener((Button.ClickListener)this); <add> bt.setStyleName(ChameleonTheme.BUTTON_SMALL); <add> <add> /*HORIZONTAL LAYOUT*/ <add> frame = new HorizontalLayout(); <add> frame.setSpacing(true);//used to be true <add> frame.setCaption(level); <add> <add> /*VISUALIZE*/ <add> frame.addComponent(scb); <add> frame.addComponent(bt); <add> frame.setComponentAlignment(bt, Alignment.BOTTOM_RIGHT); <add> setContent(frame); <add> } <add> <add> @Deprecated /*ever seen this? ^^ just wrote it and it's already deprecated*/ <add> public ValueField(FlatQueryBuilder sq, SearchBox sb, String level, String value) <add> { <add> this(sq, sb, level); <add> scb.setValue(value); <add> } <add> <add> @Override <add> public void buttonClick(Button.ClickEvent event) <add> { <add> if(event.getButton()==bt) <add> { <add> sb.removeValueField(this); <add> } <add> } <add> <add> @Override <add> public void textChange(TextChangeEvent event) <add> { <add> reducingStringComparator rsc = sq.getRSC(); <add> String fm = sq.getFilterMechanism(); <add> if (!"generic".equals(fm)) <add> { <add> ConcurrentSkipListSet<String> notInYet = new ConcurrentSkipListSet<String>(); <add> String txt = event.getText(); <add> if (!txt.equals("")) <add> { <add> scb.removeAllItems(); <add> for (Iterator<String> it = values.keySet().iterator(); it.hasNext();) <add> { <add> String s = it.next(); <add> if(rsc.compare(s, txt, fm)==0) <add> { <add> scb.addItem(s); <add> } <add> else {notInYet.add(s);} <add> } <add> //startsWith <add> for(String s : notInYet) <add> { <add> if(rsc.startsWith(s, txt, fm)) <add> { <add> scb.addItem(s); <add> notInYet.remove(s); <add> } <add> } <add> //contains <add> for(String s : notInYet) <add> { <add> if(rsc.contains(s, txt, fm)) <add> { <add> scb.addItem(s); <add> } <add> } <add> } <add> else <add> { <add> buildValues(this.vm); <add> } <add> } <add> else <add> { <add> String txt = event.getText(); <add> HashMap<Integer, Collection> levdistvals = new HashMap<Integer, Collection>(); <add> if (txt.length() > 1) <add> { <add> scb.removeAllItems(); <add> for(String s : values.keySet()) <add> { <add> Integer d = StringUtils.getLevenshteinDistance(removeAccents(txt).toLowerCase(), removeAccents(s).toLowerCase()); <add> if (levdistvals.containsKey(d)){ <add> levdistvals.get(d).add(s); <add> } <add> if (!levdistvals.containsKey(d)){ <add> Set<String> newc = new TreeSet<String>(); <add> newc.add(s); <add> levdistvals.put(d, newc); <add> } <add> } <add> SortedSet<Integer> keys = new TreeSet<Integer>(levdistvals.keySet()); <add> for(Integer k : keys.subSet(0, 10)){ <add> List<String> valueList = new ArrayList(levdistvals.get(k)); <add> Collections.sort(valueList, String.CASE_INSENSITIVE_ORDER); <add> for(String v : valueList){ <add> scb.addItem(v); <add> } <add> } <add> } <add> } <add> } <add> <add> public String getValue() <add> { <add> return (String)scb.getValue(); <add> /*ATTENTION: scb.getValue().toString() causes NullPointerException*/ <add> } <add> <add> public void setValue(String value) <add> { <add> if((vm.equals(ValueMode.REGEX))&(!scb.containsId(value))) <add> { <add> scb.addItem(value); <add> scb.setItemCaption(value, value+" (user defined)"); <add> } <add> scb.setValue(value); <add> } <add> <add> public boolean isRegex() <add> { <add> return (vm==ValueMode.REGEX); <add> } <add> <add> public void setValueMode(ValueMode vm) <add> { <add> if(!vm.equals(this.vm)) <add> { <add> buildValues(vm); <add> } <add> } <add> <add> private void buildValues(ValueMode vm) <add> { <add> this.vm = vm; <add> if(vm.equals(ValueMode.REGEX)) <add> { <add> scb.removeAllItems(); <add> //scb.setItemCaptionMode(ItemCaptionMode.EXPLICIT); <add> for(String v : values.keySet()) <add> { <add> String item = values.get(v); <add> //String itemCaption = v; <add> scb.addItem(item); <add> //scb.setItemCaption(item, itemCaption); <add> } <add> } <add> else <add> { <add> scb.removeAllItems(); <add> scb.setItemCaptionMode(ItemCaptionMode.ID); <add> for(String v : values.keySet()) <add> { <add> scb.addItem(v); <add> } <add> } <add> } <add> <add> public Button getButton() <add> { <add> return bt; <add> } <add> <add> public SensitiveComboBox getSCB() <add> { <add> return scb; <add> } <add> <add> public static String removeAccents(String text) { <add> return text == null ? null <add> : Normalizer.normalize(text, Normalizer.Form.NFD) <add> .replaceAll("\\p{InCombiningDiacriticalMarks}+", ""); <add> } <add> <add> public enum ValueMode <add> { <add> NORMAL, REGEX; <add> } <add>}
Java
apache-2.0
2574c9ef3444bfcf42120902b3749c93e900a182
0
apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
/* * Copyright 2016-2018 shardingsphere.io. * <p> * 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. * </p> */ package io.shardingsphere.example.repository.api.service; import io.shardingsphere.example.repository.api.entity.Order; import io.shardingsphere.example.repository.api.entity.OrderItem; import io.shardingsphere.example.repository.api.repository.Repository; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.ArrayList; import java.util.List; @Service public class DemoService { @Resource private Repository<Order> orderRepository; @Resource private Repository<OrderItem> orderItemRepository; public void demo() { orderRepository.createIfNotExistsTable(); orderItemRepository.createIfNotExistsTable(); orderRepository.truncateTable(); orderItemRepository.truncateTable(); List<Long> orderIds = new ArrayList<>(10); System.out.println("1.Insert--------------"); for (int i = 0; i < 10; i++) { Order order = new Order(); order.setUserId(51); order.setStatus("INSERT_TEST"); orderRepository.insert(order); long orderId = order.getOrderId(); orderIds.add(orderId); OrderItem item = new OrderItem(); item.setOrderId(orderId); item.setUserId(51); item.setStatus("INSERT_TEST"); orderItemRepository.insert(item); } System.out.println("Order Data--------------"); System.out.println(orderRepository.selectAll()); System.out.println("OrderItem Data--------------"); System.out.println(orderItemRepository.selectAll()); System.out.println("2.Delete--------------"); for (Long each : orderIds) { orderRepository.delete(each); orderItemRepository.delete(each); } System.out.println("Order Data--------------"); System.out.println(orderRepository.selectAll()); System.out.println("OrderItem Data--------------"); System.out.println(orderItemRepository.selectAll()); orderItemRepository.dropTable(); orderRepository.dropTable(); } }
common-repository/api-repository/src/main/java/io/shardingsphere/example/repository/api/service/DemoService.java
/* * Copyright 2016-2018 shardingsphere.io. * <p> * 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. * </p> */ package io.shardingsphere.example.repository.api.service; import io.shardingsphere.example.repository.api.entity.Order; import io.shardingsphere.example.repository.api.entity.OrderItem; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.ArrayList; import java.util.List; @Service public class DemoService { @Resource private OrderRepository orderRepository; @Resource private OrderItemRepository orderItemRepository; public void demo() { orderRepository.createIfNotExistsTable(); orderItemRepository.createIfNotExistsTable(); orderRepository.truncateTable(); orderItemRepository.truncateTable(); List<Long> orderIds = new ArrayList<>(10); System.out.println("1.Insert--------------"); for (int i = 0; i < 10; i++) { Order order = new Order(); order.setUserId(51); order.setStatus("INSERT_TEST"); orderRepository.insert(order); long orderId = order.getOrderId(); orderIds.add(orderId); OrderItem item = new OrderItem(); item.setOrderId(orderId); item.setUserId(51); item.setStatus("INSERT_TEST"); orderItemRepository.insert(item); } System.out.println(orderItemRepository.selectAll()); System.out.println("2.Delete--------------"); for (Long each : orderIds) { orderRepository.delete(each); orderItemRepository.delete(each); } System.out.println(orderItemRepository.selectAll()); orderItemRepository.dropTable(); orderRepository.dropTable(); } }
add order select all()
common-repository/api-repository/src/main/java/io/shardingsphere/example/repository/api/service/DemoService.java
add order select all()
<ide><path>ommon-repository/api-repository/src/main/java/io/shardingsphere/example/repository/api/service/DemoService.java <ide> <ide> import io.shardingsphere.example.repository.api.entity.Order; <ide> import io.shardingsphere.example.repository.api.entity.OrderItem; <add>import io.shardingsphere.example.repository.api.repository.Repository; <ide> import org.springframework.stereotype.Service; <ide> <ide> import javax.annotation.Resource; <ide> public class DemoService { <ide> <ide> @Resource <del> private OrderRepository orderRepository; <add> private Repository<Order> orderRepository; <ide> <ide> @Resource <del> private OrderItemRepository orderItemRepository; <add> private Repository<OrderItem> orderItemRepository; <ide> <ide> public void demo() { <ide> orderRepository.createIfNotExistsTable(); <ide> item.setStatus("INSERT_TEST"); <ide> orderItemRepository.insert(item); <ide> } <add> System.out.println("Order Data--------------"); <add> System.out.println(orderRepository.selectAll()); <add> System.out.println("OrderItem Data--------------"); <ide> System.out.println(orderItemRepository.selectAll()); <ide> System.out.println("2.Delete--------------"); <ide> for (Long each : orderIds) { <ide> orderRepository.delete(each); <ide> orderItemRepository.delete(each); <ide> } <add> System.out.println("Order Data--------------"); <add> System.out.println(orderRepository.selectAll()); <add> System.out.println("OrderItem Data--------------"); <ide> System.out.println(orderItemRepository.selectAll()); <ide> orderItemRepository.dropTable(); <ide> orderRepository.dropTable();
Java
apache-2.0
441b22fcce3ef50da14d5f4c8b376c870b57748d
0
BruceZu/sawdust,BruceZu/sawdust,BruceZu/sawdust,BruceZu/sawdust
// Copyright 2016 The Sawdust 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 nosubmmitted; /** * 161. One Edit Distance * https://leetcode.com/problems/one-edit-distance/ * <pre> * Difficulty: Medium * Given two strings S and T, determine if they are both one edit distance apart. * * Hide Company Tags Snapchat Uber Facebook Twitter * Hide Tags String * Hide Similar Problems (H) Edit Distance * Have you met this question in a real interview? Yes No * Discuss * * </pre> */ public class LC161OneEditDistance { /** * the fast one currently * beat 93.69% */ public boolean isOneEditDistance(String S, String T) { int si = -1, sl = S.length(), ti = -1, tl = T.length(); char[] sArr = S.toCharArray(), tArr = T.toCharArray(); if (Math.abs(sl - tl) > 1) { return false; } while (si < sl - 1 && ti < tl - 1 && sArr[si + 1] == tArr[ti + 1]) { si++; ti++; } // equals if (sl == tl && si == sl - 1) { return false; } while (sl > 0 && tl > 0 && sArr[sl - 1] == tArr[tl - 1]) { sl--; tl--; } return Math.max(sl - si, tl - ti) < 3; } /** * same as above * I referenced https://leetcode.com/discuss/55496/simple-java-solution-o-n-time-%26-o-1-space but did some improvement: * Basic idea is as follows: Using 2 pointers to go through each string and compare if the characters are the same. When there is an disagreement, jump out of inner loop and increase one of the pointers by 1. (if s.length() < t.length(), increase the pointer of t, otherwise increase that of s) * <p/> * Return true if we reach the end of either of them, otherwise check if the disagreement occurs for the first time. If so make increment indicated above, otherwise return false. (since in this situation, the distance apart is more than 1) * <p/> * (1) do not use equals(), that add another O(n) burden. * <p/> * (2) define longer and shorter, so focus on shorter's end. * <p/> * (3) when shorter reaches end, cnt==0 still might be true situation. For example, "a" and "ab", thus refer to their difference in length. */ public boolean isOneEditDistance2(String s, String t) { char[] longer = s.length() > t.length() ? s.toCharArray() : t.toCharArray(); char[] shorter = s.length() > t.length() ? t.toCharArray() : s.toCharArray(); if (longer.length - shorter.length > 1) return false; int cnt = 0; int i = 0, j = 0; while (true) { while (j < shorter.length && longer[i] == shorter[j]) { ++i; ++j; } if (j == shorter.length) return !(cnt == 0) || longer.length - shorter.length == 1; if (++cnt > 1) return false; // same length, replace if (longer.length == shorter.length) { ++i; ++j; } else { //delete from longer ++i; } } } /** * other idea scan from head of two strings until to index l where two characters are different. scan from tails of two strings until to index r1, r2 where two characters are different. y1 = r1 - l + 1, y2 = r2 - l + 1 are the different characters number y1, y2 should only be 1,0 or 0,1 or 1,1. I could have make the code shorter but I don't want to sacrifice clarity. \ */ }
arrows/src/main/java/nosubmmitted/LC161OneEditDistance.java
// Copyright 2016 The Sawdust 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 nosubmmitted; /** * 161. One Edit Distance * https://leetcode.com/problems/one-edit-distance/ * <pre> * Difficulty: Medium * Given two strings S and T, determine if they are both one edit distance apart. * * Hide Company Tags Snapchat Uber Facebook Twitter * Hide Tags String * Hide Similar Problems (H) Edit Distance * Have you met this question in a real interview? Yes No * Discuss * * </pre> */ public class LC161OneEditDistance { /** * the fast one currently * beat 93.69% */ public boolean isOneEditDistance(String s, String t) { int s1 = -1, s2 = s.length(), t1 = -1, t2 = t.length(); char[] sArr = s.toCharArray(), tArr = t.toCharArray(); if (Math.abs(s2 - t2) > 1) { return false; } while (s1 < s2 - 1 && t1 < t2 - 1 && sArr[s1 + 1] == tArr[t1 + 1]) { s1++; t1++; } // equals if (s2 == t2 && s1 == s2 - 1) { return false; } while (s2 > 0 && t2 > 0 && sArr[s2 - 1] == tArr[t2 - 1]) { s2--; t2--; } return Math.max(s2 - s1, t2 - t1) < 3; } /** * same as above * I referenced https://leetcode.com/discuss/55496/simple-java-solution-o-n-time-%26-o-1-space but did some improvement: * Basic idea is as follows: Using 2 pointers to go through each string and compare if the characters are the same. When there is an disagreement, jump out of inner loop and increase one of the pointers by 1. (if s.length() < t.length(), increase the pointer of t, otherwise increase that of s) * <p/> * Return true if we reach the end of either of them, otherwise check if the disagreement occurs for the first time. If so make increment indicated above, otherwise return false. (since in this situation, the distance apart is more than 1) * <p/> * (1) do not use equals(), that add another O(n) burden. * <p/> * (2) define longer and shorter, so focus on shorter's end. * <p/> * (3) when shorter reaches end, cnt==0 still might be true situation. For example, "a" and "ab", thus refer to their difference in length. */ public boolean isOneEditDistance2(String s, String t) { char[] longer = s.length() > t.length() ? s.toCharArray() : t.toCharArray(); char[] shorter = s.length() > t.length() ? t.toCharArray() : s.toCharArray(); if (longer.length - shorter.length > 1) return false; int cnt = 0; int i = 0, j = 0; while (true) { while (j < shorter.length && longer[i] == shorter[j]) { ++i; ++j; } if (j == shorter.length) return !(cnt == 0) || longer.length - shorter.length == 1; if (++cnt > 1) return false; // same length, replace if (longer.length == shorter.length) { ++i; ++j; } else { //delete from longer ++i; } } } /** * other idea scan from head of two strings until to index l where two characters are different. scan from tails of two strings until to index r1, r2 where two characters are different. y1 = r1 - l + 1, y2 = r2 - l + 1 are the different characters number y1, y2 should only be 1,0 or 0,1 or 1,1. I could have make the code shorter but I don't want to sacrifice clarity. \ */ }
More readable of Once Edit Distance
arrows/src/main/java/nosubmmitted/LC161OneEditDistance.java
More readable of Once Edit Distance
<ide><path>rrows/src/main/java/nosubmmitted/LC161OneEditDistance.java <ide> * the fast one currently <ide> * beat 93.69% <ide> */ <del> public boolean isOneEditDistance(String s, String t) { <add> public boolean isOneEditDistance(String S, String T) { <ide> <del> int s1 = -1, s2 = s.length(), t1 = -1, t2 = t.length(); <del> char[] sArr = s.toCharArray(), tArr = t.toCharArray(); <add> int si = -1, sl = S.length(), ti = -1, tl = T.length(); <add> char[] sArr = S.toCharArray(), tArr = T.toCharArray(); <ide> <del> if (Math.abs(s2 - t2) > 1) { <add> if (Math.abs(sl - tl) > 1) { <ide> return false; <ide> } <ide> <del> while (s1 < s2 - 1 && t1 < t2 - 1 && sArr[s1 + 1] == tArr[t1 + 1]) { <del> s1++; <del> t1++; <add> while (si < sl - 1 && ti < tl - 1 && sArr[si + 1] == tArr[ti + 1]) { <add> si++; <add> ti++; <ide> } <ide> <ide> // equals <del> if (s2 == t2 && s1 == s2 - 1) { <add> if (sl == tl && si == sl - 1) { <ide> return false; <ide> } <ide> <del> while (s2 > 0 && t2 > 0 && sArr[s2 - 1] == tArr[t2 - 1]) { <del> s2--; <del> t2--; <add> while (sl > 0 && tl > 0 && sArr[sl - 1] == tArr[tl - 1]) { <add> sl--; <add> tl--; <ide> } <ide> <del> return Math.max(s2 - s1, t2 - t1) < 3; <add> return Math.max(sl - si, tl - ti) < 3; <ide> } <ide> <ide> /**
Java
apache-2.0
1497958f9c9b4fa293d99bfd96e48428a6883a47
0
AArhin/head,AArhin/head,AArhin/head,jpodeszwik/mifos,AArhin/head,jpodeszwik/mifos,jpodeszwik/mifos,jpodeszwik/mifos,maduhu/head,maduhu/head,maduhu/head,maduhu/head,AArhin/head,maduhu/head
/* * Copyright (c) 2005-2011 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.test.acceptance.util; import org.apache.commons.lang.RandomStringUtils; public class StringUtil { public static String getRandomString(int length) { return RandomStringUtils.randomAlphanumeric(length); } }
acceptanceTests/src/test/java/org/mifos/test/acceptance/util/StringUtil.java
/* * Copyright (c) 2005-2011 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.test.acceptance.util; public class StringUtil { public static String getRandomString(int length) { String millis = Long.toString(System.currentTimeMillis()); return millis.substring(millis.length() - length); } }
MIFOS-4589 : Use better random string generation from appache commons lang util
acceptanceTests/src/test/java/org/mifos/test/acceptance/util/StringUtil.java
MIFOS-4589 : Use better random string generation from appache commons lang util
<ide><path>cceptanceTests/src/test/java/org/mifos/test/acceptance/util/StringUtil.java <ide> <ide> package org.mifos.test.acceptance.util; <ide> <add>import org.apache.commons.lang.RandomStringUtils; <add> <ide> public class StringUtil { <ide> <ide> public static String getRandomString(int length) { <del> String millis = Long.toString(System.currentTimeMillis()); <del> return millis.substring(millis.length() - length); <add> return RandomStringUtils.randomAlphanumeric(length); <ide> } <ide> } <ide>
Java
apache-2.0
6664ec61af1e2e684f372f878876ea8ff621625b
0
vherilier/jmeter,etnetera/jmeter,vherilier/jmeter,ubikloadpack/jmeter,etnetera/jmeter,vherilier/jmeter,etnetera/jmeter,ubikloadpack/jmeter,etnetera/jmeter,ubikloadpack/jmeter,etnetera/jmeter,vherilier/jmeter,ubikloadpack/jmeter
/* * 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.jmeter.protocol.java.sampler; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Enumeration; import org.apache.jmeter.samplers.AbstractSampler; import org.apache.jmeter.samplers.Entry; import org.apache.jmeter.samplers.SampleResult; import org.apache.jmeter.testelement.ThreadListener; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.Test.None; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import junit.framework.AssertionFailedError; import junit.framework.Protectable; import junit.framework.TestCase; import junit.framework.TestFailure; import junit.framework.TestResult; /** * * This is a basic implementation that runs a single test method of * a JUnit test case. The current implementation will use the string * constructor first. If the test class does not declare a string * constructor, the sampler will try empty constructor. */ public class JUnitSampler extends AbstractSampler implements ThreadListener { private static final Logger log = LoggerFactory.getLogger(JUnitSampler.class); private static final long serialVersionUID = 240L; // Remember to change this when the class changes ... //++ JMX file attributes - do not change private static final String CLASSNAME = "junitSampler.classname"; private static final String CONSTRUCTORSTRING = "junitsampler.constructorstring"; private static final String METHOD = "junitsampler.method"; private static final String ERROR = "junitsampler.error"; private static final String ERRORCODE = "junitsampler.error.code"; private static final String FAILURE = "junitsampler.failure"; private static final String FAILURECODE = "junitsampler.failure.code"; private static final String SUCCESS = "junitsampler.success"; private static final String SUCCESSCODE = "junitsampler.success.code"; private static final String FILTER = "junitsampler.pkg.filter"; private static final String DOSETUP = "junitsampler.exec.setup"; private static final String APPEND_ERROR = "junitsampler.append.error"; private static final String APPEND_EXCEPTION = "junitsampler.append.exception"; private static final String JUNIT4 = "junitsampler.junit4"; private static final String CREATE_INSTANCE_PER_SAMPLE="junitsampler.createinstancepersample"; private static final boolean CREATE_INSTANCE_PER_SAMPLE_DEFAULT = false; //-- JMX file attributes - do not change private static final String SETUP = "setUp"; private static final String TEARDOWN = "tearDown"; // the Method objects for setUp (@Before) and tearDown (@After) methods // Will be null if not provided or not required private transient Method setUpMethod; private transient Method tearDownMethod; // The TestCase to run private transient TestCase testCase; // The test object, i.e. the instance of the class containing the test method // This is the same as testCase for JUnit3 tests // but different for JUnit4 tests which use a wrapper private transient Object testObject; // The method name to be invoked private transient String methodName; // The name of the class containing the method private transient String className; // The wrapper used to invoke the method private transient Protectable protectable; public JUnitSampler(){ super(); } /** * Method tries to get the setUp and tearDown method for the class * @param testObject */ private void initMethodObjects(Object testObject){ setUpMethod = null; tearDownMethod = null; if (!getDoNotSetUpTearDown()) { setUpMethod = getJunit4() ? getMethodWithAnnotation(testObject, Before.class) : getMethod(testObject, SETUP); tearDownMethod = getJunit4() ? getMethodWithAnnotation(testObject, After.class) : getMethod(testObject, TEARDOWN); } } /** * Sets the Classname attribute of the JavaConfig object * * @param classname * the new Classname value */ public void setClassname(String classname) { setProperty(CLASSNAME, classname); } /** * Gets the Classname attribute of the JavaConfig object * * @return the Classname value */ public String getClassname() { return getPropertyAsString(CLASSNAME); } /** * Set the string label used to create an instance of the * test with the string constructor. * @param constr the string passed to the constructor */ public void setConstructorString(String constr) { setProperty(CONSTRUCTORSTRING,constr); } /** * @return the string passed to the string constructor */ public String getConstructorString() { return getPropertyAsString(CONSTRUCTORSTRING); } /** * @return the name of the method to test */ public String getMethod(){ return getPropertyAsString(METHOD); } /** * Method should add the JUnit <em>testXXX</em> method to the list at * the end, since the sequence matters. * @param methodName name of the method to test */ public void setMethod(String methodName){ setProperty(METHOD,methodName); } /** * @return the success message */ public String getSuccess(){ return getPropertyAsString(SUCCESS); } /** * set the success message * @param success message to be used for success */ public void setSuccess(String success){ setProperty(SUCCESS,success); } /** * @return the success code defined by the user */ public String getSuccessCode(){ return getPropertyAsString(SUCCESSCODE); } /** * Set the success code. The success code should * be unique. * @param code unique success code */ public void setSuccessCode(String code){ setProperty(SUCCESSCODE,code); } /** * @return the failure message */ public String getFailure(){ return getPropertyAsString(FAILURE); } /** * set the failure message * @param fail the failure message */ public void setFailure(String fail){ setProperty(FAILURE,fail); } /** * @return The failure code that is used by other components */ public String getFailureCode(){ return getPropertyAsString(FAILURECODE); } /** * Provide some unique code to denote a type of failure * @param code unique code to denote the type of failure */ public void setFailureCode(String code){ setProperty(FAILURECODE,code); } /** * @return the descriptive error for the test */ public String getError(){ return getPropertyAsString(ERROR); } /** * provide a descriptive error for the test method. For * a description of the difference between failure and * error, please refer to the * <a href="http://junit.sourceforge.net/doc/faq/faq.htm#tests_9">junit faq</a> * @param error the description of the error */ public void setError(String error){ setProperty(ERROR,error); } /** * @return the error code for the test method. It should * be an unique error code. */ public String getErrorCode(){ return getPropertyAsString(ERRORCODE); } /** * Provide an unique error code for when the test * does not pass the assert test. * @param code unique error code */ public void setErrorCode(String code){ setProperty(ERRORCODE,code); } /** * @return the comma separated string for the filter */ public String getFilterString(){ return getPropertyAsString(FILTER); } /** * set the filter string in comma separated format * @param text comma separated filter */ public void setFilterString(String text){ setProperty(FILTER,text); } /** * if the sample shouldn't call setup/teardown, the * method returns true. It's meant for onetimesetup * and onetimeteardown. * * @return flag whether setup/teardown methods should not be called */ public boolean getDoNotSetUpTearDown(){ return getPropertyAsBoolean(DOSETUP); } /** * set the setup/teardown option * * @param setup flag whether the setup/teardown methods should not be called */ public void setDoNotSetUpTearDown(boolean setup){ setProperty(DOSETUP,String.valueOf(setup)); } /** * If append error is not set, by default it is set to false, * which means users have to explicitly set the sampler to * append the assert errors. Because of how junit works, there * should only be one error * * @return flag whether errors should be appended */ public boolean getAppendError() { return getPropertyAsBoolean(APPEND_ERROR,false); } /** * Set whether to append errors or not. * * @param error the setting to apply */ public void setAppendError(boolean error) { setProperty(APPEND_ERROR,String.valueOf(error)); } /** * If append exception is not set, by default it is set to <code>false</code>. * Users have to explicitly set it to <code>true</code> to see the exceptions * in the result tree. * * @return flag whether exceptions should be appended to the result tree */ public boolean getAppendException() { return getPropertyAsBoolean(APPEND_EXCEPTION,false); } /** * Set whether to append exceptions or not. * * @param exc the setting to apply. */ public void setAppendException(boolean exc) { setProperty(APPEND_EXCEPTION,String.valueOf(exc)); } /** * Check if JUnit4 (annotations) are to be used instead of * the JUnit3 style (TestClass and specific method names) * * @return true if JUnit4 (annotations) are to be used. * Default is false. */ public boolean getJunit4() { return getPropertyAsBoolean(JUNIT4, false); } /** * Set whether to use JUnit4 style or not. * @param junit4 true if JUnit4 style is to be used. */ public void setJunit4(boolean junit4) { setProperty(JUNIT4, junit4, false); } /** {@inheritDoc} */ @Override public SampleResult sample(Entry entry) { if(getCreateOneInstancePerSample()) { initializeTestObject(); } SampleResult sresult = new SampleResult(); sresult.setSampleLabel(getName());// Bug 41522 - don't use rlabel here sresult.setSamplerData(className + "." + methodName); sresult.setDataType(SampleResult.TEXT); // Assume success sresult.setSuccessful(true); sresult.setResponseMessage(getSuccess()); sresult.setResponseCode(getSuccessCode()); if (this.testCase != null){ // create a new TestResult TestResult tr = new TestResult(); final TestCase theClazz = this.testCase; try { if (setUpMethod != null){ setUpMethod.invoke(this.testObject,new Object[0]); } sresult.sampleStart(); tr.startTest(this.testCase); // Do not use TestCase.run(TestResult) method, since it will // call setUp and tearDown. Doing that will result in calling // the setUp and tearDown method twice and the elapsed time // will include setup and teardown. tr.runProtected(theClazz, protectable); tr.endTest(this.testCase); sresult.sampleEnd(); if (tearDownMethod != null){ tearDownMethod.invoke(testObject,new Object[0]); } } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof AssertionFailedError){ tr.addFailure(theClazz, (AssertionFailedError) cause); } else if (cause instanceof AssertionError) { // Convert JUnit4 failure to Junit3 style AssertionFailedError afe = new AssertionFailedError(cause.toString()); // copy the original stack trace afe.setStackTrace(cause.getStackTrace()); tr.addFailure(theClazz, afe); } else if (cause != null) { tr.addError(theClazz, cause); log.info("caught exception", e); } else { tr.addError(theClazz, e); log.info("caught exception", e); } } catch (IllegalAccessException | IllegalArgumentException e) { tr.addError(theClazz, e); } if ( !tr.wasSuccessful() ){ sresult.setSuccessful(false); StringBuilder buf = new StringBuilder(); StringBuilder buftrace = new StringBuilder(); Enumeration<TestFailure> en; if (getAppendError()) { en = tr.failures(); if (en.hasMoreElements()){ sresult.setResponseCode(getFailureCode()); buf.append( getFailure() ); buf.append("\n"); } while (en.hasMoreElements()){ TestFailure item = en.nextElement(); buf.append( "Failure -- "); buf.append( item.toString() ); buf.append("\n"); buftrace.append( "Failure -- "); buftrace.append( item.toString() ); buftrace.append("\n"); buftrace.append( "Trace -- "); buftrace.append( item.trace() ); } en = tr.errors(); if (en.hasMoreElements()){ sresult.setResponseCode(getErrorCode()); buf.append( getError() ); buf.append("\n"); } while (en.hasMoreElements()){ TestFailure item = en.nextElement(); buf.append( "Error -- "); buf.append( item.toString() ); buf.append("\n"); buftrace.append( "Error -- "); buftrace.append( item.toString() ); buftrace.append("\n"); buftrace.append( "Trace -- "); buftrace.append( item.trace() ); } } sresult.setResponseMessage(buf.toString()); sresult.setResponseData(buftrace.toString(), null); } } else { // we should log a warning, but allow the test to keep running sresult.setSuccessful(false); // this should be externalized to the properties sresult.setResponseMessage("Failed to create an instance of the class:"+getClassname() +", reasons may be missing both empty constructor and one " + "String constructor or failure to instantiate constructor," + " check warning messages in jmeter log file"); sresult.setResponseCode(getErrorCode()); } return sresult; } /** * If the method is not able to create a new instance of the * class, it returns null and logs all the exceptions at * warning level. */ private static Object getClassInstance(String className, String label){ Object testclass = null; if (className != null){ Constructor<?> con = null; Constructor<?> strCon = null; Class<?> theclazz = null; Object[] strParams = null; Object[] params = null; try { theclazz = Thread.currentThread().getContextClassLoader().loadClass(className.trim()); } catch (ClassNotFoundException e) { log.warn("ClassNotFoundException:: {}", e.getMessage()); } if (theclazz != null) { // first we see if the class declares a string // constructor. if it is doesn't we look for // empty constructor. try { strCon = theclazz.getDeclaredConstructor( new Class[] {String.class}); // we have to check and make sure the constructor is // accessible. if we didn't it would throw an exception // and cause a NPE. if (label == null || label.length() == 0) { label = className; } if (strCon.getModifiers() == Modifier.PUBLIC) { strParams = new Object[]{label}; } else { strCon = null; } } catch (NoSuchMethodException e) { log.info("Trying to find constructor with one String parameter returned error: {}", e.getMessage()); } try { con = theclazz.getDeclaredConstructor(new Class[0]); if (con != null){ params = new Object[]{}; } } catch (NoSuchMethodException e) { log.info("Trying to find empty constructor returned error: {}", e.getMessage()); } try { // if the string constructor is not null, we use it. // if the string constructor is null, we use the empty // constructor to get a new instance if (strCon != null) { testclass = strCon.newInstance(strParams); } else if (con != null){ testclass = con.newInstance(params); } else { log.error("No empty constructor nor string constructor found for class:{}", theclazz); } } catch (InvocationTargetException | IllegalAccessException | InstantiationException e) { log.error("Error instantiating class:{}:{}", theclazz, e.getMessage(), e); } } } return testclass; } /** * Get a method. * @param clazz the classname (may be null) * @param method the method name (may be null) * @return the method or null if an error occurred * (or either parameter is null) */ private Method getMethod(Object clazz, String method){ if (clazz != null && method != null){ try { return clazz.getClass().getMethod(method,new Class[0]); } catch (NoSuchMethodException e) { log.warn(e.getMessage()); } } return null; } private Method getMethodWithAnnotation(Object clazz, Class<? extends Annotation> annotation) { if(null != clazz && null != annotation) { for(Method m : clazz.getClass().getMethods()) { if(m.isAnnotationPresent(annotation)) { return m; } } } return null; } /* * Wrapper to convert a JUnit4 class into a TestCase * * TODO - work out how to convert JUnit4 assertions so they are treated as failures rather than errors */ private class AnnotatedTestCase extends TestCase { private final Method method; private final Class<? extends Throwable> expectedException; private final long timeout; public AnnotatedTestCase(Method method, Class<? extends Throwable> expectedException2, long timeout) { this.method = method; this.expectedException = expectedException2; this.timeout = timeout; } @Override protected void runTest() throws Throwable { try { long start = System.currentTimeMillis(); method.invoke(testObject, (Object[])null); if (expectedException != None.class) { throw new AssertionFailedError( "No error was generated for a test case which specifies an error."); } if (timeout > 0){ long elapsed = System.currentTimeMillis() - start; if (elapsed > timeout) { throw new AssertionFailedError("Test took longer than the specified timeout."); } } } catch (InvocationTargetException e) { Throwable thrown = e.getCause(); if (thrown == null) { // probably should not happen throw e; } if (expectedException == None.class){ // Convert JUnit4 AssertionError failures to JUnit3 style so // will be treated as failure rather than error. if (thrown instanceof AssertionError && !(thrown instanceof AssertionFailedError)){ AssertionFailedError afe = new AssertionFailedError(thrown.toString()); // copy the original stack trace afe.setStackTrace(thrown.getStackTrace()); throw afe; } throw thrown; } if (!expectedException.isAssignableFrom(thrown.getClass())){ throw new AssertionFailedError("The wrong exception was thrown from the test case"); } } } } @Override public void threadFinished() { } /** * Set up all variables that don't change between samples. */ @Override public void threadStarted() { testObject = null; testCase = null; methodName = getMethod(); className = getClassname(); protectable = null; if(!getCreateOneInstancePerSample()) { // NO NEED TO INITIALIZE WHEN getCreateOneInstancePerSample // is true cause it will be done in sample initializeTestObject(); } } /** * Initialize test object */ private void initializeTestObject() { String rlabel = getConstructorString(); if (rlabel.length()== 0) { rlabel = JUnitSampler.class.getName(); } this.testObject = getClassInstance(className, rlabel); if (this.testObject != null){ initMethodObjects(this.testObject); final Method m = getMethod(this.testObject,methodName); if (getJunit4()){ Class<? extends Throwable> expectedException = None.class; long timeout = 0; Test annotation = m.getAnnotation(Test.class); if(null != annotation) { expectedException = annotation.expected(); timeout = annotation.timeout(); } final AnnotatedTestCase at = new AnnotatedTestCase(m, expectedException, timeout); testCase = at; protectable = new Protectable() { @Override public void protect() throws Throwable { at.runTest(); } }; } else { this.testCase = (TestCase) this.testObject; final Object theClazz = this.testObject; // Must be final to create instance protectable = new Protectable() { @Override public void protect() throws Throwable { try { m.invoke(theClazz,new Object[0]); } catch (InvocationTargetException e) { /* * Calling a method via reflection results in wrapping any * Exceptions in ITE; unwrap these here so runProtected can * allocate them correctly. */ Throwable t = e.getCause(); if (t != null) { throw t; } throw e; } } }; } if (this.testCase != null){ this.testCase.setName(methodName); } } } /** * * @param createOneInstancePerSample * flag whether a new instance for each call should be created */ public void setCreateOneInstancePerSample(boolean createOneInstancePerSample) { this.setProperty(CREATE_INSTANCE_PER_SAMPLE, createOneInstancePerSample, CREATE_INSTANCE_PER_SAMPLE_DEFAULT); } /** * * @return boolean create New Instance For Each Call */ public boolean getCreateOneInstancePerSample() { return getPropertyAsBoolean(CREATE_INSTANCE_PER_SAMPLE, CREATE_INSTANCE_PER_SAMPLE_DEFAULT); } }
src/junit/org/apache/jmeter/protocol/java/sampler/JUnitSampler.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.jmeter.protocol.java.sampler; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Enumeration; import org.apache.jmeter.samplers.AbstractSampler; import org.apache.jmeter.samplers.Entry; import org.apache.jmeter.samplers.SampleResult; import org.apache.jmeter.testelement.ThreadListener; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.Test.None; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import junit.framework.AssertionFailedError; import junit.framework.Protectable; import junit.framework.TestCase; import junit.framework.TestFailure; import junit.framework.TestResult; /** * * This is a basic implementation that runs a single test method of * a JUnit test case. The current implementation will use the string * constructor first. If the test class does not declare a string * constructor, the sampler will try empty constructor. */ public class JUnitSampler extends AbstractSampler implements ThreadListener { private static final Logger log = LoggerFactory.getLogger(JUnitSampler.class); private static final long serialVersionUID = 240L; // Remember to change this when the class changes ... //++ JMX file attributes - do not change private static final String CLASSNAME = "junitSampler.classname"; private static final String CONSTRUCTORSTRING = "junitsampler.constructorstring"; private static final String METHOD = "junitsampler.method"; private static final String ERROR = "junitsampler.error"; private static final String ERRORCODE = "junitsampler.error.code"; private static final String FAILURE = "junitsampler.failure"; private static final String FAILURECODE = "junitsampler.failure.code"; private static final String SUCCESS = "junitsampler.success"; private static final String SUCCESSCODE = "junitsampler.success.code"; private static final String FILTER = "junitsampler.pkg.filter"; private static final String DOSETUP = "junitsampler.exec.setup"; private static final String APPEND_ERROR = "junitsampler.append.error"; private static final String APPEND_EXCEPTION = "junitsampler.append.exception"; private static final String JUNIT4 = "junitsampler.junit4"; private static final String CREATE_INSTANCE_PER_SAMPLE="junitsampler.createinstancepersample"; private static final boolean CREATE_INSTANCE_PER_SAMPLE_DEFAULT = false; //-- JMX file attributes - do not change private static final String SETUP = "setUp"; private static final String TEARDOWN = "tearDown"; // the Method objects for setUp (@Before) and tearDown (@After) methods // Will be null if not provided or not required private transient Method setUpMethod; private transient Method tearDownMethod; // The TestCase to run private transient TestCase testCase; // The test object, i.e. the instance of the class containing the test method // This is the same as testCase for JUnit3 tests // but different for JUnit4 tests which use a wrapper private transient Object testObject; // The method name to be invoked private transient String methodName; // The name of the class containing the method private transient String className; // The wrapper used to invoke the method private transient Protectable protectable; public JUnitSampler(){ super(); } /** * Method tries to get the setUp and tearDown method for the class * @param testObject */ private void initMethodObjects(Object testObject){ setUpMethod = null; tearDownMethod = null; if (!getDoNotSetUpTearDown()) { setUpMethod = getJunit4() ? getMethodWithAnnotation(testObject, Before.class) : getMethod(testObject, SETUP); tearDownMethod = getJunit4() ? getMethodWithAnnotation(testObject, After.class) : getMethod(testObject, TEARDOWN); } } /** * Sets the Classname attribute of the JavaConfig object * * @param classname * the new Classname value */ public void setClassname(String classname) { setProperty(CLASSNAME, classname); } /** * Gets the Classname attribute of the JavaConfig object * * @return the Classname value */ public String getClassname() { return getPropertyAsString(CLASSNAME); } /** * Set the string label used to create an instance of the * test with the string constructor. * @param constr the string passed to the constructor */ public void setConstructorString(String constr) { setProperty(CONSTRUCTORSTRING,constr); } /** * @return the string passed to the string constructor */ public String getConstructorString() { return getPropertyAsString(CONSTRUCTORSTRING); } /** * @return the name of the method to test */ public String getMethod(){ return getPropertyAsString(METHOD); } /** * Method should add the JUnit <em>testXXX</em> method to the list at * the end, since the sequence matters. * @param methodName name of the method to test */ public void setMethod(String methodName){ setProperty(METHOD,methodName); } /** * @return the success message */ public String getSuccess(){ return getPropertyAsString(SUCCESS); } /** * set the success message * @param success message to be used for success */ public void setSuccess(String success){ setProperty(SUCCESS,success); } /** * @return the success code defined by the user */ public String getSuccessCode(){ return getPropertyAsString(SUCCESSCODE); } /** * Set the success code. The success code should * be unique. * @param code unique success code */ public void setSuccessCode(String code){ setProperty(SUCCESSCODE,code); } /** * @return the failure message */ public String getFailure(){ return getPropertyAsString(FAILURE); } /** * set the failure message * @param fail the failure message */ public void setFailure(String fail){ setProperty(FAILURE,fail); } /** * @return The failure code that is used by other components */ public String getFailureCode(){ return getPropertyAsString(FAILURECODE); } /** * Provide some unique code to denote a type of failure * @param code unique code to denote the type of failure */ public void setFailureCode(String code){ setProperty(FAILURECODE,code); } /** * @return the descriptive error for the test */ public String getError(){ return getPropertyAsString(ERROR); } /** * provide a descriptive error for the test method. For * a description of the difference between failure and * error, please refer to the * <a href="http://junit.sourceforge.net/doc/faq/faq.htm#tests_9">junit faq</a> * @param error the description of the error */ public void setError(String error){ setProperty(ERROR,error); } /** * @return the error code for the test method. It should * be an unique error code. */ public String getErrorCode(){ return getPropertyAsString(ERRORCODE); } /** * Provide an unique error code for when the test * does not pass the assert test. * @param code unique error code */ public void setErrorCode(String code){ setProperty(ERRORCODE,code); } /** * @return the comma separated string for the filter */ public String getFilterString(){ return getPropertyAsString(FILTER); } /** * set the filter string in comma separated format * @param text comma separated filter */ public void setFilterString(String text){ setProperty(FILTER,text); } /** * if the sample shouldn't call setup/teardown, the * method returns true. It's meant for onetimesetup * and onetimeteardown. * * @return flag whether setup/teardown methods should not be called */ public boolean getDoNotSetUpTearDown(){ return getPropertyAsBoolean(DOSETUP); } /** * set the setup/teardown option * * @param setup flag whether the setup/teardown methods should not be called */ public void setDoNotSetUpTearDown(boolean setup){ setProperty(DOSETUP,String.valueOf(setup)); } /** * If append error is not set, by default it is set to false, * which means users have to explicitly set the sampler to * append the assert errors. Because of how junit works, there * should only be one error * * @return flag whether errors should be appended */ public boolean getAppendError() { return getPropertyAsBoolean(APPEND_ERROR,false); } /** * Set whether to append errors or not. * * @param error the setting to apply */ public void setAppendError(boolean error) { setProperty(APPEND_ERROR,String.valueOf(error)); } /** * If append exception is not set, by default it is set to <code>false</code>. * Users have to explicitly set it to <code>true</code> to see the exceptions * in the result tree. * * @return flag whether exceptions should be appended to the result tree */ public boolean getAppendException() { return getPropertyAsBoolean(APPEND_EXCEPTION,false); } /** * Set whether to append exceptions or not. * * @param exc the setting to apply. */ public void setAppendException(boolean exc) { setProperty(APPEND_EXCEPTION,String.valueOf(exc)); } /** * Check if JUnit4 (annotations) are to be used instead of * the JUnit3 style (TestClass and specific method names) * * @return true if JUnit4 (annotations) are to be used. * Default is false. */ public boolean getJunit4() { return getPropertyAsBoolean(JUNIT4, false); } /** * Set whether to use JUnit4 style or not. * @param junit4 true if JUnit4 style is to be used. */ public void setJunit4(boolean junit4) { setProperty(JUNIT4, junit4, false); } /** {@inheritDoc} */ @Override public SampleResult sample(Entry entry) { if(getCreateOneInstancePerSample()) { initializeTestObject(); } SampleResult sresult = new SampleResult(); sresult.setSampleLabel(getName());// Bug 41522 - don't use rlabel here sresult.setSamplerData(className + "." + methodName); sresult.setDataType(SampleResult.TEXT); // Assume success sresult.setSuccessful(true); sresult.setResponseMessage(getSuccess()); sresult.setResponseCode(getSuccessCode()); if (this.testCase != null){ // create a new TestResult TestResult tr = new TestResult(); final TestCase theClazz = this.testCase; try { if (setUpMethod != null){ setUpMethod.invoke(this.testObject,new Object[0]); } sresult.sampleStart(); tr.startTest(this.testCase); // Do not use TestCase.run(TestResult) method, since it will // call setUp and tearDown. Doing that will result in calling // the setUp and tearDown method twice and the elapsed time // will include setup and teardown. tr.runProtected(theClazz, protectable); tr.endTest(this.testCase); sresult.sampleEnd(); if (tearDownMethod != null){ tearDownMethod.invoke(testObject,new Object[0]); } } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof AssertionFailedError){ tr.addFailure(theClazz, (AssertionFailedError) cause); } else if (cause instanceof AssertionError) { // Convert JUnit4 failure to Junit3 style AssertionFailedError afe = new AssertionFailedError(cause.toString()); // copy the original stack trace afe.setStackTrace(cause.getStackTrace()); tr.addFailure(theClazz, afe); } else if (cause != null) { tr.addError(theClazz, cause); log.warn("caught exception", e); } else { tr.addError(theClazz, e); log.warn("caught exception", e); } } catch (IllegalAccessException | IllegalArgumentException e) { tr.addError(theClazz, e); } if ( !tr.wasSuccessful() ){ sresult.setSuccessful(false); StringBuilder buf = new StringBuilder(); StringBuilder buftrace = new StringBuilder(); Enumeration<TestFailure> en; if (getAppendError()) { en = tr.failures(); if (en.hasMoreElements()){ sresult.setResponseCode(getFailureCode()); buf.append( getFailure() ); buf.append("\n"); } while (en.hasMoreElements()){ TestFailure item = en.nextElement(); buf.append( "Failure -- "); buf.append( item.toString() ); buf.append("\n"); buftrace.append( "Failure -- "); buftrace.append( item.toString() ); buftrace.append("\n"); buftrace.append( "Trace -- "); buftrace.append( item.trace() ); } en = tr.errors(); if (en.hasMoreElements()){ sresult.setResponseCode(getErrorCode()); buf.append( getError() ); buf.append("\n"); } while (en.hasMoreElements()){ TestFailure item = en.nextElement(); buf.append( "Error -- "); buf.append( item.toString() ); buf.append("\n"); buftrace.append( "Error -- "); buftrace.append( item.toString() ); buftrace.append("\n"); buftrace.append( "Trace -- "); buftrace.append( item.trace() ); } } sresult.setResponseMessage(buf.toString()); sresult.setResponseData(buftrace.toString(), null); } } else { // we should log a warning, but allow the test to keep running sresult.setSuccessful(false); // this should be externalized to the properties sresult.setResponseMessage("Failed to create an instance of the class:"+getClassname() +", reasons may be missing both empty constructor and one " + "String constructor or failure to instantiate constructor," + " check warning messages in jmeter log file"); sresult.setResponseCode(getErrorCode()); } return sresult; } /** * If the method is not able to create a new instance of the * class, it returns null and logs all the exceptions at * warning level. */ private static Object getClassInstance(String className, String label){ Object testclass = null; if (className != null){ Constructor<?> con = null; Constructor<?> strCon = null; Class<?> theclazz = null; Object[] strParams = null; Object[] params = null; try { theclazz = Thread.currentThread().getContextClassLoader().loadClass(className.trim()); } catch (ClassNotFoundException e) { log.warn("ClassNotFoundException:: {}", e.getMessage()); } if (theclazz != null) { // first we see if the class declares a string // constructor. if it is doesn't we look for // empty constructor. try { strCon = theclazz.getDeclaredConstructor( new Class[] {String.class}); // we have to check and make sure the constructor is // accessible. if we didn't it would throw an exception // and cause a NPE. if (label == null || label.length() == 0) { label = className; } if (strCon.getModifiers() == Modifier.PUBLIC) { strParams = new Object[]{label}; } else { strCon = null; } } catch (NoSuchMethodException e) { log.info("Trying to find constructor with one String parameter returned error: {}", e.getMessage()); } try { con = theclazz.getDeclaredConstructor(new Class[0]); if (con != null){ params = new Object[]{}; } } catch (NoSuchMethodException e) { log.info("Trying to find empty constructor returned error: {}", e.getMessage()); } try { // if the string constructor is not null, we use it. // if the string constructor is null, we use the empty // constructor to get a new instance if (strCon != null) { testclass = strCon.newInstance(strParams); } else if (con != null){ testclass = con.newInstance(params); } else { log.error("No empty constructor nor string constructor found for class:{}", theclazz); } } catch (InvocationTargetException | IllegalAccessException | InstantiationException e) { log.error("Error instantiating class:{}:{}", theclazz, e.getMessage(), e); } } } return testclass; } /** * Get a method. * @param clazz the classname (may be null) * @param method the method name (may be null) * @return the method or null if an error occurred * (or either parameter is null) */ private Method getMethod(Object clazz, String method){ if (clazz != null && method != null){ try { return clazz.getClass().getMethod(method,new Class[0]); } catch (NoSuchMethodException e) { log.warn(e.getMessage()); } } return null; } private Method getMethodWithAnnotation(Object clazz, Class<? extends Annotation> annotation) { if(null != clazz && null != annotation) { for(Method m : clazz.getClass().getMethods()) { if(m.isAnnotationPresent(annotation)) { return m; } } } return null; } /* * Wrapper to convert a JUnit4 class into a TestCase * * TODO - work out how to convert JUnit4 assertions so they are treated as failures rather than errors */ private class AnnotatedTestCase extends TestCase { private final Method method; private final Class<? extends Throwable> expectedException; private final long timeout; public AnnotatedTestCase(Method method, Class<? extends Throwable> expectedException2, long timeout) { this.method = method; this.expectedException = expectedException2; this.timeout = timeout; } @Override protected void runTest() throws Throwable { try { long start = System.currentTimeMillis(); method.invoke(testObject, (Object[])null); if (expectedException != None.class) { throw new AssertionFailedError( "No error was generated for a test case which specifies an error."); } if (timeout > 0){ long elapsed = System.currentTimeMillis() - start; if (elapsed > timeout) { throw new AssertionFailedError("Test took longer than the specified timeout."); } } } catch (InvocationTargetException e) { Throwable thrown = e.getCause(); if (thrown == null) { // probably should not happen throw e; } if (expectedException == None.class){ // Convert JUnit4 AssertionError failures to JUnit3 style so // will be treated as failure rather than error. if (thrown instanceof AssertionError && !(thrown instanceof AssertionFailedError)){ AssertionFailedError afe = new AssertionFailedError(thrown.toString()); // copy the original stack trace afe.setStackTrace(thrown.getStackTrace()); throw afe; } throw thrown; } if (!expectedException.isAssignableFrom(thrown.getClass())){ throw new AssertionFailedError("The wrong exception was thrown from the test case"); } } } } @Override public void threadFinished() { } /** * Set up all variables that don't change between samples. */ @Override public void threadStarted() { testObject = null; testCase = null; methodName = getMethod(); className = getClassname(); protectable = null; if(!getCreateOneInstancePerSample()) { // NO NEED TO INITIALIZE WHEN getCreateOneInstancePerSample // is true cause it will be done in sample initializeTestObject(); } } /** * Initialize test object */ private void initializeTestObject() { String rlabel = getConstructorString(); if (rlabel.length()== 0) { rlabel = JUnitSampler.class.getName(); } this.testObject = getClassInstance(className, rlabel); if (this.testObject != null){ initMethodObjects(this.testObject); final Method m = getMethod(this.testObject,methodName); if (getJunit4()){ Class<? extends Throwable> expectedException = None.class; long timeout = 0; Test annotation = m.getAnnotation(Test.class); if(null != annotation) { expectedException = annotation.expected(); timeout = annotation.timeout(); } final AnnotatedTestCase at = new AnnotatedTestCase(m, expectedException, timeout); testCase = at; protectable = new Protectable() { @Override public void protect() throws Throwable { at.runTest(); } }; } else { this.testCase = (TestCase) this.testObject; final Object theClazz = this.testObject; // Must be final to create instance protectable = new Protectable() { @Override public void protect() throws Throwable { try { m.invoke(theClazz,new Object[0]); } catch (InvocationTargetException e) { /* * Calling a method via reflection results in wrapping any * Exceptions in ITE; unwrap these here so runProtected can * allocate them correctly. */ Throwable t = e.getCause(); if (t != null) { throw t; } throw e; } } }; } if (this.testCase != null){ this.testCase.setName(methodName); } } } /** * * @param createOneInstancePerSample * flag whether a new instance for each call should be created */ public void setCreateOneInstancePerSample(boolean createOneInstancePerSample) { this.setProperty(CREATE_INSTANCE_PER_SAMPLE, createOneInstancePerSample, CREATE_INSTANCE_PER_SAMPLE_DEFAULT); } /** * * @return boolean create New Instance For Each Call */ public boolean getCreateOneInstancePerSample() { return getPropertyAsBoolean(CREATE_INSTANCE_PER_SAMPLE, CREATE_INSTANCE_PER_SAMPLE_DEFAULT); } }
Log assertion errors with a lower criticality Part of #376 on github git-svn-id: 5ccfe34f605a6c2f9041ff2965ab60012c62539a@1824658 13f79535-47bb-0310-9956-ffa450edef68
src/junit/org/apache/jmeter/protocol/java/sampler/JUnitSampler.java
Log assertion errors with a lower criticality
<ide><path>rc/junit/org/apache/jmeter/protocol/java/sampler/JUnitSampler.java <ide> tr.addFailure(theClazz, afe); <ide> } else if (cause != null) { <ide> tr.addError(theClazz, cause); <del> log.warn("caught exception", e); <add> log.info("caught exception", e); <ide> } else { <ide> tr.addError(theClazz, e); <del> log.warn("caught exception", e); <add> log.info("caught exception", e); <ide> } <ide> } catch (IllegalAccessException | IllegalArgumentException e) { <ide> tr.addError(theClazz, e);
Java
apache-2.0
6cd0bc56170499b9b47aa4b5d508a587384b6bcb
0
googlegenomics/dataflow-java,deflaux/dataflow-java,deflaux/dataflow-java,googlegenomics/dataflow-java,jakeakopp/dataflow-java,deflaux/dataflow-java,jakeakopp/dataflow-java,googlegenomics/dataflow-java
/* * Copyright (C) 2015 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.cloud.genomics.dataflow.pipelines; import com.google.api.client.util.Strings; import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.io.TextIO; import com.google.cloud.dataflow.sdk.options.Default; import com.google.cloud.dataflow.sdk.options.Description; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.Filter; import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.transforms.Sample; import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; import com.google.cloud.dataflow.sdk.transforms.View; import com.google.cloud.dataflow.sdk.transforms.join.CoGbkResult; import com.google.cloud.dataflow.sdk.transforms.join.CoGroupByKey; import com.google.cloud.dataflow.sdk.transforms.join.KeyedPCollectionTuple; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollectionView; import com.google.cloud.dataflow.sdk.values.TupleTag; import com.google.cloud.genomics.dataflow.coders.GenericJsonCoder; import com.google.cloud.genomics.dataflow.functions.VariantFunctions; import com.google.cloud.genomics.dataflow.functions.verifybamid.LikelihoodFn; import com.google.cloud.genomics.dataflow.functions.verifybamid.ReadFunctions; import com.google.cloud.genomics.dataflow.functions.verifybamid.Solver; import com.google.cloud.genomics.dataflow.model.AlleleFreq; import com.google.cloud.genomics.dataflow.model.ReadBaseQuality; import com.google.cloud.genomics.dataflow.model.ReadBaseWithReference; import com.google.cloud.genomics.dataflow.model.ReadCounts; import com.google.cloud.genomics.dataflow.model.ReadQualityCount; import com.google.cloud.genomics.dataflow.pipelines.CalculateCoverage.CheckMatchingReferenceSet; import com.google.cloud.genomics.dataflow.readers.ReadGroupStreamer; import com.google.cloud.genomics.dataflow.readers.VariantStreamer; import com.google.cloud.genomics.dataflow.utils.CallSetNamesOptions; import com.google.cloud.genomics.dataflow.utils.GCSOutputOptions; import com.google.cloud.genomics.dataflow.utils.GenomicsOptions; import com.google.cloud.genomics.dataflow.utils.ShardOptions; import com.google.cloud.genomics.utils.GenomicsUtils; import com.google.cloud.genomics.utils.OfflineAuth; import com.google.cloud.genomics.utils.ShardBoundary; import com.google.cloud.genomics.utils.ShardUtils; import com.google.cloud.genomics.utils.ShardUtils.SexChromosomeFilter; import com.google.common.collect.ImmutableMultiset; import com.google.common.collect.Lists; import com.google.common.collect.Multiset; import com.google.genomics.v1.Position; import com.google.genomics.v1.Read; import com.google.genomics.v1.StreamVariantsRequest; import com.google.genomics.v1.Variant; import com.google.protobuf.ListValue; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.List; import java.util.logging.Logger; import java.util.Map; import java.util.Vector; /** * Test a set of reads for contamination. * * Takes a set of specified ReadGroupSets of reads to test and statistics on reference allele * frequencies for SNPs with a single alternative from a specified set of VariantSets. * * See http://googlegenomics.readthedocs.org/en/latest/use_cases/perform_quality_control_checks/verify_bam_id.html * for running instructions. * * Uses the sequence data alone approach described in: * G. Jun, M. Flickinger, K. N. Hetrick, Kurt, J. M. Romm, K. F. Doheny, * G. Abecasis, M. Boehnke,and H. M. Kang, Detecting and Estimating * Contamination of Human DNA Samples in Sequencing and Array-Based Genotype * Data, American journal of human genetics doi:10.1016/j.ajhg.2012.09.004 * (volume 91 issue 5 pp.839 - 848) * http://www.sciencedirect.com/science/article/pii/S0002929712004788 */ public class VerifyBamId { private static final Logger LOG = Logger.getLogger(VerifyBamId.class.getName()); /** * Options required to run this pipeline. */ public static interface Options extends // Options for call set names. CallSetNamesOptions, // Options for calculating over regions, chromosomes, or whole genomes. ShardOptions, // Options for the output destination. GCSOutputOptions { @Description("A comma delimited list of the IDs of the Google Genomics ReadGroupSets this " + "pipeline is working with. Default (empty) indicates all ReadGroupSets in InputDatasetId." + " This or InputDatasetId must be set. InputDatasetId overrides " + "ReadGroupSetIds (if InputDatasetId is set, this field will be ignored).") @Default.String("") String getReadGroupSetIds(); void setReadGroupSetIds(String readGroupSetId); @Description("The ID of the Google Genomics Dataset that the pipeline will get its input reads" + " from. Default (empty) means to use ReadGroupSetIds and VariantSetIds instead. This or" + " ReadGroupSetIds and VariantSetIds must be set. InputDatasetId overrides" + " ReadGroupSetIds and VariantSetIds (if this field is set, ReadGroupSetIds and" + " VariantSetIds will be ignored).") @Default.String("") String getInputDatasetId(); void setInputDatasetId(String inputDatasetId); public String DEFAULT_VARIANTSET = "10473108253681171589"; @Override @Description("The ID of the Google Genomics VariantSet this pipeline is working with." + " It assumes the variant set has INFO field 'AF' from which it retrieves the" + " allele frequency for the variant, such as 1,000 Genomes phase 1 or phase 3 variants." + " Defaults to the 1,000 Genomes phase 1 VariantSet with id " + DEFAULT_VARIANTSET + ".") @Default.String(DEFAULT_VARIANTSET) String getVariantSetId(); void setVariantSetId(String variantSetId); @Description("The minimum allele frequency to use in analysis. Defaults to 0.01.") @Default.Double(0.01) double getMinFrequency(); void setMinFrequency(double minFrequency); @Description("The fraction of positions to check. Defaults to 0.01.") @Default.Double(0.01) double getSamplingFraction(); void setSamplingFraction(double minFrequency); public static class Methods { public static void validateOptions(Options options) { GCSOutputOptions.Methods.validateOptions(options); } } } private static Pipeline p; private static Options pipelineOptions; private static OfflineAuth auth; /** * String prefix used for sampling hash function */ private static final String HASH_PREFIX = ""; // Tip: Use the API explorer to test which fields to include in partial responses. // https://developers.google.com/apis-explorer/#p/genomics/v1/genomics.variants.stream?fields=variants(alternateBases%252Ccalls(callSetName%252Cgenotype)%252CreferenceBases)&_h=3&resource=%257B%250A++%2522variantSetId%2522%253A+%25223049512673186936334%2522%252C%250A++%2522referenceName%2522%253A+%2522chr17%2522%252C%250A++%2522start%2522%253A+%252241196311%2522%252C%250A++%2522end%2522%253A+%252241196312%2522%252C%250A++%2522callSetIds%2522%253A+%250A++%255B%25223049512673186936334-0%2522%250A++%255D%250A%257D& private static final String VARIANT_FIELDS = "variants(alternateBases,filter,info,quality,referenceBases,referenceName,start)"; /** * Run the VerifyBamId algorithm and output the resulting contamination estimate. */ public static void main(String[] args) throws GeneralSecurityException, IOException { LOG.info("Starting VerfyBamId"); // Register the options so that they show up via --help PipelineOptionsFactory.register(Options.class); pipelineOptions = PipelineOptionsFactory.fromArgs(args) .withValidation().as(Options.class); // Option validation is not yet automatic, we make an explicit call here. Options.Methods.validateOptions(pipelineOptions); // Set up the prototype request and auth. StreamVariantsRequest prototype = CallSetNamesOptions.Methods.getRequestPrototype(pipelineOptions); auth = GenomicsOptions.Methods.getGenomicsAuth(pipelineOptions); p = Pipeline.create(pipelineOptions); p.getCoderRegistry().setFallbackCoderProvider(GenericJsonCoder.PROVIDER); if (pipelineOptions.getInputDatasetId().isEmpty() && pipelineOptions.getReadGroupSetIds().isEmpty()) { throw new IllegalArgumentException("InputDatasetId or ReadGroupSetIds must be specified"); } List<String> rgsIds; if (pipelineOptions.getInputDatasetId().isEmpty()) { rgsIds = Lists.newArrayList(pipelineOptions.getReadGroupSetIds().split(",")); } else { rgsIds = GenomicsUtils.getReadGroupSetIds(pipelineOptions.getInputDatasetId(), auth); } // Grab one ReferenceSetId to be used within the pipeline to confirm that all ReadGroupSets // are associated with the same ReferenceSet. String referenceSetId = GenomicsUtils.getReferenceSetId(rgsIds.get(0), auth); if (Strings.isNullOrEmpty(referenceSetId)) { throw new IllegalArgumentException("No ReferenceSetId associated with ReadGroupSetId " + rgsIds.get(0) + ". All ReadGroupSets in given input must have an associated ReferenceSet."); } // TODO: confirm that variant set also corresponds to the same reference // https://github.com/googlegenomics/api-client-java/issues/66 // Reads in Reads. PCollection<Read> reads = p.begin() .apply(Create.of(rgsIds)) .apply(ParDo.of(new CheckMatchingReferenceSet(referenceSetId, auth))) .apply(new ReadGroupStreamer(auth, ShardBoundary.Requirement.STRICT, null, SexChromosomeFilter.INCLUDE_XY)); /* TODO: We can reduce the number of requests needed to be created by doing the following: 1. Stream the Variants first (rather than concurrently with the Reads). Select a subset of them equal to some threshold (say 50K by default). 2. Create the requests for streaming Reads by running a ParDo over the selected Variants to get their ranges (we only need to stream Reads that overlap the selected Variants). 3. Stream the Reads from the created requests. */ // Reads in Variants. TODO potentially provide an option to load the Variants from a file. List<StreamVariantsRequest> variantRequests = pipelineOptions.isAllReferences() ? ShardUtils.getVariantRequests(prototype, ShardUtils.SexChromosomeFilter.INCLUDE_XY, pipelineOptions.getBasesPerShard(), auth) : ShardUtils.getVariantRequests(prototype, pipelineOptions.getBasesPerShard(), pipelineOptions.getReferences()); PCollection<Variant> variants = p.apply(Create.of(variantRequests)) .apply(new VariantStreamer(auth, ShardBoundary.Requirement.STRICT, VARIANT_FIELDS)); PCollection<KV<Position, AlleleFreq>> refFreq = getFreq(variants, pipelineOptions.getMinFrequency()); PCollection<KV<Position, ReadCounts>> readCountsTable = combineReads(reads, pipelineOptions.getSamplingFraction(), HASH_PREFIX, refFreq); // Converts our results to a single Map of Position keys to ReadCounts values. PCollectionView<Map<Position, ReadCounts>> view = readCountsTable .apply(View.<Position, ReadCounts>asMap()); // Calculates the contamination estimate based on the resulting Map above. PCollection<String> result = p.begin() .apply(Create.of("")) .apply(ParDo.of(new Maximizer(view)).withSideInputs(view)); // Writes the result to the given output location in Cloud Storage. result.apply(TextIO.Write.to(pipelineOptions.getOutput()).named("WriteOutput").withoutSharding()); p.run(); } /** * Compute a PCollection of reference allele frequencies for SNPs of interest. * The SNPs all have only a single alternate allele, and neither the * reference nor the alternate allele have a population frequency < minFreq. * The results are returned in a PCollection indexed by Position. * * @param variants a set of variant calls for a reference population * @param minFreq the minimum allele frequency for the set * @return a PCollection mapping Position to AlleleCounts */ static PCollection<KV<Position, AlleleFreq>> getFreq( PCollection<Variant> variants, double minFreq) { return variants.apply(Filter.byPredicate(VariantFunctions.IS_PASSING).named("PassingFilter")) .apply(Filter.byPredicate(VariantFunctions.IS_ON_CHROMOSOME).named("OnChromosomeFilter")) .apply(Filter.byPredicate(VariantFunctions.IS_NOT_LOW_QUALITY).named("NotLowQualityFilter")) .apply(Filter.byPredicate(VariantFunctions.IS_SINGLE_ALTERNATE_SNP).named("SNPFilter")) .apply(ParDo.of(new GetAlleleFreq())) .apply(Filter.byPredicate(new FilterFreq(minFreq))); } /** * Filter, pile up, and sample reads, then join against reference statistics. * * @param reads A PCollection of reads * @param samplingFraction Fraction of reads to keep * @param samplingPrefix A prefix used in generating hashes used in sampling * @param refCounts A PCollection mapping position to counts of alleles in * a reference population. * @return A PCollection mapping Position to a ReadCounts proto */ static PCollection<KV<Position, ReadCounts>> combineReads(PCollection<Read> reads, double samplingFraction, String samplingPrefix, PCollection<KV<Position, AlleleFreq>> refFreq) { // Runs filters on input Reads, splits into individual aligned bases (emitting the // base and quality) and grabs a sample of them based on a hash mod of Position. PCollection<KV<Position, ReadBaseQuality>> joinReadCounts = reads.apply(Filter.byPredicate(ReadFunctions.IS_ON_CHROMOSOME).named("IsOnChromosome")) .apply(Filter.byPredicate(ReadFunctions.IS_NOT_QC_FAILURE).named("IsNotQCFailure")) .apply(Filter.byPredicate(ReadFunctions.IS_NOT_DUPLICATE).named("IsNotDuplicate")) .apply(Filter.byPredicate(ReadFunctions.IS_PROPER_PLACEMENT).named("IsProperPlacement")) .apply(ParDo.of(new SplitReads())) .apply(Filter.byPredicate(new SampleReads(samplingFraction, samplingPrefix))); TupleTag<ReadBaseQuality> readCountsTag = new TupleTag<>(); TupleTag<AlleleFreq> refFreqTag = new TupleTag<>(); // Pile up read counts, then join against reference stats. PCollection<KV<Position, CoGbkResult>> joined = KeyedPCollectionTuple .of(readCountsTag, joinReadCounts) .and(refFreqTag, refFreq) .apply(CoGroupByKey.<Position>create()); return joined.apply(ParDo.of(new PileupAndJoinReads(readCountsTag, refFreqTag))); } /** * Split reads into individual aligned bases and emit base + quality. */ static class SplitReads extends DoFn<Read, KV<Position, ReadBaseQuality>> { @Override public void processElement(ProcessContext c) throws Exception { List<ReadBaseWithReference> readBases = ReadFunctions.extractReadBases(c.element()); if (!readBases.isEmpty()) { for (ReadBaseWithReference rb : readBases) { c.output(KV.of(rb.getRefPosition(), rb.getRbq())); } } } } /** * Sample bases via a hash mod of position. */ static class SampleReads implements SerializableFunction<KV<Position, ReadBaseQuality>, Boolean> { private final double samplingFraction; private final String samplingPrefix; public SampleReads(double samplingFraction, String samplingPrefix) { this.samplingFraction = samplingFraction; this.samplingPrefix = samplingPrefix; } @Override public Boolean apply(KV<Position, ReadBaseQuality> input) { if (samplingFraction == 1.0) { return true; } else { byte[] msg; Position position = input.getKey(); try { msg = (samplingPrefix + position.getReferenceName() + ":" + position.getPosition() + ":" + position.getReverseStrand()).getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new AssertionError("UTF-8 not available - should not happen"); } MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new AssertionError("MD5 not available - should not happen"); } byte[] digest = md.digest(msg); if (digest.length != 16) { throw new AssertionError("MD5 should return 128 bits"); } ByteBuffer buffer = ByteBuffer.allocate(Long.SIZE); buffer.put(Arrays.copyOf(digest, Long.SIZE)); return ((((double) buffer.getLong(0) / (double) ((long) 1 << 63)) + 1.0) * 0.5) < samplingFraction; } } } /** * Map a variant to a Position, AlleleFreq pair. */ static class GetAlleleFreq extends DoFn<Variant, KV<Position, AlleleFreq>> { @Override public void processElement(ProcessContext c) throws Exception { ListValue lv = c.element().getInfo().get("AF"); if (lv != null && lv.getValuesCount() > 0) { Position position = Position.newBuilder() .setPosition(c.element().getStart()) .setReferenceName(c.element().getReferenceName()) .build(); AlleleFreq af = new AlleleFreq(); af.setRefFreq(Double.parseDouble(lv.getValues(0).getStringValue())); af.setAltBases(c.element().getAlternateBasesList()); af.setRefBases(c.element().getReferenceBases()); c.output(KV.of(position, af)); } else { // AF field wasn't populated in info, so we don't have frequency information // for this Variant. // TODO instead of straight throwing an exception, log a warning. If at the end of this // step the number of AlleleFreqs retrieved is below a given threshold, then throw an // exception. throw new IllegalArgumentException("Variant " + c.element().getId() + " does not have " + "allele frequency information stored in INFO field AF."); } } } /** * Filters out AlleleFreqs for which the reference or alternate allele * frequencies are below a minimum specified at construction. */ static class FilterFreq implements SerializableFunction<KV<Position, AlleleFreq>, Boolean> { private final double minFreq; public FilterFreq(double minFreq) { this.minFreq = minFreq; } @Override public Boolean apply(KV<Position, AlleleFreq> input) { double freq = input.getValue().getRefFreq(); if (freq >= minFreq && (1.0 - freq) >= minFreq) { return true; } return false; } } /** * Piles up reads and joins them against reference population statistics. */ static class PileupAndJoinReads extends DoFn<KV<Position, CoGbkResult>, KV<Position, ReadCounts>> { private final TupleTag<ReadBaseQuality> readCountsTag; private final TupleTag<AlleleFreq> refFreqTag; public PileupAndJoinReads(TupleTag<ReadBaseQuality> readCountsTag, TupleTag<AlleleFreq> refFreqTag) { this.readCountsTag = readCountsTag; this.refFreqTag = refFreqTag; } @Override public void processElement(ProcessContext c) throws Exception { AlleleFreq af = null; af = c.element().getValue().getOnly(refFreqTag, null); if (af == null || af.getAltBases() == null) { // no ref stats return; } if (af.getAltBases().size() != 1) { throw new IllegalArgumentException("Wrong number (" + af.getAltBases().size() + ") of" + " alternate bases for Position " + c.element().getKey()); } Iterable<ReadBaseQuality> reads = c.element().getValue().getAll(readCountsTag); ImmutableMultiset.Builder<ReadQualityCount> rqSetBuilder = ImmutableMultiset.builder(); for (ReadBaseQuality r : reads) { ReadQualityCount.Base b; if (af.getRefBases().equals(r.getBase())) { b = ReadQualityCount.Base.REF; } else if (af.getAltBases().get(0).equals(r.getBase())) { b = ReadQualityCount.Base.NONREF; } else { b = ReadQualityCount.Base.OTHER; } ReadQualityCount rqc = new ReadQualityCount(); rqc.setBase(b); rqc.setQuality(r.getQuality()); rqSetBuilder.add(rqc); } ReadCounts rc = new ReadCounts(); rc.setRefFreq(af.getRefFreq()); for (Multiset.Entry<ReadQualityCount> entry : rqSetBuilder.build().entrySet()) { ReadQualityCount rq = entry.getElement(); rq.setCount(entry.getCount()); rc.addReadQualityCount(rq); } c.output(KV.of(c.element().getKey(), rc)); } } /** * Calls the Solver to maximize via a univariate function the results of the pipeline, inputted * as a PCollectionView (the best way to retrieve our results as a Map in Dataflow). */ static class Maximizer extends DoFn<Object, String> { private final PCollectionView<Map<Position, ReadCounts>> view; // Target absolute error for Brent's algorithm private static final double ABS_ERR = 0.00001; // Target relative error for Brent's algorithm private static final double REL_ERR = 0.0001; // Maximum number of evaluations of the Likelihood function in Brent's algorithm private static final int MAX_EVAL = 1000; // Maximum number of iterations of Brent's algorithm private static final int MAX_ITER = 1000; // Grid search step size private static final double GRID_STEP = 0.001; public Maximizer(PCollectionView<Map<Position, ReadCounts>> view) { this.view = view; } @Override public void processElement(ProcessContext c) throws Exception { float[] steps = new float[]{0.1f, 0.05f, 0.01f, 0.005f, 0.001f}; for (float step : steps) { c.output(Float.toString(step) + ": " + Double.toString(Solver.maximize(new LikelihoodFn(c.sideInput(view)), 0.0, 0.5, step, REL_ERR, ABS_ERR, MAX_ITER, MAX_EVAL))); } } } }
src/main/java/com/google/cloud/genomics/dataflow/pipelines/VerifyBamId.java
/* * Copyright (C) 2015 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.cloud.genomics.dataflow.pipelines; import com.google.api.client.util.Strings; import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.io.TextIO; import com.google.cloud.dataflow.sdk.options.Default; import com.google.cloud.dataflow.sdk.options.Description; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.Filter; import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.transforms.Sample; import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; import com.google.cloud.dataflow.sdk.transforms.View; import com.google.cloud.dataflow.sdk.transforms.join.CoGbkResult; import com.google.cloud.dataflow.sdk.transforms.join.CoGroupByKey; import com.google.cloud.dataflow.sdk.transforms.join.KeyedPCollectionTuple; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollectionView; import com.google.cloud.dataflow.sdk.values.TupleTag; import com.google.cloud.genomics.dataflow.coders.GenericJsonCoder; import com.google.cloud.genomics.dataflow.functions.VariantFunctions; import com.google.cloud.genomics.dataflow.functions.verifybamid.LikelihoodFn; import com.google.cloud.genomics.dataflow.functions.verifybamid.ReadFunctions; import com.google.cloud.genomics.dataflow.functions.verifybamid.Solver; import com.google.cloud.genomics.dataflow.model.AlleleFreq; import com.google.cloud.genomics.dataflow.model.ReadBaseQuality; import com.google.cloud.genomics.dataflow.model.ReadBaseWithReference; import com.google.cloud.genomics.dataflow.model.ReadCounts; import com.google.cloud.genomics.dataflow.model.ReadQualityCount; import com.google.cloud.genomics.dataflow.pipelines.CalculateCoverage.CheckMatchingReferenceSet; import com.google.cloud.genomics.dataflow.readers.ReadGroupStreamer; import com.google.cloud.genomics.dataflow.readers.VariantStreamer; import com.google.cloud.genomics.dataflow.utils.CallSetNamesOptions; import com.google.cloud.genomics.dataflow.utils.GCSOutputOptions; import com.google.cloud.genomics.dataflow.utils.GenomicsOptions; import com.google.cloud.genomics.dataflow.utils.ShardOptions; import com.google.cloud.genomics.utils.GenomicsUtils; import com.google.cloud.genomics.utils.OfflineAuth; import com.google.cloud.genomics.utils.ShardBoundary; import com.google.cloud.genomics.utils.ShardUtils; import com.google.cloud.genomics.utils.ShardUtils.SexChromosomeFilter; import com.google.common.collect.ImmutableMultiset; import com.google.common.collect.Lists; import com.google.common.collect.Multiset; import com.google.genomics.v1.Position; import com.google.genomics.v1.Read; import com.google.genomics.v1.StreamVariantsRequest; import com.google.genomics.v1.Variant; import com.google.protobuf.ListValue; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.List; import java.util.logging.Logger; import java.util.Map; import java.util.Vector; /** * Test a set of reads for contamination. * * Takes a set of specified ReadGroupSets of reads to test and statistics on reference allele * frequencies for SNPs with a single alternative from a specified set of VariantSets. * * See http://googlegenomics.readthedocs.org/en/latest/use_cases/perform_quality_control_checks/verify_bam_id.html * for running instructions. * * Uses the sequence data alone approach described in: * G. Jun, M. Flickinger, K. N. Hetrick, Kurt, J. M. Romm, K. F. Doheny, * G. Abecasis, M. Boehnke,and H. M. Kang, Detecting and Estimating * Contamination of Human DNA Samples in Sequencing and Array-Based Genotype * Data, American journal of human genetics doi:10.1016/j.ajhg.2012.09.004 * (volume 91 issue 5 pp.839 - 848) * http://www.sciencedirect.com/science/article/pii/S0002929712004788 */ public class VerifyBamId { private static final Logger LOG = Logger.getLogger(VerifyBamId.class.getName()); /** * Options required to run this pipeline. */ public static interface Options extends // Options for call set names. CallSetNamesOptions, // Options for calculating over regions, chromosomes, or whole genomes. ShardOptions, // Options for the output destination. GCSOutputOptions { @Description("A comma delimited list of the IDs of the Google Genomics ReadGroupSets this " + "pipeline is working with. Default (empty) indicates all ReadGroupSets in InputDatasetId." + " This or InputDatasetId must be set. InputDatasetId overrides " + "ReadGroupSetIds (if InputDatasetId is set, this field will be ignored).") @Default.String("") String getReadGroupSetIds(); void setReadGroupSetIds(String readGroupSetId); @Description("The ID of the Google Genomics Dataset that the pipeline will get its input reads" + " from. Default (empty) means to use ReadGroupSetIds and VariantSetIds instead. This or" + " ReadGroupSetIds and VariantSetIds must be set. InputDatasetId overrides" + " ReadGroupSetIds and VariantSetIds (if this field is set, ReadGroupSetIds and" + " VariantSetIds will be ignored).") @Default.String("") String getInputDatasetId(); void setInputDatasetId(String inputDatasetId); public String DEFAULT_VARIANTSET = "10473108253681171589"; @Override @Description("The ID of the Google Genomics VariantSet this pipeline is working with." + " It assumes the variant set has INFO field 'AF' from which it retrieves the" + " allele frequency for the variant, such as 1,000 Genomes phase 1 or phase 3 variants." + " Defaults to the 1,000 Genomes phase 1 VariantSet with id " + DEFAULT_VARIANTSET + ".") @Default.String(DEFAULT_VARIANTSET) String getVariantSetId(); void setVariantSetId(String variantSetId); @Description("The minimum allele frequency to use in analysis. Defaults to 0.01.") @Default.Double(0.01) double getMinFrequency(); void setMinFrequency(double minFrequency); @Description("The fraction of positions to check. Defaults to 0.01.") @Default.Double(0.01) double getSamplingFraction(); void setSamplingFraction(double minFrequency); public static class Methods { public static void validateOptions(Options options) { GCSOutputOptions.Methods.validateOptions(options); } } } private static Pipeline p; private static Options pipelineOptions; private static OfflineAuth auth; /** * String prefix used for sampling hash function */ private static final String HASH_PREFIX = ""; // Tip: Use the API explorer to test which fields to include in partial responses. // https://developers.google.com/apis-explorer/#p/genomics/v1/genomics.variants.stream?fields=variants(alternateBases%252Ccalls(callSetName%252Cgenotype)%252CreferenceBases)&_h=3&resource=%257B%250A++%2522variantSetId%2522%253A+%25223049512673186936334%2522%252C%250A++%2522referenceName%2522%253A+%2522chr17%2522%252C%250A++%2522start%2522%253A+%252241196311%2522%252C%250A++%2522end%2522%253A+%252241196312%2522%252C%250A++%2522callSetIds%2522%253A+%250A++%255B%25223049512673186936334-0%2522%250A++%255D%250A%257D& private static final String VARIANT_FIELDS = "variants(alternateBases,filter,info,quality,referenceBases,referenceName,start)"; /** * Run the VerifyBamId algorithm and output the resulting contamination estimate. */ public static void main(String[] args) throws GeneralSecurityException, IOException { LOG.info("Starting VerfyBamId"); // Register the options so that they show up via --help PipelineOptionsFactory.register(Options.class); pipelineOptions = PipelineOptionsFactory.fromArgs(args) .withValidation().as(Options.class); // Option validation is not yet automatic, we make an explicit call here. Options.Methods.validateOptions(pipelineOptions); // Set up the prototype request and auth. StreamVariantsRequest prototype = CallSetNamesOptions.Methods.getRequestPrototype(pipelineOptions); auth = GenomicsOptions.Methods.getGenomicsAuth(pipelineOptions); p = Pipeline.create(pipelineOptions); p.getCoderRegistry().setFallbackCoderProvider(GenericJsonCoder.PROVIDER); if (pipelineOptions.getInputDatasetId().isEmpty() && pipelineOptions.getReadGroupSetIds().isEmpty()) { throw new IllegalArgumentException("InputDatasetId or ReadGroupSetIds must be specified"); } List<String> rgsIds; if (pipelineOptions.getInputDatasetId().isEmpty()) { rgsIds = Lists.newArrayList(pipelineOptions.getReadGroupSetIds().split(",")); } else { rgsIds = GenomicsUtils.getReadGroupSetIds(pipelineOptions.getInputDatasetId(), auth); } // Grab one ReferenceSetId to be used within the pipeline to confirm that all ReadGroupSets // are associated with the same ReferenceSet. String referenceSetId = GenomicsUtils.getReferenceSetId(rgsIds.get(0), auth); if (Strings.isNullOrEmpty(referenceSetId)) { throw new IllegalArgumentException("No ReferenceSetId associated with ReadGroupSetId " + rgsIds.get(0) + ". All ReadGroupSets in given input must have an associated ReferenceSet."); } // TODO: confirm that variant set also corresponds to the same reference // https://github.com/googlegenomics/api-client-java/issues/66 // Reads in Reads. PCollection<Read> reads = p.begin() .apply(Create.of(rgsIds)) .apply(ParDo.of(new CheckMatchingReferenceSet(referenceSetId, auth))) .apply(new ReadGroupStreamer(auth, ShardBoundary.Requirement.STRICT, null, SexChromosomeFilter.INCLUDE_XY)); /* TODO: We can reduce the number of requests needed to be created by doing the following: 1. Stream the Variants first (rather than concurrently with the Reads). Select a subset of them equal to some threshold (say 50K by default). 2. Create the requests for streaming Reads by running a ParDo over the selected Variants to get their ranges (we only need to stream Reads that overlap the selected Variants). 3. Stream the Reads from the created requests. */ // Reads in Variants. TODO potentially provide an option to load the Variants from a file. List<StreamVariantsRequest> variantRequests = pipelineOptions.isAllReferences() ? ShardUtils.getVariantRequests(prototype, ShardUtils.SexChromosomeFilter.INCLUDE_XY, pipelineOptions.getBasesPerShard(), auth) : ShardUtils.getVariantRequests(prototype, pipelineOptions.getBasesPerShard(), pipelineOptions.getReferences()); PCollection<Variant> variants = p.apply(Create.of(variantRequests)) .apply(new VariantStreamer(auth, ShardBoundary.Requirement.STRICT, VARIANT_FIELDS)); PCollection<KV<Position, AlleleFreq>> refFreq = getFreq(variants, pipelineOptions.getMinFrequency()); PCollection<KV<Position, ReadCounts>> readCountsTable = combineReads(reads, pipelineOptions.getSamplingFraction(), HASH_PREFIX, refFreq); // Converts our results to a single Map of Position keys to ReadCounts values. PCollectionView<Map<Position, ReadCounts>> view = readCountsTable .apply(View.<Position, ReadCounts>asMap()); // Calculates the contamination estimate based on the resulting Map above. PCollection<String> result = p.begin() .apply(Create.of("")) .apply(ParDo.of(new Maximizer(view)).withSideInputs(view)); // Writes the result to the given output location in Cloud Storage. result.apply(TextIO.Write.to(pipelineOptions.getOutput()).named("WriteOutput").withoutSharding()); p.run(); } /** * Compute a PCollection of reference allele frequencies for SNPs of interest. * The SNPs all have only a single alternate allele, and neither the * reference nor the alternate allele have a population frequency < minFreq. * The results are returned in a PCollection indexed by Position. * * @param variants a set of variant calls for a reference population * @param minFreq the minimum allele frequency for the set * @return a PCollection mapping Position to AlleleCounts */ static PCollection<KV<Position, AlleleFreq>> getFreq( PCollection<Variant> variants, double minFreq) { return variants.apply(Filter.byPredicate(VariantFunctions.IS_PASSING).named("PassingFilter")) .apply(Filter.byPredicate(VariantFunctions.IS_ON_CHROMOSOME).named("OnChromosomeFilter")) .apply(Filter.byPredicate(VariantFunctions.IS_NOT_LOW_QUALITY).named("NotLowQualityFilter")) .apply(Filter.byPredicate(VariantFunctions.IS_SINGLE_ALTERNATE_SNP).named("SNPFilter")) .apply(ParDo.of(new GetAlleleFreq())) .apply(Filter.byPredicate(new FilterFreq(minFreq))); } /** * Filter, pile up, and sample reads, then join against reference statistics. * * @param reads A PCollection of reads * @param samplingFraction Fraction of reads to keep * @param samplingPrefix A prefix used in generating hashes used in sampling * @param refCounts A PCollection mapping position to counts of alleles in * a reference population. * @return A PCollection mapping Position to a ReadCounts proto */ static PCollection<KV<Position, ReadCounts>> combineReads(PCollection<Read> reads, double samplingFraction, String samplingPrefix, PCollection<KV<Position, AlleleFreq>> refFreq) { // Runs filters on input Reads, splits into individual aligned bases (emitting the // base and quality) and grabs a sample of them based on a hash mod of Position. PCollection<KV<Position, ReadBaseQuality>> joinReadCounts = reads.apply(Filter.byPredicate(ReadFunctions.IS_ON_CHROMOSOME).named("IsOnChromosome")) .apply(Filter.byPredicate(ReadFunctions.IS_NOT_QC_FAILURE).named("IsNotQCFailure")) .apply(Filter.byPredicate(ReadFunctions.IS_NOT_DUPLICATE).named("IsNotDuplicate")) .apply(Filter.byPredicate(ReadFunctions.IS_PROPER_PLACEMENT).named("IsProperPlacement")) .apply(ParDo.of(new SplitReads())) .apply(Filter.byPredicate(new SampleReads(samplingFraction, samplingPrefix))); TupleTag<ReadBaseQuality> readCountsTag = new TupleTag<>(); TupleTag<AlleleFreq> refFreqTag = new TupleTag<>(); // Pile up read counts, then join against reference stats. PCollection<KV<Position, CoGbkResult>> joined = KeyedPCollectionTuple .of(readCountsTag, joinReadCounts) .and(refFreqTag, refFreq) .apply(CoGroupByKey.<Position>create()); return joined.apply(ParDo.of(new PileupAndJoinReads(readCountsTag, refFreqTag))); } /** * Split reads into individual aligned bases and emit base + quality. */ static class SplitReads extends DoFn<Read, KV<Position, ReadBaseQuality>> { @Override public void processElement(ProcessContext c) throws Exception { List<ReadBaseWithReference> readBases = ReadFunctions.extractReadBases(c.element()); if (!readBases.isEmpty()) { for (ReadBaseWithReference rb : readBases) { c.output(KV.of(rb.getRefPosition(), rb.getRbq())); } } } } /** * Sample bases via a hash mod of position. */ static class SampleReads implements SerializableFunction<KV<Position, ReadBaseQuality>, Boolean> { private final double samplingFraction; private final String samplingPrefix; public SampleReads(double samplingFraction, String samplingPrefix) { this.samplingFraction = samplingFraction; this.samplingPrefix = samplingPrefix; } @Override public Boolean apply(KV<Position, ReadBaseQuality> input) { if (samplingFraction == 1.0) { return true; } else { byte[] msg; Position position = input.getKey(); try { msg = (samplingPrefix + position.getReferenceName() + ":" + position.getPosition() + ":" + position.getReverseStrand()).getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new AssertionError("UTF-8 not available - should not happen"); } MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new AssertionError("MD5 not available - should not happen"); } byte[] digest = md.digest(msg); if (digest.length != 16) { throw new AssertionError("MD5 should return 128 bits"); } ByteBuffer buffer = ByteBuffer.allocate(Long.SIZE); buffer.put(Arrays.copyOf(digest, Long.SIZE)); return ((((double) buffer.getLong(0) / (double) ((long) 1 << 63)) + 1.0) * 0.5) < samplingFraction; } } } /** * Map a variant to a Position, AlleleFreq pair. */ static class GetAlleleFreq extends DoFn<Variant, KV<Position, AlleleFreq>> { @Override public void processElement(ProcessContext c) throws Exception { ListValue lv = c.element().getInfo().get("AF"); if (lv != null && lv.getValuesCount() > 0) { Position position = Position.newBuilder() .setPosition(c.element().getStart()) .setReferenceName(c.element().getReferenceName()) .build(); AlleleFreq af = new AlleleFreq(); af.setRefFreq(Double.parseDouble(lv.getValues(0).getStringValue())); af.setAltBases(c.element().getAlternateBasesList()); af.setRefBases(c.element().getReferenceBases()); c.output(KV.of(position, af)); } else { // AF field wasn't populated in info, so we don't have frequency information // for this Variant. // TODO instead of straight throwing an exception, log a warning. If at the end of this // step the number of AlleleFreqs retrieved is below a given threshold, then throw an // exception. throw new IllegalArgumentException("Variant " + c.element().getId() + " does not have " + "allele frequency information stored in INFO field AF."); } } } /** * Filters out AlleleFreqs for which the reference or alternate allele * frequencies are below a minimum specified at construction. */ static class FilterFreq implements SerializableFunction<KV<Position, AlleleFreq>, Boolean> { private final double minFreq; public FilterFreq(double minFreq) { this.minFreq = minFreq; } @Override public Boolean apply(KV<Position, AlleleFreq> input) { double freq = input.getValue().getRefFreq(); if (freq >= minFreq && (1.0 - freq) >= minFreq) { return true; } return false; } } /** * Piles up reads and joins them against reference population statistics. */ static class PileupAndJoinReads extends DoFn<KV<Position, CoGbkResult>, KV<Position, ReadCounts>> { private final TupleTag<ReadBaseQuality> readCountsTag; private final TupleTag<AlleleFreq> refFreqTag; public PileupAndJoinReads(TupleTag<ReadBaseQuality> readCountsTag, TupleTag<AlleleFreq> refFreqTag) { this.readCountsTag = readCountsTag; this.refFreqTag = refFreqTag; } @Override public void processElement(ProcessContext c) throws Exception { AlleleFreq af = null; af = c.element().getValue().getOnly(refFreqTag, null); if (af == null || af.getAltBases() == null) { // no ref stats return; } if (af.getAltBases().size() != 1) { throw new IllegalArgumentException("Wrong number (" + af.getAltBases().size() + ") of" + " alternate bases for Position " + c.element().getKey()); } Iterable<ReadBaseQuality> reads = c.element().getValue().getAll(readCountsTag); ImmutableMultiset.Builder<ReadQualityCount> rqSetBuilder = ImmutableMultiset.builder(); for (ReadBaseQuality r : reads) { ReadQualityCount.Base b; if (af.getRefBases().equals(r.getBase())) { b = ReadQualityCount.Base.REF; } else if (af.getAltBases().get(0).equals(r.getBase())) { b = ReadQualityCount.Base.NONREF; } else { b = ReadQualityCount.Base.OTHER; } ReadQualityCount rqc = new ReadQualityCount(); rqc.setBase(b); rqc.setQuality(r.getQuality()); rqSetBuilder.add(rqc); } ReadCounts rc = new ReadCounts(); rc.setRefFreq(af.getRefFreq()); for (Multiset.Entry<ReadQualityCount> entry : rqSetBuilder.build().entrySet()) { ReadQualityCount rq = entry.getElement(); rq.setCount(entry.getCount()); rc.addReadQualityCount(rq); } c.output(KV.of(c.element().getKey(), rc)); } } /** * Calls the Solver to maximize via a univariate function the results of the pipeline, inputted * as a PCollectionView (the best way to retrieve our results as a Map in Dataflow). */ static class Maximizer extends DoFn<Object, String> { private final PCollectionView<Map<Position, ReadCounts>> view; // Target absolute error for Brent's algorithm private static final double ABS_ERR = 0.00001; // Target relative error for Brent's algorithm private static final double REL_ERR = 0.0001; // Maximum number of evaluations of the Likelihood function in Brent's algorithm private static final int MAX_EVAL = 1000; // Maximum number of iterations of Brent's algorithm private static final int MAX_ITER = 1000; // Grid search step size private static final double GRID_STEP = 0.001; public Maximizer(PCollectionView<Map<Position, ReadCounts>> view) { this.view = view; } @Override public void processElement(ProcessContext c) throws Exception { float[] steps = new float[]{0.1f, 0.05f, 0.01f, 0.005f, 0.001f}; for (float step : steps) { c.output(Float.toString(step) + ": " + Double.toString(Solver.maximize(new LikelihoodFn(c.sideInput(view)), 0.0, 0.5, step, REL_ERR, ABS_ERR, MAX_ITER, MAX_EVAL))); } } } }
Update VerifyBamId.java
src/main/java/com/google/cloud/genomics/dataflow/pipelines/VerifyBamId.java
Update VerifyBamId.java
<ide><path>rc/main/java/com/google/cloud/genomics/dataflow/pipelines/VerifyBamId.java <ide> // Grid search step size <ide> private static final double GRID_STEP = 0.001; <ide> <del> public Maximizer(PCollectionView<Map<Position, ReadCounts>> view) { <add> public Maximizer(PCollectionView<Map<Position, ReadCounts>> view) { <ide> this.view = view; <ide> } <ide>
Java
bsd-2-clause
43dd11ffa7bc521b6afcaa53fee6dd589c04780a
0
chototsu/MikuMikuStudio,chototsu/MikuMikuStudio,chototsu/MikuMikuStudio,chototsu/MikuMikuStudio
/* * Copyright (c) 2003-2004, jMonkeyEngine - Mojo Monkey Coding * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the Mojo Monkey Coding, jME, jMonkey Engine, 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 OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ package com.jme.scene; import java.io.Serializable; import java.util.ArrayList; import java.util.Stack; import com.jme.bounding.BoundingVolume; import com.jme.math.Matrix3f; import com.jme.math.Quaternion; import com.jme.math.Vector3f; import com.jme.renderer.Camera; import com.jme.renderer.Renderer; import com.jme.scene.state.LightState; import com.jme.scene.state.RenderState; import com.jme.scene.state.TextureState; /** * <code>Spatial</code> defines the base class for scene graph nodes. It * maintains a link to a parent, it's local transforms and the world's * transforms. All other nodes, such as <code>Node</code> and * <code>Geometry</code> are subclasses of <code>Spatial</code>. * @author Mark Powell * @version $Id: Spatial.java,v 1.47 2004-08-07 01:07:50 renanse Exp $ */ public abstract class Spatial implements Serializable { /** Spatial's rotation relative to its parent. */ protected Quaternion localRotation; /** Spatial's world absolute rotation. */ protected Quaternion worldRotation; /** Spatial's translation relative to its parent. */ protected Vector3f localTranslation; /** Spatial's world absolute translation. */ protected Vector3f worldTranslation; /** Spatial's scale relative to its parent. */ protected Vector3f localScale; /** Spatial's world absolute scale. */ protected Vector3f worldScale; /** If true, spatial and all children are culled from the scene graph. */ protected boolean forceCull; /** If true, spatial and all children are always rendered in the scene graph. */ protected boolean forceView; /** Spatial's bounding volume relative to the world. */ protected BoundingVolume worldBound; /** Spatial's parent, or null if it has none. */ protected transient Node parent; /** If true, spatial is a root node. */ protected boolean isRoot; /** List of default states all spatials take if none is set. */ public static RenderState[] defaultStateList = new RenderState[RenderState.RS_MAX_STATE]; /** RenderStates a Spatial contains during rendering. */ protected static RenderState[] currentStates = new RenderState[RenderState.RS_MAX_STATE]; /** The render states of this spatial. */ protected RenderState[] renderStateList; protected int renderQueueMode = Renderer.QUEUE_INHERIT; protected int zOrder = 0; public transient float queueDistance = Float.NEGATIVE_INFINITY; /** Flag signaling how lights are combined for this node. By default set to INHERIT. */ protected int lightCombineMode = LightState.INHERIT; /** Flag signaling how textures are combined for this node. By default set to INHERIT. */ protected int textureCombineMode = TextureState.INHERIT; /** ArrayList of controllers for this spatial. */ protected ArrayList geometricalControllers = new ArrayList(); /** This spatial's name. */ protected String name; //scale values protected int frustrumIntersects = Camera.INTERSECTS_FRUSTUM; /** * Empty Constructor to be used internally only. */ public Spatial() {} /** * Constructor instantiates a new <code>Spatial</code> object setting * the rotation, translation and scale value to defaults. * @param name the name of the scene element. This is required for identification and * comparision purposes. */ public Spatial(String name) { this.name = name; renderStateList = new RenderState[RenderState.RS_MAX_STATE]; localRotation = new Quaternion(); worldRotation = new Quaternion(); localTranslation = new Vector3f(); worldTranslation = new Vector3f(); localScale = new Vector3f(1.0f, 1.0f, 1.0f); worldScale = new Vector3f(1.0f, 1.0f, 1.0f); } /** * Sets the name of this spatial. * @param name The spatial's new name. */ public void setName(String name) { this.name = name; } /** * Sets if this spatial is a root spatial. * @param value If true, flag this spatial as a root. */ public void setIsRoot(boolean value) { isRoot = value; } /** * Returns the flag value for this spatial's root settting. * @return True if this spatial is flagged as a root. */ public boolean isRoot() { return isRoot; } /** * Returns the name of this spatial. * @return This spatial's name. */ public String getName() { return name; } /** * Adds a Controller to this Spatial's list of controllers. * @param controller The Controller to add * @see com.jme.scene.Controller */ public void addController(Controller controller) { if (geometricalControllers == null) { geometricalControllers = new ArrayList(); } geometricalControllers.add(controller); } /** * Removes a Controller to this Spatial's list of controllers, if it exist. * @param controller The Controller to remove * @return True if the Controller was in the list to remove. * @see com.jme.scene.Controller */ public boolean removeController(Controller controller) { if (geometricalControllers == null) { geometricalControllers = new ArrayList(); } return geometricalControllers.remove(controller); } /** * Returns the controller in this list of controllers at index i. * @param i The index to get a controller from. * @return The controller at index i. * @see com.jme.scene.Controller */ public Controller getController(int i) { if (geometricalControllers == null) { geometricalControllers = new ArrayList(); } return (Controller) geometricalControllers.get(i); } /** * Returns the ArrayList that contains this spatial's Controllers. * @return This spatial's geometricalControllers. */ public ArrayList getControllers() { if (geometricalControllers == null) { geometricalControllers = new ArrayList(); } return geometricalControllers; } /** * * <code>getWorldBound</code> retrieves the world bound at this node level. * @return the world bound at this level. */ public BoundingVolume getWorldBound() { return worldBound; } /** * * <code>setWorldBound</code> sets the world bound for this node level. * @param worldBound the world bound at this level. */ public void setWorldBound(BoundingVolume worldBound) { this.worldBound = worldBound; } /** * * <code>onDraw</code> checks the node with the camera to see if it * should be culled, if not, the node's draw method is called. * @param r the renderer used for display. */ public void onDraw(Renderer r) { if (forceCull) { return; } Camera camera = r.getCamera(); int state = camera.getPlaneState(); //check to see if we can cull this node frustrumIntersects = (parent != null ? parent.frustrumIntersects : Camera.INTERSECTS_FRUSTUM); if (!forceView && frustrumIntersects == Camera.INTERSECTS_FRUSTUM) { frustrumIntersects = camera.contains(worldBound); } if (forceView || frustrumIntersects != Camera.OUTSIDE_FRUSTUM) { draw(r); } camera.setPlaneState(state); } /** * * <code>onDrawBounds</code> checks the node with the camera to see if it * should be culled, if not, the node's draw method is called. * @param r the renderer used for display. */ public void onDrawBounds(Renderer r) { if (forceCull) { return; } Camera camera = r.getCamera(); int state = camera.getPlaneState(); //check to see if we can cull this node frustrumIntersects = (parent != null ? parent.frustrumIntersects : Camera.INTERSECTS_FRUSTUM); if (!forceView && frustrumIntersects == Camera.INTERSECTS_FRUSTUM) { frustrumIntersects = camera.contains(worldBound); } if (forceView || frustrumIntersects != Camera.OUTSIDE_FRUSTUM) { drawBounds(r); } camera.setPlaneState(state); } /** * * <code>draw</code> abstract method that handles drawing data to the * renderer if it is geometry and passing the call to it's children if it * is a node. * @param r the renderer used for display. */ public abstract void draw(Renderer r); /** * * <code>drawBounds</code> abstract method that handles drawing bounds data to the * renderer if it is geometry and passing the call to it's children if it * is a node. * @param r the renderer used for display. */ public abstract void drawBounds(Renderer r); /** * * <code>getWorldRotation</code> retrieves the rotation matrix of the * world. * @return the world's rotation matrix. */ public Quaternion getWorldRotation() { return worldRotation; } /** * * <code>getWorldTranslation</code> retrieves the translation vector of * the world. * @return the world's tranlsation vector. */ public Vector3f getWorldTranslation() { return worldTranslation; } /** * * <code>getWorldScale</code> retrieves the scale factor of the world. * @return the world's scale factor. */ public Vector3f getWorldScale() { return worldScale; } /** * * <code>isForceCulled</code> reports if this node should always be * culled or not. If true, this node will not be displayed. * @return true if this node should never be displayed, false otherwise. */ public boolean isForceCulled() { return forceCull; } /** * * <code>isForceView</code> returns true if the node will be rendered whether * it's in the camera frustum or not. * @return true if viewing is forced, false otherwise. */ public boolean isForceView() { return forceView; } /** * * <code>setForceCull</code> sets if this node should always be culled or * not. True will always cull the node, false will allow proper culling to * take place. * @param forceCull the value for forcing a culling. */ public void setForceCull(boolean forceCull) { this.forceCull = forceCull; } /** * * <code>setForceView</code> will force the node to be rendered whether it's * in the camera frustum or not. * @param value true to force viewing, false otherwise. */ public abstract void setForceView(boolean value); /** * * <code>updateGeometricState</code> updates all the geometry information * for the node. * @param time the frame time. * @param initiator true if this node started the update process. */ public void updateGeometricState(float time, boolean initiator) { updateWorldData(time); updateWorldBound(); if (initiator) { propagateBoundToRoot(); } } /** * * <code>updateWorldData</code> updates the world transforms from the * parent down to the leaf. * @param time the frame time. */ protected void updateWorldData(float time) { //update spatial state via controllers Object controller; for (int i = 0, gSize = geometricalControllers.size(); i < gSize; i++) { if ( (controller = geometricalControllers.get(i)) != null) { ( (Controller) controller).update(time); } } //update render state via controllers Controller[] controls; RenderState rs; for (int i = renderStateList.length; --i >= 0; ) { rs = renderStateList[i]; if (rs != null) { controls = rs.getControllers(); for (int j = 0; j < controls.length; j++) { if (controls[j] != null) { controls[j].update(time); } } } } // update spatial controllers boolean computesWorldTransform = false; // update world transforms if (!computesWorldTransform) { if (parent != null) { worldScale.set(parent.getWorldScale()).multLocal(localScale); parent.getWorldRotation().mult(localRotation, worldRotation); worldTranslation = parent .getWorldRotation() .mult(localTranslation, worldTranslation) .multLocal(parent.getWorldScale()) .addLocal(parent.getWorldTranslation()); } else { worldScale = localScale; worldRotation = localRotation; worldTranslation = localTranslation; } } } /** * * <code>updateWorldBound</code> updates the bounding volume of the * world. Abstract, geometry transforms the bound while node merges * the children's bound. * */ public abstract void updateWorldBound(); /** * Updates the render state values of this Spatial and * and children it has. Should be called whenever render states change. */ public void updateRenderState() { updateRenderState(null); } /** * Called internally. Updates the render states of this Spatial. The stack contains * parent render states. * @param parentStates The list of parent renderstates. */ protected void updateRenderState(Stack[] parentStates) { boolean initiator = (parentStates == null); // first we need to get all the states from parent to us. if (initiator) { // grab all states from root to here. parentStates = new Stack[RenderState.RS_MAX_STATE]; for (int x = 0; x < parentStates.length; x++) parentStates[x] = new Stack(); propagateStatesFromRoot(parentStates); } else { for (int x = 0; x < RenderState.RS_MAX_STATE; x++) { if (renderStateList[x] != null) parentStates[x].push(renderStateList[x]); } } // now set these onto this spatial and below applyRenderState(parentStates); // restore previous if we are not the initiator if (!initiator) { for (int x = 0; x < RenderState.RS_MAX_STATE; x++) if (renderStateList[x] != null) parentStates[x].pop(); } } /** * Called during updateRenderState(Stack[]), this function determines how the render * states are actually applied to the spatial and any children it may have. By default, * this function does nothing. * @param states An array of stacks for each state. */ protected void applyRenderState(Stack[] states){} /** * Called during updateRenderState(Stack[]), this function goes up the scene graph tree * until the parent is null and pushes RenderStates onto the states Stack array. * @param states The Stack[] to push states onto. */ protected void propagateStatesFromRoot(Stack[] states) { // traverse to root to allow downward state propagation if (parent != null) parent.propagateStatesFromRoot(states); // push states onto current render state stack for (int x = 0; x < RenderState.RS_MAX_STATE; x++) if (renderStateList[x] != null) states[x].push(renderStateList[x]); } /** * * <code>propagateBoundToRoot</code> passes the new world bound up the * tree to the root. * */ public void propagateBoundToRoot() { if (parent != null) { parent.updateWorldBound(); parent.propagateBoundToRoot(); } } /** * <code>getParent</code> retrieve's this node's parent. If the parent is * null this is the root node. * @return the parent of this node. */ public Node getParent() { return parent; } /** * <code>setParent</code> sets the parent of this node. * @param parent the parent of this node. */ public void setParent(Node parent) { this.parent = parent; } /** * <code>getLocalRotation</code> retrieves the local rotation of this * node. * @return the local rotation of this node. */ public Quaternion getLocalRotation() { return localRotation; } /** * <code>setLocalRotation</code> sets the local rotation of this node. * @param rotation the new local rotation. */ public void setLocalRotation(Matrix3f rotation) { if (localRotation == null) localRotation = new Quaternion(); localRotation.fromRotationMatrix(rotation); } /** * * <code>setLocalRotation</code> sets the local rotation of this node, using * a quaterion to build the matrix. * @param quaternion the quaternion that defines the matrix. */ public void setLocalRotation(Quaternion quaternion) { localRotation = quaternion; } /** * <code>getLocalScale</code> retrieves the local scale of this node. * @return the local scale of this node. */ public Vector3f getLocalScale() { return localScale; } /** * <code>setLocalScale</code> sets the local scale of this node. * @param localScale the new local scale, applied to x, y and z */ public void setLocalScale(float localScale) { this.localScale.x = localScale; this.localScale.y = localScale; this.localScale.z = localScale; } /** * <code>setLocalScale</code> sets the local scale of this node. * @param localScale the new local scale. */ public void setLocalScale(Vector3f localScale) { this.localScale = localScale; } /** * <code>getLocalTranslation</code> retrieves the local translation of * this node. * @return the local translation of this node. */ public Vector3f getLocalTranslation() { return localTranslation; } /** * <code>setLocalTranslation</code> sets the local translation of this * node. * @param localTranslation the local translation of this node. */ public void setLocalTranslation(Vector3f localTranslation) { this.localTranslation = localTranslation; } /** * * <code>setRenderState</code> sets a render state for this node. Note, * there can only be one render state per type per node. That is, there * can only be a single AlphaState a single TextureState, etc. If there * is already a render state for a type set the old render state will * be rendered. Otherwise, null is returned. * @param rs the render state to add. * @return the old render state. */ public RenderState setRenderState(RenderState rs) { RenderState oldState = renderStateList[rs.getType()]; renderStateList[rs.getType()] = rs; return oldState; } /** * Returns the array of RenerState that this Spatial currently has. * @return This spatial's state array. */ public RenderState[] getRenderStateList() { return renderStateList; } /** * Clears a given render state index by setting it to 0. * @param renderStateType The index of a RenderState to clear * @see com.jme.scene.state.RenderState#getType() */ public void clearRenderState(int renderStateType) { renderStateList[renderStateType] = null; } public void setRenderQueueMode(int renderQueueMode) { this.renderQueueMode = renderQueueMode; } public int getRenderQueueMode() { if (renderQueueMode != Renderer.QUEUE_INHERIT) return renderQueueMode; else if (parent != null) return parent.getRenderQueueMode(); else return Renderer.QUEUE_SKIP; } public void setZOrder(int zOrder) { this.zOrder = zOrder; } public int getZOrder() { return zOrder; } /** * Sets how lights from parents should be combined for this spatial. * @param lightCombineMode The light combine mode for this spatial * @see com.jme.scene.state.LightState#COMBINE_CLOSEST * @see com.jme.scene.state.LightState#COMBINE_FIRST * @see com.jme.scene.state.LightState#COMBINE_RECENT_ENABLED * @see com.jme.scene.state.LightState#INHERIT * @see com.jme.scene.state.LightState#OFF * @see com.jme.scene.state.LightState#REPLACE */ public void setLightCombineMode(int lightCombineMode) { this.lightCombineMode = lightCombineMode; } /** * Returns this spatial's light combine mode. If the mode is set to inherit, * then the spatial gets its combine mode from its parent. * @return The spatial's light current combine mode. */ public int getLightCombineMode() { if (lightCombineMode != LightState.INHERIT) return lightCombineMode; else if (parent != null) return parent.getLightCombineMode(); else return LightState.COMBINE_FIRST; } /** * Sets how textures from parents should be combined for this Spatial. * @param textureCombineMode The new texture combine mode for this spatial. * @see com.jme.scene.state.TextureState#COMBINE_CLOSEST * @see com.jme.scene.state.TextureState#COMBINE_FIRST * @see com.jme.scene.state.TextureState#COMBINE_RECENT_ENABLED * @see com.jme.scene.state.TextureState#INHERIT * @see com.jme.scene.state.TextureState#OFF * @see com.jme.scene.state.TextureState#REPLACE */ public void setTextureCombineMode(int textureCombineMode) { this.textureCombineMode = textureCombineMode; } /** * Returns this spatial's texture combine mode. If the mode is set to inherit, * then the spatial gets its combine mode from its parent. * @return The spatial's texture current combine mode. */ public int getTextureCombineMode() { if (textureCombineMode != TextureState.INHERIT) return textureCombineMode; else if (parent != null) return parent.getTextureCombineMode(); else return TextureState.COMBINE_CLOSEST; } public static void clearCurrentStates() { for (int i = 0; i < currentStates.length; i++) currentStates[i] = null; } /** * All non null default states are applied to the renderer. */ public static void applyDefaultStates() { for (int i = 0; i < defaultStateList.length; i++) { if (defaultStateList[i] != null) defaultStateList[i].apply(); } } /** * Returns the Spatial's name followed by the class of the spatial<br> * Example: "MyNode (com.jme.scene.Spatial) * @return Spatial's name followed by the class of the Spatial */ public String toString() { return name+" ("+this.getClass().getName()+')'; } }
src/com/jme/scene/Spatial.java
/* * Copyright (c) 2003-2004, jMonkeyEngine - Mojo Monkey Coding * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the Mojo Monkey Coding, jME, jMonkey Engine, 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 OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ package com.jme.scene; import java.io.Serializable; import java.util.ArrayList; import java.util.Stack; import com.jme.bounding.BoundingVolume; import com.jme.math.Matrix3f; import com.jme.math.Quaternion; import com.jme.math.Vector3f; import com.jme.renderer.Camera; import com.jme.renderer.Renderer; import com.jme.scene.state.LightState; import com.jme.scene.state.RenderState; import com.jme.scene.state.TextureState; /** * <code>Spatial</code> defines the base class for scene graph nodes. It * maintains a link to a parent, it's local transforms and the world's * transforms. All other nodes, such as <code>Node</code> and * <code>Geometry</code> are subclasses of <code>Spatial</code>. * @author Mark Powell * @version $Id: Spatial.java,v 1.46 2004-07-31 17:54:27 cep21 Exp $ */ public abstract class Spatial implements Serializable { /** Spatial's rotation relative to its parent. */ protected Quaternion localRotation; /** Spatial's world absolute rotation. */ protected Quaternion worldRotation; /** Spatial's translation relative to its parent. */ protected Vector3f localTranslation; /** Spatial's world absolute translation. */ protected Vector3f worldTranslation; /** Spatial's scale relative to its parent. */ protected Vector3f localScale; /** Spatial's world absolute scale. */ protected Vector3f worldScale; /** If true, spatial and all children are culled from the scene graph. */ protected boolean forceCull; /** If true, spatial and all children are always rendered in the scene graph. */ protected boolean forceView; /** Spatial's bounding volume relative to the world. */ protected BoundingVolume worldBound; /** Spatial's parent, or null if it has none. */ protected transient Node parent; /** If true, spatial is a root node. */ protected boolean isRoot; /** List of default states all spatials take if none is set. */ public static RenderState[] defaultStateList = new RenderState[RenderState.RS_MAX_STATE]; /** RenderStates a Spatial contains during rendering. */ protected static RenderState[] currentStates = new RenderState[RenderState.RS_MAX_STATE]; /** The render states of this spatial. */ protected RenderState[] renderStateList; protected int renderQueueMode = Renderer.QUEUE_INHERIT; protected int zOrder = 0; public transient float queueDistance = Float.NEGATIVE_INFINITY; /** Flag signaling how lights are combined for this node. By default set to INHERIT. */ protected int lightCombineMode = LightState.INHERIT; /** Flag signaling how textures are combined for this node. By default set to INHERIT. */ protected int textureCombineMode = TextureState.INHERIT; /** ArrayList of controllers for this spatial. */ protected ArrayList geometricalControllers = new ArrayList(); /** This spatial's name. */ protected String name; //scale values protected int frustrumIntersects = Camera.INTERSECTS_FRUSTUM; /** * Empty Constructor to be used internally only. */ public Spatial() {} /** * Constructor instantiates a new <code>Spatial</code> object setting * the rotation, translation and scale value to defaults. * @param name the name of the scene element. This is required for identification and * comparision purposes. */ public Spatial(String name) { this.name = name; renderStateList = new RenderState[RenderState.RS_MAX_STATE]; localRotation = new Quaternion(); worldRotation = new Quaternion(); localTranslation = new Vector3f(); worldTranslation = new Vector3f(); localScale = new Vector3f(1.0f, 1.0f, 1.0f); worldScale = new Vector3f(1.0f, 1.0f, 1.0f); } /** * Sets the name of this spatial. * @param name The spatial's new name. */ public void setName(String name) { this.name = name; } /** * Sets if this spatial is a root spatial. * @param value If true, flag this spatial as a root. */ public void setIsRoot(boolean value) { isRoot = value; } /** * Returns the flag value for this spatial's root settting. * @return True if this spatial is flagged as a root. */ public boolean isRoot() { return isRoot; } /** * Returns the name of this spatial. * @return This spatial's name. */ public String getName() { return name; } /** * Adds a Controller to this Spatial's list of controllers. * @param controller The Controller to add * @see com.jme.scene.Controller */ public void addController(Controller controller) { if (geometricalControllers == null) { geometricalControllers = new ArrayList(); } geometricalControllers.add(controller); } /** * Removes a Controller to this Spatial's list of controllers, if it exist. * @param controller The Controller to remove * @return True if the Controller was in the list to remove. * @see com.jme.scene.Controller */ public boolean removeController(Controller controller) { if (geometricalControllers == null) { geometricalControllers = new ArrayList(); } return geometricalControllers.remove(controller); } /** * Returns the controller in this list of controllers at index i. * @param i The index to get a controller from. * @return The controller at index i. * @see com.jme.scene.Controller */ public Controller getController(int i) { if (geometricalControllers == null) { geometricalControllers = new ArrayList(); } return (Controller) geometricalControllers.get(i); } /** * Returns the ArrayList that contains this spatial's Controllers. * @return This spatial's geometricalControllers. */ public ArrayList getControllers() { if (geometricalControllers == null) { geometricalControllers = new ArrayList(); } return geometricalControllers; } /** * * <code>getWorldBound</code> retrieves the world bound at this node level. * @return the world bound at this level. */ public BoundingVolume getWorldBound() { return worldBound; } /** * * <code>setWorldBound</code> sets the world bound for this node level. * @param worldBound the world bound at this level. */ public void setWorldBound(BoundingVolume worldBound) { this.worldBound = worldBound; } /** * * <code>onDraw</code> checks the node with the camera to see if it * should be culled, if not, the node's draw method is called. * @param r the renderer used for display. */ public void onDraw(Renderer r) { if (forceCull) { return; } Camera camera = r.getCamera(); int state = camera.getPlaneState(); //check to see if we can cull this node frustrumIntersects = (parent != null ? parent.frustrumIntersects : Camera.INTERSECTS_FRUSTUM); if (!forceView && frustrumIntersects == Camera.INTERSECTS_FRUSTUM) { frustrumIntersects = camera.contains(worldBound); } if (forceView || frustrumIntersects != Camera.OUTSIDE_FRUSTUM) { draw(r); } camera.setPlaneState(state); } /** * * <code>onDrawBounds</code> checks the node with the camera to see if it * should be culled, if not, the node's draw method is called. * @param r the renderer used for display. */ public void onDrawBounds(Renderer r) { if (forceCull) { return; } Camera camera = r.getCamera(); int state = camera.getPlaneState(); //check to see if we can cull this node frustrumIntersects = (parent != null ? parent.frustrumIntersects : Camera.INTERSECTS_FRUSTUM); if (!forceView && frustrumIntersects == Camera.INTERSECTS_FRUSTUM) { frustrumIntersects = camera.contains(worldBound); } if (forceView || frustrumIntersects != Camera.OUTSIDE_FRUSTUM) { drawBounds(r); } camera.setPlaneState(state); } /** * * <code>draw</code> abstract method that handles drawing data to the * renderer if it is geometry and passing the call to it's children if it * is a node. * @param r the renderer used for display. */ public abstract void draw(Renderer r); /** * * <code>drawBounds</code> abstract method that handles drawing bounds data to the * renderer if it is geometry and passing the call to it's children if it * is a node. * @param r the renderer used for display. */ public abstract void drawBounds(Renderer r); /** * * <code>getWorldRotation</code> retrieves the rotation matrix of the * world. * @return the world's rotation matrix. */ public Quaternion getWorldRotation() { return worldRotation; } /** * * <code>getWorldTranslation</code> retrieves the translation vector of * the world. * @return the world's tranlsation vector. */ public Vector3f getWorldTranslation() { return worldTranslation; } /** * * <code>getWorldScale</code> retrieves the scale factor of the world. * @return the world's scale factor. */ public Vector3f getWorldScale() { return worldScale; } /** * * <code>isForceCulled</code> reports if this node should always be * culled or not. If true, this node will not be displayed. * @return true if this node should never be displayed, false otherwise. */ public boolean isForceCulled() { return forceCull; } /** * * <code>isForceView</code> returns true if the node will be rendered whether * it's in the camera frustum or not. * @return true if viewing is forced, false otherwise. */ public boolean isForceView() { return forceView; } /** * * <code>setForceCull</code> sets if this node should always be culled or * not. True will always cull the node, false will allow proper culling to * take place. * @param forceCull the value for forcing a culling. */ public void setForceCull(boolean forceCull) { this.forceCull = forceCull; } /** * * <code>setForceView</code> will force the node to be rendered whether it's * in the camera frustum or not. * @param value true to force viewing, false otherwise. */ public abstract void setForceView(boolean value); /** * * <code>updateGeometricState</code> updates all the geometry information * for the node. * @param time the frame time. * @param initiator true if this node started the update process. */ public void updateGeometricState(float time, boolean initiator) { updateWorldData(time); updateWorldBound(); if (initiator) { propagateBoundToRoot(); } } /** * * <code>updateWorldData</code> updates the world transforms from the * parent down to the leaf. * @param time the frame time. */ protected void updateWorldData(float time) { //update spatial state via controllers Object controller; for (int i = 0, gSize = geometricalControllers.size(); i < gSize; i++) { if ( (controller = geometricalControllers.get(i)) != null) { ( (Controller) controller).update(time); } } //update render state via controllers Controller[] controls; RenderState rs; for (int i = 0, rLength = renderStateList.length; i < rLength; i++) { rs = renderStateList[i]; if (rs != null) { controls = rs.getControllers(); for (int j = 0; j < controls.length; j++) { if (controls[j] != null) { controls[j].update(time); } } } } // update spatial controllers boolean computesWorldTransform = false; // update world transforms if (!computesWorldTransform) { if (parent != null) { worldScale.set(parent.getWorldScale()).multLocal(localScale); parent.getWorldRotation().mult(localRotation, worldRotation); worldTranslation = parent .getWorldRotation() .mult(localTranslation, worldTranslation) .multLocal(parent.getWorldScale()) .addLocal(parent.getWorldTranslation()); } else { worldScale = localScale; worldRotation = localRotation; worldTranslation = localTranslation; } } } /** * * <code>updateWorldBound</code> updates the bounding volume of the * world. Abstract, geometry transforms the bound while node merges * the children's bound. * */ public abstract void updateWorldBound(); /** * Updates the render state values of this Spatial and * and children it has. Should be called whenever render states change. */ public void updateRenderState() { updateRenderState(null); } /** * Called internally. Updates the render states of this Spatial. The stack contains * parent render states. * @param parentStates The list of parent renderstates. */ protected void updateRenderState(Stack[] parentStates) { boolean initiator = (parentStates == null); // first we need to get all the states from parent to us. if (initiator) { // grab all states from root to here. parentStates = new Stack[RenderState.RS_MAX_STATE]; for (int x = 0; x < parentStates.length; x++) parentStates[x] = new Stack(); propagateStatesFromRoot(parentStates); } else { for (int x = 0; x < RenderState.RS_MAX_STATE; x++) { if (renderStateList[x] != null) parentStates[x].push(renderStateList[x]); } } // now set these onto this spatial and below applyRenderState(parentStates); // restore previous if we are not the initiator if (!initiator) { for (int x = 0; x < RenderState.RS_MAX_STATE; x++) if (renderStateList[x] != null) parentStates[x].pop(); } } /** * Called during updateRenderState(Stack[]), this function determines how the render * states are actually applied to the spatial and any children it may have. By default, * this function does nothing. * @param states An array of stacks for each state. */ protected void applyRenderState(Stack[] states){} /** * Called during updateRenderState(Stack[]), this function goes up the scene graph tree * until the parent is null and pushes RenderStates onto the states Stack array. * @param states The Stack[] to push states onto. */ protected void propagateStatesFromRoot(Stack[] states) { // traverse to root to allow downward state propagation if (parent != null) parent.propagateStatesFromRoot(states); // push states onto current render state stack for (int x = 0; x < RenderState.RS_MAX_STATE; x++) if (renderStateList[x] != null) states[x].push(renderStateList[x]); } /** * * <code>propagateBoundToRoot</code> passes the new world bound up the * tree to the root. * */ public void propagateBoundToRoot() { if (parent != null) { parent.updateWorldBound(); parent.propagateBoundToRoot(); } } /** * <code>getParent</code> retrieve's this node's parent. If the parent is * null this is the root node. * @return the parent of this node. */ public Node getParent() { return parent; } /** * <code>setParent</code> sets the parent of this node. * @param parent the parent of this node. */ public void setParent(Node parent) { this.parent = parent; } /** * <code>getLocalRotation</code> retrieves the local rotation of this * node. * @return the local rotation of this node. */ public Quaternion getLocalRotation() { return localRotation; } /** * <code>setLocalRotation</code> sets the local rotation of this node. * @param rotation the new local rotation. */ public void setLocalRotation(Matrix3f rotation) { if (localRotation == null) localRotation = new Quaternion(); localRotation.fromRotationMatrix(rotation); } /** * * <code>setLocalRotation</code> sets the local rotation of this node, using * a quaterion to build the matrix. * @param quaternion the quaternion that defines the matrix. */ public void setLocalRotation(Quaternion quaternion) { localRotation = quaternion; } /** * <code>getLocalScale</code> retrieves the local scale of this node. * @return the local scale of this node. */ public Vector3f getLocalScale() { return localScale; } /** * <code>setLocalScale</code> sets the local scale of this node. * @param localScale the new local scale, applied to x, y and z */ public void setLocalScale(float localScale) { this.localScale.x = localScale; this.localScale.y = localScale; this.localScale.z = localScale; } /** * <code>setLocalScale</code> sets the local scale of this node. * @param localScale the new local scale. */ public void setLocalScale(Vector3f localScale) { this.localScale = localScale; } /** * <code>getLocalTranslation</code> retrieves the local translation of * this node. * @return the local translation of this node. */ public Vector3f getLocalTranslation() { return localTranslation; } /** * <code>setLocalTranslation</code> sets the local translation of this * node. * @param localTranslation the local translation of this node. */ public void setLocalTranslation(Vector3f localTranslation) { this.localTranslation = localTranslation; } /** * * <code>setRenderState</code> sets a render state for this node. Note, * there can only be one render state per type per node. That is, there * can only be a single AlphaState a single TextureState, etc. If there * is already a render state for a type set the old render state will * be rendered. Otherwise, null is returned. * @param rs the render state to add. * @return the old render state. */ public RenderState setRenderState(RenderState rs) { RenderState oldState = renderStateList[rs.getType()]; renderStateList[rs.getType()] = rs; return oldState; } /** * Returns the array of RenerState that this Spatial currently has. * @return This spatial's state array. */ public RenderState[] getRenderStateList() { return renderStateList; } /** * Clears a given render state index by setting it to 0. * @param renderStateType The index of a RenderState to clear * @see com.jme.scene.state.RenderState#getType() */ public void clearRenderState(int renderStateType) { renderStateList[renderStateType] = null; } public void setRenderQueueMode(int renderQueueMode) { this.renderQueueMode = renderQueueMode; } public int getRenderQueueMode() { if (renderQueueMode != Renderer.QUEUE_INHERIT) return renderQueueMode; else if (parent != null) return parent.getRenderQueueMode(); else return Renderer.QUEUE_SKIP; } public void setZOrder(int zOrder) { this.zOrder = zOrder; } public int getZOrder() { return zOrder; } /** * Sets how lights from parents should be combined for this spatial. * @param lightCombineMode The light combine mode for this spatial * @see com.jme.scene.state.LightState#COMBINE_CLOSEST * @see com.jme.scene.state.LightState#COMBINE_FIRST * @see com.jme.scene.state.LightState#COMBINE_RECENT_ENABLED * @see com.jme.scene.state.LightState#INHERIT * @see com.jme.scene.state.LightState#OFF * @see com.jme.scene.state.LightState#REPLACE */ public void setLightCombineMode(int lightCombineMode) { this.lightCombineMode = lightCombineMode; } /** * Returns this spatial's light combine mode. If the mode is set to inherit, * then the spatial gets its combine mode from its parent. * @return The spatial's light current combine mode. */ public int getLightCombineMode() { if (lightCombineMode != LightState.INHERIT) return lightCombineMode; else if (parent != null) return parent.getLightCombineMode(); else return LightState.COMBINE_FIRST; } /** * Sets how textures from parents should be combined for this Spatial. * @param textureCombineMode The new texture combine mode for this spatial. * @see com.jme.scene.state.TextureState#COMBINE_CLOSEST * @see com.jme.scene.state.TextureState#COMBINE_FIRST * @see com.jme.scene.state.TextureState#COMBINE_RECENT_ENABLED * @see com.jme.scene.state.TextureState#INHERIT * @see com.jme.scene.state.TextureState#OFF * @see com.jme.scene.state.TextureState#REPLACE */ public void setTextureCombineMode(int textureCombineMode) { this.textureCombineMode = textureCombineMode; } /** * Returns this spatial's texture combine mode. If the mode is set to inherit, * then the spatial gets its combine mode from its parent. * @return The spatial's texture current combine mode. */ public int getTextureCombineMode() { if (textureCombineMode != TextureState.INHERIT) return textureCombineMode; else if (parent != null) return parent.getTextureCombineMode(); else return TextureState.COMBINE_CLOSEST; } public static void clearCurrentStates() { for (int i = 0; i < currentStates.length; i++) currentStates[i] = null; } /** * All non null default states are applied to the renderer. */ public static void applyDefaultStates() { for (int i = 0; i < defaultStateList.length; i++) { if (defaultStateList[i] != null) defaultStateList[i].apply(); } } /** * Returns the Spatial's name followed by the class of the spatial<br> * Example: "MyNode (com.jme.scene.Spatial) * @return Spatial's name followed by the class of the Spatial */ public String toString() { return name+" ("+this.getClass().getName()+')'; } }
slightly faster looping git-svn-id: 5afc437a751a4ff2ced778146f5faadda0b504ab@1709 75d07b2b-3a1a-0410-a2c5-0572b91ccdca
src/com/jme/scene/Spatial.java
slightly faster looping
<ide><path>rc/com/jme/scene/Spatial.java <ide> * transforms. All other nodes, such as <code>Node</code> and <ide> * <code>Geometry</code> are subclasses of <code>Spatial</code>. <ide> * @author Mark Powell <del> * @version $Id: Spatial.java,v 1.46 2004-07-31 17:54:27 cep21 Exp $ <add> * @version $Id: Spatial.java,v 1.47 2004-08-07 01:07:50 renanse Exp $ <ide> */ <ide> public abstract class Spatial implements Serializable { <ide> /** Spatial's rotation relative to its parent. */ <ide> //update render state via controllers <ide> Controller[] controls; <ide> RenderState rs; <del> for (int i = 0, rLength = renderStateList.length; i < rLength; i++) { <add> for (int i = renderStateList.length; --i >= 0; ) { <ide> rs = renderStateList[i]; <ide> if (rs != null) { <ide> controls = rs.getControllers();
JavaScript
mit
1b1fa1045cd32ec2feb9835e767d38b108b215ed
0
Satisfive/Satisfive,Satisfive/Satisfive
require('dotenv').config(); var express = require('express') , http = require('http') , sparkpost = require('./sparkpost') , db = require('./db') , path = require('path'); var app = express(); app.configure(function(){ app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); }); app.configure('development', function(){ app.use(express.errorHandler()); }); app.get('/api/emails/:uuid', function(req, res){ var email = db.Email.find(req.params.uuid); if (email) { res.json(email); } else { res.send(404); } }); app.post('/users', function(req, res){ var user; if (user = db.User.find(req.params.email)) { res.send(200); } else { res.send(400); } }); app.post('/webhook', function(req, res){ // do sentiment analysis req.body.map(function(e){ e.msys.relay_message; }).forEach(function(msg){ if(!msg) return; var thisEmail = "[email protected]"; // msg.rcpt_to , msg = new sparkpost.Message({ content: msg['content'], }); msg.addRecipient("name", thisEmail); console.log("sent"); }); res.send(200); }); app.get('/users/:email', function(req, res){ var user = db.User.find(req.params.email); if (user) { res.json(user.getEmails()); } else { res.send(404); } }); http.createServer(app).listen(app.get('port'), function(){ console.log("Express server listening on port " + app.get('port')); });
app.js
require('dotenv').config(); var express = require('express') , http = require('http') , sparkpost = require('./sparkpost') , db = require('./db') , path = require('path'); var app = express(); app.configure(function(){ app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); }); app.configure('development', function(){ app.use(express.errorHandler()); }); app.get('/api/emails/:uuid', function(req, res){ var email = db.Email.find(req.params.uuid); if (email) { res.json(email); } else { res.send(404); } }); app.post('/users', function(req, res){ var user; if (user = db.User.find(req.params.email)) { res.send(200); } else { res.send(400); } }); app.post('/webhook', function(req, res){ // do sentiment analysis console.log(req.body) console.log(req.params) req.body.map(function(e){ e.msys.relay_message; }).forEach(function(msg){ if(!msg) return; var thisEmail = "[email protected]"; // msg.rcpt_to , msg = new sparkpost.Message({ content: msg.content, }); msg.addRecipient("", thisEmail); msg.send(); }); res.send(200); }); app.get('/users/:email', function(req, res){ var user = db.User.find(req.params.email); if (user) { res.json(user.getEmails()); } else { res.send(404); } }); http.createServer(app).listen(app.get('port'), function(){ console.log("Express server listening on port " + app.get('port')); });
iteration on webhook
app.js
iteration on webhook
<ide><path>pp.js <ide> <ide> app.post('/webhook', function(req, res){ <ide> // do sentiment analysis <del> console.log(req.body) <del> console.log(req.params) <ide> req.body.map(function(e){ <ide> e.msys.relay_message; <ide> }).forEach(function(msg){ <ide> if(!msg) return; <ide> var thisEmail = "[email protected]"; // msg.rcpt_to , <ide> msg = new sparkpost.Message({ <del> content: msg.content, <add> content: msg['content'], <ide> }); <del> msg.addRecipient("", thisEmail); <del> msg.send(); <add> msg.addRecipient("name", thisEmail); <add> console.log("sent"); <ide> }); <ide> res.send(200); <ide> });
Java
apache-2.0
55c11566569ea890a8a70418e5fba9ced267f956
0
alphafoobar/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,slisson/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,robovm/robovm-studio,kdwink/intellij-community,signed/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,samthor/intellij-community,ibinti/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,clumsy/intellij-community,dslomov/intellij-community,adedayo/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,retomerz/intellij-community,caot/intellij-community,asedunov/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,vladmm/intellij-community,hurricup/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,semonte/intellij-community,semonte/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,ernestp/consulo,ryano144/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,samthor/intellij-community,xfournet/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,izonder/intellij-community,blademainer/intellij-community,slisson/intellij-community,blademainer/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,ernestp/consulo,adedayo/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,samthor/intellij-community,adedayo/intellij-community,fitermay/intellij-community,jagguli/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,izonder/intellij-community,samthor/intellij-community,holmes/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,supersven/intellij-community,vladmm/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,hurricup/intellij-community,FHannes/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,signed/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,xfournet/intellij-community,diorcety/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,ibinti/intellij-community,semonte/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,supersven/intellij-community,supersven/intellij-community,allotria/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,clumsy/intellij-community,da1z/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,jagguli/intellij-community,FHannes/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,apixandru/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,consulo/consulo,muntasirsyed/intellij-community,fnouama/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,ernestp/consulo,izonder/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,slisson/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,signed/intellij-community,da1z/intellij-community,holmes/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,izonder/intellij-community,allotria/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,semonte/intellij-community,signed/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,retomerz/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,semonte/intellij-community,caot/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,ryano144/intellij-community,retomerz/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,dslomov/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,semonte/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,blademainer/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,signed/intellij-community,clumsy/intellij-community,retomerz/intellij-community,caot/intellij-community,petteyg/intellij-community,asedunov/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,signed/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,allotria/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,consulo/consulo,nicolargo/intellij-community,holmes/intellij-community,kdwink/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,blademainer/intellij-community,supersven/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,kdwink/intellij-community,caot/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,diorcety/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,fnouama/intellij-community,kdwink/intellij-community,slisson/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,blademainer/intellij-community,ernestp/consulo,diorcety/intellij-community,ibinti/intellij-community,signed/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,ernestp/consulo,izonder/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,caot/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,apixandru/intellij-community,signed/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,samthor/intellij-community,petteyg/intellij-community,allotria/intellij-community,kool79/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,adedayo/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,vladmm/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,kdwink/intellij-community,adedayo/intellij-community,dslomov/intellij-community,jagguli/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,ernestp/consulo,mglukhikh/intellij-community,allotria/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,da1z/intellij-community,tmpgit/intellij-community,da1z/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,consulo/consulo,ivan-fedorov/intellij-community,signed/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,slisson/intellij-community,orekyuu/intellij-community,allotria/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,jagguli/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,adedayo/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,fitermay/intellij-community,apixandru/intellij-community,slisson/intellij-community,xfournet/intellij-community,hurricup/intellij-community,jagguli/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,samthor/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,da1z/intellij-community,slisson/intellij-community,clumsy/intellij-community,samthor/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,semonte/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,pwoodworth/intellij-community,caot/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,blademainer/intellij-community,kool79/intellij-community,hurricup/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,hurricup/intellij-community,supersven/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,slisson/intellij-community,robovm/robovm-studio,fitermay/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,signed/intellij-community,holmes/intellij-community,signed/intellij-community,supersven/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,clumsy/intellij-community,consulo/consulo,dslomov/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,ryano144/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,retomerz/intellij-community,consulo/consulo,ivan-fedorov/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,izonder/intellij-community,kool79/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,izonder/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,holmes/intellij-community,apixandru/intellij-community,caot/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,vladmm/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,asedunov/intellij-community,amith01994/intellij-community,izonder/intellij-community,da1z/intellij-community,diorcety/intellij-community,semonte/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,semonte/intellij-community,xfournet/intellij-community,fitermay/intellij-community,hurricup/intellij-community,supersven/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,robovm/robovm-studio,petteyg/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,semonte/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,allotria/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,adedayo/intellij-community,consulo/consulo,gnuhub/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,supersven/intellij-community,jagguli/intellij-community,slisson/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,retomerz/intellij-community
/* * Copyright 2000-2011 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.impl; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.application.impl.ApplicationImpl; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.roots.OrderEntry; import com.intellij.openapi.roots.OrderRootType; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.JarFileSystem; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.newvfs.NewVirtualFile; import com.intellij.openapi.vfs.newvfs.NewVirtualFileSystem; import com.intellij.openapi.vfs.newvfs.RefreshQueue; import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent; import com.intellij.openapi.vfs.newvfs.persistent.PersistentFS; import com.intellij.util.ArrayUtil; import com.intellij.util.PathUtil; import com.intellij.util.SystemProperties; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.text.CaseInsensitiveStringHashingStrategy; import gnu.trove.THashMap; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URISyntaxException; import java.net.URL; import java.util.*; /** * @author max */ public class VirtualDirectoryImpl extends VirtualFileSystemEntry { private static final VirtualFileSystemEntry NULL_VIRTUAL_FILE = new VirtualFileImpl("*?;%NULL", null, -42); private final NewVirtualFileSystem myFS; // guarded by this protected Object myChildren; // Either HashMap<String, VFile> or VFile[] public VirtualDirectoryImpl(@NotNull String name, final VirtualDirectoryImpl parent, @NotNull NewVirtualFileSystem fs, final int id) { super(name, parent, id); myFS = fs; } @Override @NotNull public NewVirtualFileSystem getFileSystem() { return myFS; } @Nullable private VirtualFileSystemEntry findChild(@NotNull String name, final boolean createIfNotFound, boolean ensureCanonicalName, NewVirtualFileSystem delegate) { final VirtualFileSystemEntry result = doFindChild(name, createIfNotFound, ensureCanonicalName, delegate); if (result == NULL_VIRTUAL_FILE) { return createIfNotFound ? createAndFindChildWithEventFire(name) : null; } if (result == null) { synchronized (this) { Map<String, VirtualFileSystemEntry> map = asMap(); if (map != null) { map.put(name, NULL_VIRTUAL_FILE); } } } return result; } @Nullable private VirtualFileSystemEntry doFindChild(@NotNull String name, final boolean createIfNotFound, boolean ensureCanonicalName, NewVirtualFileSystem delegate) { if (name.length() == 0) { return null; } final VirtualFileSystemEntry[] array; final Map<String, VirtualFileSystemEntry> map; final VirtualFileSystemEntry file; synchronized (this) { array = asArray(); if (array == null) { map = ensureAsMap(); file = map.get(name); } else { file = null; map = null; } } if (array != null) { final boolean ignoreCase = !getFileSystem().isCaseSensitive(); for (VirtualFileSystemEntry vf : array) { if (vf.nameMatches(name, ignoreCase)) return vf; } return createIfNotFound ? createAndFindChildWithEventFire(name) : null; } if (file != null) return file; if (ensureCanonicalName) { VirtualFile fake = new FakeVirtualFile(this, name); name = delegate.getCanonicallyCasedName(fake); if (name.length() == 0) return null; } synchronized (this) { // do not extract getId outside the synchronized block since it will cause a concurrency problem. int id = PersistentFS.getId(this, name, delegate); if (id > 0) { // maybe another doFindChild() sneaked in the middle VirtualFileSystemEntry lastTry = map.get(name); if (lastTry != null) return lastTry; final String shorty = new String(name); VirtualFileSystemEntry child = createChild(shorty, id); // So we don't hold whole char[] buffer of a lengthy path map.put(shorty, child); return child; } } return null; } @NotNull public VirtualFileSystemEntry createChild(String name, int id) { final VirtualFileSystemEntry child; final NewVirtualFileSystem fs = getFileSystem(); if (PersistentFS.isDirectory(id)) { child = /*PersistentFS.isSymLink(id) ? new SymlinkDirectory(name, this, fs, id) :*/ new VirtualDirectoryImpl(name, this, fs, id); } else { child = new VirtualFileImpl(name, this, id); assertAccessInTests(child); } if (fs.markNewFilesAsDirty()) { child.markDirty(); } return child; } private static final boolean IS_UNDER_TEAMCITY = System.getProperty("bootstrap.testcases") != null; private static final boolean SHOULD_PERFORM_ACCESS_CHECK = System.getProperty("should.not.perform.access.check") == null; private static final boolean IS_UNIT_TESTS = ApplicationManager.getApplication().isUnitTestMode(); private static final Collection<String> additionalRoots = new THashSet<String>(); @TestOnly public static void allowToAccess(@NotNull String root) { additionalRoots.add(FileUtil.toSystemIndependentName(root)); } @TestOnly private static void assertAccessInTests(VirtualFileSystemEntry child) { if (IS_UNIT_TESTS && IS_UNDER_TEAMCITY && ApplicationManager.getApplication() instanceof ApplicationImpl && ((ApplicationImpl)ApplicationManager.getApplication()).isComponentsCreated() && SHOULD_PERFORM_ACCESS_CHECK) { NewVirtualFileSystem fileSystem = child.getFileSystem(); if (fileSystem != LocalFileSystem.getInstance() && fileSystem != JarFileSystem.getInstance()) { return; } // root' children are loaded always if (child.getParent() == null || child.getParent().getParent() == null) return; Set<String> allowed = allowedRoots(); boolean isUnder = allowed == null; if (!isUnder) { for (String root : allowed) { String childPath = child.getPath(); if (child.getFileSystem() == JarFileSystem.getInstance()) { VirtualFile local = JarFileSystem.getInstance().getVirtualFileForJar(child); childPath = local.getPath(); } if (FileUtil.startsWith(childPath, root)) { isUnder = true; break; } if (root.startsWith(JarFileSystem.PROTOCOL_PREFIX)) { String rootLocalPath = FileUtil.toSystemIndependentName(PathUtil.toPresentableUrl(root)); isUnder = FileUtil.startsWith(childPath, rootLocalPath); if (isUnder) break; } } } if (!isUnder) { if (!allowed.isEmpty()) { assert false : "File accessed outside allowed roots: " + child + ";\n Allowed roots: " + new ArrayList(allowed); } } } } // null means we were unable to get roots, so do not check access private static Set<String> allowedRoots() { if (insideGettingRoots) return null; Project[] openProjects = ProjectManager.getInstance().getOpenProjects(); if (openProjects.length == 0) return null; final Set<String> allowed = new THashSet<String>(); String homePath = PathManager.getHomePath(); allowed.add(FileUtil.toSystemIndependentName(homePath)); try { URL outUrl = Application.class.getResource("/"); String output = new File(outUrl.toURI()).getParentFile().getParentFile().getPath(); allowed.add(FileUtil.toSystemIndependentName(output)); } catch (URISyntaxException ignored) { } String javaHome = SystemProperties.getJavaHome(); allowed.add(FileUtil.toSystemIndependentName(javaHome)); String tempDirectorySpecific = new File(FileUtil.getTempDirectory()).getParent(); allowed.add(FileUtil.toSystemIndependentName(tempDirectorySpecific)); String tempDirectory = System.getProperty("java.io.tmpdir"); allowed.add(FileUtil.toSystemIndependentName(tempDirectory)); String userHome = SystemProperties.getUserHome(); allowed.add(FileUtil.toSystemIndependentName(userHome)); for (Project project : openProjects) { if (!project.isInitialized()) { return null; // all is allowed } for (VirtualFile root : ProjectRootManager.getInstance(project).getContentRoots()) { allowed.add(root.getPath()); } for (VirtualFile root : getAllRoots(project)) { allowed.add(StringUtil.trimEnd(root.getPath(), JarFileSystem.JAR_SEPARATOR)); } String location = project.getLocation(); allowed.add(FileUtil.toSystemIndependentName(location)); } //for (Sdk sdk : ProjectJdkTable.getInstance().getAllJdks()) { // allowed.add(FileUtil.toSystemIndependentName(sdk.getHomePath())); //} for (String root : additionalRoots) { allowed.add(root); } return allowed; } private static boolean insideGettingRoots; private static VirtualFile[] getAllRoots(Project project) { insideGettingRoots = true; Set<VirtualFile> roots = new THashSet<VirtualFile>(); final Module[] modules = ModuleManager.getInstance(project).getModules(); for (Module module : modules) { final ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module); final OrderEntry[] orderEntries = moduleRootManager.getOrderEntries(); for (OrderEntry entry : orderEntries) { VirtualFile[] files; files = entry.getFiles(OrderRootType.CLASSES); ContainerUtil.addAll(roots, files); files = entry.getFiles(OrderRootType.SOURCES); ContainerUtil.addAll(roots, files); files = entry.getFiles(OrderRootType.CLASSES_AND_OUTPUT); ContainerUtil.addAll(roots, files); } } insideGettingRoots = false; return VfsUtil.toVirtualFileArray(roots); } @Nullable private VirtualFileSystemEntry createAndFindChildWithEventFire(@NotNull String name) { final NewVirtualFileSystem delegate = getFileSystem(); VirtualFile fake = new FakeVirtualFile(this, name); if (delegate.exists(fake)) { final String realName = delegate.getCanonicallyCasedName(fake); VFileCreateEvent event = new VFileCreateEvent(null, this, realName, delegate.isDirectory(fake), true); RefreshQueue.getInstance().processSingleEvent(event); return findChild(realName); } else { return null; } } @Override @Nullable public NewVirtualFile refreshAndFindChild(@NotNull String name) { return findChild(name, true, true, getFileSystem()); } @Override @Nullable public synchronized NewVirtualFile findChildIfCached(@NotNull String name) { final VirtualFileSystemEntry[] a = asArray(); if (a != null) { final boolean ignoreCase = !getFileSystem().isCaseSensitive(); for (VirtualFileSystemEntry file : a) { if (file.nameMatches(name, ignoreCase)) return file; } return null; } final Map<String, VirtualFileSystemEntry> map = asMap(); if (map != null) { final VirtualFileSystemEntry file = map.get(name); return file != NULL_VIRTUAL_FILE ? file : null; } return null; } @Override @NotNull public Iterable<VirtualFile> iterInDbChildren() { return ContainerUtil.iterate(getInDbChildren(), new Condition<VirtualFile>() { @Override public boolean value(VirtualFile file) { return file != NULL_VIRTUAL_FILE; } }); } @NotNull private synchronized Collection<VirtualFile> getInDbChildren() { if (myChildren instanceof VirtualFileSystemEntry[]) { return Arrays.asList((VirtualFile[])myChildren); } if (!ourPersistence.wereChildrenAccessed(this)) { return Collections.emptyList(); } if (ourPersistence.areChildrenLoaded(this)) { return Arrays.asList(getChildren()); } final String[] names = PersistentFS.listPersisted(this); NewVirtualFileSystem delegate = PersistentFS.replaceWithNativeFS(getFileSystem()); for (String name : names) { findChild(name, false, false, delegate); } // important: should return a copy here for safe iterations return new ArrayList<VirtualFile>(ensureAsMap().values()); } @Override @NotNull public synchronized VirtualFile[] getChildren() { if (myChildren instanceof VirtualFileSystemEntry[]) { return (VirtualFileSystemEntry[])myChildren; } Pair<String[], int[]> pair = PersistentFS.listAll(this); final int[] childrenIds = pair.second; VirtualFileSystemEntry[] children; if (childrenIds.length == 0) { children = EMPTY_ARRAY; } else { children = new VirtualFileSystemEntry[childrenIds.length]; String[] names = pair.first; final Map<String, VirtualFileSystemEntry> map = asMap(); for (int i = 0; i < children.length; i++) { final int childId = childrenIds[i]; final String name = names[i]; VirtualFileSystemEntry child = map != null ? map.get(name) : null; children[i] = child != null && child != NULL_VIRTUAL_FILE ? child : createChild(name, childId); } } if (getId() > 0) { myChildren = children; } return children; } @Override @Nullable public VirtualFileSystemEntry findChild(@NotNull final String name) { return findChild(name, false, true, getFileSystem()); } @Override @Nullable public NewVirtualFile findChildById(int id) { final NewVirtualFile loaded = findChildByIdIfCached(id); if (loaded != null) { return loaded; } String name = ourPersistence.getName(id); return findChild(name, false, false, getFileSystem()); } @Override public NewVirtualFile findChildByIdIfCached(int id) { final VirtualFile[] a = asArray(); if (a != null) { for (VirtualFile file : a) { NewVirtualFile withId = (NewVirtualFile)file; if (withId.getId() == id) return withId; } return null; } synchronized (this) { final Map<String, VirtualFileSystemEntry> map = asMap(); if (map != null) { for (Map.Entry<String, VirtualFileSystemEntry> entry : map.entrySet()) { VirtualFile file = entry.getValue(); if (file == NULL_VIRTUAL_FILE) continue; NewVirtualFile withId = (NewVirtualFile)file; if (withId.getId() == id) return withId; } } } return null; } @Nullable private VirtualFileSystemEntry[] asArray() { if (myChildren instanceof VirtualFileSystemEntry[]) return (VirtualFileSystemEntry[])myChildren; return null; } @Nullable private Map<String, VirtualFileSystemEntry> asMap() { if (myChildren instanceof Map) { //noinspection unchecked return (Map<String, VirtualFileSystemEntry>)myChildren; } return null; } @NotNull private Map<String, VirtualFileSystemEntry> ensureAsMap() { Map<String, VirtualFileSystemEntry> map; if (myChildren == null) { map = createMap(); myChildren = map; } else { //noinspection unchecked map = (Map<String, VirtualFileSystemEntry>)myChildren; } return map; } public synchronized void addChild(@NotNull VirtualFileSystemEntry file) { final VirtualFileSystemEntry[] a = asArray(); if (a != null) { myChildren = ArrayUtil.append(a, file); } else { ensureAsMap().put(file.getName(), file); } } public synchronized void removeChild(@NotNull VirtualFile file) { final VirtualFileSystemEntry[] a = asArray(); if (a != null) { myChildren = ArrayUtil.remove(a, file); } else { ensureAsMap().put(file.getName(), NULL_VIRTUAL_FILE); } } public synchronized boolean allChildrenLoaded() { return myChildren instanceof VirtualFileSystemEntry[]; } @NotNull public synchronized List<String> getSuspiciousNames() { final Map<String, VirtualFileSystemEntry> map = asMap(); if (map == null) return Collections.emptyList(); List<String> names = new ArrayList<String>(); for (Map.Entry<String, VirtualFileSystemEntry> entry : map.entrySet()) { if (entry.getValue() == NULL_VIRTUAL_FILE) { names.add(entry.getKey()); } } return names; } @Override public boolean isDirectory() { return true; } @Override @NotNull public synchronized Collection<VirtualFile> getCachedChildren() { final Map<String, VirtualFileSystemEntry> map = asMap(); if (map != null) { Set<VirtualFile> files = new THashSet<VirtualFile>(map.values()); files.remove(NULL_VIRTUAL_FILE); return files; } final VirtualFile[] a = asArray(); if (a != null) return Arrays.asList(a); return Collections.emptyList(); } @NotNull private Map<String, VirtualFileSystemEntry> createMap() { return getFileSystem().isCaseSensitive() ? new THashMap<String, VirtualFileSystemEntry>() : new THashMap<String, VirtualFileSystemEntry>(CaseInsensitiveStringHashingStrategy.INSTANCE); } @TestOnly public synchronized void cleanupCachedChildren(@NotNull Set<VirtualFile> survivors) { if (survivors.contains(this)) { for (VirtualFile file : getCachedChildren()) { if (file instanceof VirtualDirectoryImpl) { ((VirtualDirectoryImpl)file).cleanupCachedChildren(survivors); } } } else { myChildren = null; } } @Override public InputStream getInputStream() throws IOException { throw new IOException("getInputStream() must not be called against a directory: " + getUrl()); } @Override @NotNull public OutputStream getOutputStream(final Object requestor, final long newModificationStamp, final long newTimeStamp) throws IOException { throw new IOException("getOutputStream() must not be called against a directory: " + getUrl()); } }
platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/impl/VirtualDirectoryImpl.java
/* * Copyright 2000-2011 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.impl; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.application.impl.ApplicationImpl; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.roots.OrderEntry; import com.intellij.openapi.roots.OrderRootType; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.JarFileSystem; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.newvfs.NewVirtualFile; import com.intellij.openapi.vfs.newvfs.NewVirtualFileSystem; import com.intellij.openapi.vfs.newvfs.RefreshQueue; import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent; import com.intellij.openapi.vfs.newvfs.persistent.PersistentFS; import com.intellij.util.ArrayUtil; import com.intellij.util.PathUtil; import com.intellij.util.SystemProperties; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.text.CaseInsensitiveStringHashingStrategy; import gnu.trove.THashMap; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URISyntaxException; import java.net.URL; import java.util.*; /** * @author max */ public class VirtualDirectoryImpl extends VirtualFileSystemEntry { private static final VirtualFileSystemEntry NULL_VIRTUAL_FILE = new VirtualFileImpl("*?;%NULL", null, -42); private final NewVirtualFileSystem myFS; // guarded by this protected Object myChildren; // Either HashMap<String, VFile> or VFile[] public VirtualDirectoryImpl(@NotNull String name, final VirtualDirectoryImpl parent, @NotNull NewVirtualFileSystem fs, final int id) { super(name, parent, id); myFS = fs; } @Override @NotNull public NewVirtualFileSystem getFileSystem() { return myFS; } @Nullable private VirtualFileSystemEntry findChild(@NotNull String name, final boolean createIfNotFound, boolean ensureCanonicalName, NewVirtualFileSystem delegate) { final VirtualFileSystemEntry result = doFindChild(name, createIfNotFound, ensureCanonicalName, delegate); if (result == NULL_VIRTUAL_FILE) { return createIfNotFound ? createAndFindChildWithEventFire(name) : null; } if (result == null) { synchronized (this) { Map<String, VirtualFileSystemEntry> map = asMap(); if (map != null) { map.put(name, NULL_VIRTUAL_FILE); } } } return result; } @Nullable private VirtualFileSystemEntry doFindChild(@NotNull String name, final boolean createIfNotFound, boolean ensureCanonicalName, NewVirtualFileSystem delegate) { if (name.length() == 0) { return null; } final VirtualFileSystemEntry[] array; final Map<String, VirtualFileSystemEntry> map; final VirtualFileSystemEntry file; synchronized (this) { array = asArray(); if (array == null) { map = ensureAsMap(); file = map.get(name); } else { file = null; map = null; } } if (array != null) { final boolean ignoreCase = !getFileSystem().isCaseSensitive(); for (VirtualFileSystemEntry vf : array) { if (vf.nameMatches(name, ignoreCase)) return vf; } return createIfNotFound ? createAndFindChildWithEventFire(name) : null; } if (file != null) return file; if (ensureCanonicalName) { VirtualFile fake = new FakeVirtualFile(this, name); name = delegate.getCanonicallyCasedName(fake); if (name.length() == 0) return null; } synchronized (this) { // do not extract getId outside the synchronized block since it will cause a concurrency problem. int id = PersistentFS.getId(this, name, delegate); if (id > 0) { // maybe another doFindChild() sneaked in the middle VirtualFileSystemEntry lastTry = map.get(name); if (lastTry != null) return lastTry; final String shorty = new String(name); VirtualFileSystemEntry child = createChild(shorty, id); // So we don't hold whole char[] buffer of a lengthy path map.put(shorty, child); return child; } } return null; } @NotNull public VirtualFileSystemEntry createChild(String name, int id) { final VirtualFileSystemEntry child; final NewVirtualFileSystem fs = getFileSystem(); if (PersistentFS.isDirectory(id)) { child = /*PersistentFS.isSymLink(id) ? new SymlinkDirectory(name, this, fs, id) :*/ new VirtualDirectoryImpl(name, this, fs, id); } else { child = new VirtualFileImpl(name, this, id); assertAccessInTests(child); } if (fs.markNewFilesAsDirty()) { child.markDirty(); } return child; } private static final boolean IS_UNDER_TEAMCITY = System.getProperty("bootstrap.testcases") != null; private static final boolean SHOULD_NOT_PERFORM_ACCESS_CHECK = System.getProperty("should.not.perform.access.check") != null; private static final boolean IS_UNIT_TESTS = ApplicationManager.getApplication().isUnitTestMode(); private static final Collection<String> additionalRoots = new THashSet<String>(); @TestOnly public static void allowToAccess(@NotNull String root) { additionalRoots.add(FileUtil.toSystemIndependentName(root)); } @TestOnly private static void assertAccessInTests(VirtualFileSystemEntry child) { if (IS_UNIT_TESTS && IS_UNDER_TEAMCITY && ApplicationManager.getApplication() instanceof ApplicationImpl && ((ApplicationImpl)ApplicationManager.getApplication()).isComponentsCreated() && !SHOULD_NOT_PERFORM_ACCESS_CHECK) { NewVirtualFileSystem fileSystem = child.getFileSystem(); if (fileSystem != LocalFileSystem.getInstance() && fileSystem != JarFileSystem.getInstance()) { return; } // root' children are loaded always if (child.getParent() == null || child.getParent().getParent() == null) return; Set<String> allowed = allowedRoots(); boolean isUnder = allowed == null; if (!isUnder) { for (String root : allowed) { String childPath = child.getPath(); if (child.getFileSystem() == JarFileSystem.getInstance()) { VirtualFile local = JarFileSystem.getInstance().getVirtualFileForJar(child); childPath = local.getPath(); } if (FileUtil.startsWith(childPath, root)) { isUnder = true; break; } if (root.startsWith(JarFileSystem.PROTOCOL_PREFIX)) { String rootLocalPath = FileUtil.toSystemIndependentName(PathUtil.toPresentableUrl(root)); isUnder = FileUtil.startsWith(childPath, rootLocalPath); if (isUnder) break; } } } if (!isUnder) { if (!allowed.isEmpty()) { assert false : "File accessed outside allowed roots: " + child + ";\n Allowed roots: " + new ArrayList(allowed); } } } } // null means we were unable to get roots, so do not check access private static Set<String> allowedRoots() { if (insideGettingRoots) return null; Project[] openProjects = ProjectManager.getInstance().getOpenProjects(); if (openProjects.length == 0) return null; final Set<String> allowed = new THashSet<String>(); String homePath = PathManager.getHomePath(); allowed.add(FileUtil.toSystemIndependentName(homePath)); try { URL outUrl = Application.class.getResource("/"); String output = new File(outUrl.toURI()).getParentFile().getParentFile().getPath(); allowed.add(FileUtil.toSystemIndependentName(output)); } catch (URISyntaxException ignored) { } String javaHome = SystemProperties.getJavaHome(); allowed.add(FileUtil.toSystemIndependentName(javaHome)); String tempDirectorySpecific = new File(FileUtil.getTempDirectory()).getParent(); allowed.add(FileUtil.toSystemIndependentName(tempDirectorySpecific)); String tempDirectory = System.getProperty("java.io.tmpdir"); allowed.add(FileUtil.toSystemIndependentName(tempDirectory)); String userHome = SystemProperties.getUserHome(); allowed.add(FileUtil.toSystemIndependentName(userHome)); for (Project project : openProjects) { if (!project.isInitialized()) { return null; // all is allowed } for (VirtualFile root : ProjectRootManager.getInstance(project).getContentRoots()) { allowed.add(root.getPath()); } for (VirtualFile root : getAllRoots(project)) { allowed.add(StringUtil.trimEnd(root.getPath(), JarFileSystem.JAR_SEPARATOR)); } String location = project.getLocation(); allowed.add(FileUtil.toSystemIndependentName(location)); } //for (Sdk sdk : ProjectJdkTable.getInstance().getAllJdks()) { // allowed.add(FileUtil.toSystemIndependentName(sdk.getHomePath())); //} for (String root : additionalRoots) { allowed.add(root); } return allowed; } private static boolean insideGettingRoots; private static VirtualFile[] getAllRoots(Project project) { insideGettingRoots = true; Set<VirtualFile> roots = new THashSet<VirtualFile>(); final Module[] modules = ModuleManager.getInstance(project).getModules(); for (Module module : modules) { final ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module); final OrderEntry[] orderEntries = moduleRootManager.getOrderEntries(); for (OrderEntry entry : orderEntries) { VirtualFile[] files; files = entry.getFiles(OrderRootType.CLASSES); ContainerUtil.addAll(roots, files); files = entry.getFiles(OrderRootType.SOURCES); ContainerUtil.addAll(roots, files); files = entry.getFiles(OrderRootType.CLASSES_AND_OUTPUT); ContainerUtil.addAll(roots, files); } } insideGettingRoots = false; return VfsUtil.toVirtualFileArray(roots); } @Nullable private VirtualFileSystemEntry createAndFindChildWithEventFire(@NotNull String name) { final NewVirtualFileSystem delegate = getFileSystem(); VirtualFile fake = new FakeVirtualFile(this, name); if (delegate.exists(fake)) { final String realName = delegate.getCanonicallyCasedName(fake); VFileCreateEvent event = new VFileCreateEvent(null, this, realName, delegate.isDirectory(fake), true); RefreshQueue.getInstance().processSingleEvent(event); return findChild(realName); } else { return null; } } @Override @Nullable public NewVirtualFile refreshAndFindChild(@NotNull String name) { return findChild(name, true, true, getFileSystem()); } @Override @Nullable public synchronized NewVirtualFile findChildIfCached(@NotNull String name) { final VirtualFileSystemEntry[] a = asArray(); if (a != null) { final boolean ignoreCase = !getFileSystem().isCaseSensitive(); for (VirtualFileSystemEntry file : a) { if (file.nameMatches(name, ignoreCase)) return file; } return null; } final Map<String, VirtualFileSystemEntry> map = asMap(); if (map != null) { final VirtualFileSystemEntry file = map.get(name); return file != NULL_VIRTUAL_FILE ? file : null; } return null; } @Override @NotNull public Iterable<VirtualFile> iterInDbChildren() { return ContainerUtil.iterate(getInDbChildren(), new Condition<VirtualFile>() { @Override public boolean value(VirtualFile file) { return file != NULL_VIRTUAL_FILE; } }); } @NotNull private synchronized Collection<VirtualFile> getInDbChildren() { if (myChildren instanceof VirtualFileSystemEntry[]) { return Arrays.asList((VirtualFile[])myChildren); } if (!ourPersistence.wereChildrenAccessed(this)) { return Collections.emptyList(); } if (ourPersistence.areChildrenLoaded(this)) { return Arrays.asList(getChildren()); } final String[] names = PersistentFS.listPersisted(this); NewVirtualFileSystem delegate = PersistentFS.replaceWithNativeFS(getFileSystem()); for (String name : names) { findChild(name, false, false, delegate); } // important: should return a copy here for safe iterations return new ArrayList<VirtualFile>(ensureAsMap().values()); } @Override @NotNull public synchronized VirtualFile[] getChildren() { if (myChildren instanceof VirtualFileSystemEntry[]) { return (VirtualFileSystemEntry[])myChildren; } Pair<String[], int[]> pair = PersistentFS.listAll(this); final int[] childrenIds = pair.second; VirtualFileSystemEntry[] children; if (childrenIds.length == 0) { children = EMPTY_ARRAY; } else { children = new VirtualFileSystemEntry[childrenIds.length]; String[] names = pair.first; final Map<String, VirtualFileSystemEntry> map = asMap(); for (int i = 0; i < children.length; i++) { final int childId = childrenIds[i]; final String name = names[i]; VirtualFileSystemEntry child = map != null ? map.get(name) : null; children[i] = child != null && child != NULL_VIRTUAL_FILE ? child : createChild(name, childId); } } if (getId() > 0) { myChildren = children; } return children; } @Override @Nullable public VirtualFileSystemEntry findChild(@NotNull final String name) { return findChild(name, false, true, getFileSystem()); } @Override @Nullable public NewVirtualFile findChildById(int id) { final NewVirtualFile loaded = findChildByIdIfCached(id); if (loaded != null) { return loaded; } String name = ourPersistence.getName(id); return findChild(name, false, false, getFileSystem()); } @Override public NewVirtualFile findChildByIdIfCached(int id) { final VirtualFile[] a = asArray(); if (a != null) { for (VirtualFile file : a) { NewVirtualFile withId = (NewVirtualFile)file; if (withId.getId() == id) return withId; } return null; } synchronized (this) { final Map<String, VirtualFileSystemEntry> map = asMap(); if (map != null) { for (Map.Entry<String, VirtualFileSystemEntry> entry : map.entrySet()) { VirtualFile file = entry.getValue(); if (file == NULL_VIRTUAL_FILE) continue; NewVirtualFile withId = (NewVirtualFile)file; if (withId.getId() == id) return withId; } } } return null; } @Nullable private VirtualFileSystemEntry[] asArray() { if (myChildren instanceof VirtualFileSystemEntry[]) return (VirtualFileSystemEntry[])myChildren; return null; } @Nullable private Map<String, VirtualFileSystemEntry> asMap() { if (myChildren instanceof Map) { //noinspection unchecked return (Map<String, VirtualFileSystemEntry>)myChildren; } return null; } @NotNull private Map<String, VirtualFileSystemEntry> ensureAsMap() { Map<String, VirtualFileSystemEntry> map; if (myChildren == null) { map = createMap(); myChildren = map; } else { //noinspection unchecked map = (Map<String, VirtualFileSystemEntry>)myChildren; } return map; } public synchronized void addChild(@NotNull VirtualFileSystemEntry file) { final VirtualFileSystemEntry[] a = asArray(); if (a != null) { myChildren = ArrayUtil.append(a, file); } else { ensureAsMap().put(file.getName(), file); } } public synchronized void removeChild(@NotNull VirtualFile file) { final VirtualFileSystemEntry[] a = asArray(); if (a != null) { myChildren = ArrayUtil.remove(a, file); } else { ensureAsMap().put(file.getName(), NULL_VIRTUAL_FILE); } } public synchronized boolean allChildrenLoaded() { return myChildren instanceof VirtualFileSystemEntry[]; } @NotNull public synchronized List<String> getSuspiciousNames() { final Map<String, VirtualFileSystemEntry> map = asMap(); if (map == null) return Collections.emptyList(); List<String> names = new ArrayList<String>(); for (Map.Entry<String, VirtualFileSystemEntry> entry : map.entrySet()) { if (entry.getValue() == NULL_VIRTUAL_FILE) { names.add(entry.getKey()); } } return names; } @Override public boolean isDirectory() { return true; } @Override @NotNull public synchronized Collection<VirtualFile> getCachedChildren() { final Map<String, VirtualFileSystemEntry> map = asMap(); if (map != null) { Set<VirtualFile> files = new THashSet<VirtualFile>(map.values()); files.remove(NULL_VIRTUAL_FILE); return files; } final VirtualFile[] a = asArray(); if (a != null) return Arrays.asList(a); return Collections.emptyList(); } @NotNull private Map<String, VirtualFileSystemEntry> createMap() { return getFileSystem().isCaseSensitive() ? new THashMap<String, VirtualFileSystemEntry>() : new THashMap<String, VirtualFileSystemEntry>(CaseInsensitiveStringHashingStrategy.INSTANCE); } @TestOnly public synchronized void cleanupCachedChildren(@NotNull Set<VirtualFile> survivors) { if (survivors.contains(this)) { for (VirtualFile file : getCachedChildren()) { if (file instanceof VirtualDirectoryImpl) { ((VirtualDirectoryImpl)file).cleanupCachedChildren(survivors); } } } else { myChildren = null; } } @Override public InputStream getInputStream() throws IOException { throw new IOException("getInputStream() must not be called against a directory: " + getUrl()); } @Override @NotNull public OutputStream getOutputStream(final Object requestor, final long newModificationStamp, final long newTimeStamp) throws IOException { throw new IOException("getOutputStream() must not be called against a directory: " + getUrl()); } }
removed double negation
platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/impl/VirtualDirectoryImpl.java
removed double negation
<ide><path>latform/platform-impl/src/com/intellij/openapi/vfs/newvfs/impl/VirtualDirectoryImpl.java <ide> <ide> private static final boolean IS_UNDER_TEAMCITY = System.getProperty("bootstrap.testcases") != null; <ide> <del> private static final boolean SHOULD_NOT_PERFORM_ACCESS_CHECK = System.getProperty("should.not.perform.access.check") != null; <add> private static final boolean SHOULD_PERFORM_ACCESS_CHECK = System.getProperty("should.not.perform.access.check") == null; <ide> <ide> private static final boolean IS_UNIT_TESTS = ApplicationManager.getApplication().isUnitTestMode(); <ide> <ide> ApplicationManager.getApplication() instanceof ApplicationImpl && <ide> ((ApplicationImpl)ApplicationManager.getApplication()).isComponentsCreated() <ide> && <del> !SHOULD_NOT_PERFORM_ACCESS_CHECK) { <add> SHOULD_PERFORM_ACCESS_CHECK) { <ide> NewVirtualFileSystem fileSystem = child.getFileSystem(); <ide> if (fileSystem != LocalFileSystem.getInstance() && fileSystem != JarFileSystem.getInstance()) { <ide> return;
Java
apache-2.0
ad0873be85994968690e2c53101324e00b2aafc4
0
sazibislam/codeAlgorithom,mission-peace/interview,rtkasodariya/interview,mission-peace/interview,rtkasodariya/interview,mission-peace/interview
package com.interview.dynamic; import java.util.HashMap; import java.util.Map; /** * Date 04/04/2014 * @author Tushar Roy * * 0/1 Knapsack Problem - Given items of certain weights/values and maximum allowed weight * how to pick items to pick items from this set to maximize sum of value of items such that * sum of weights is less than or equal to maximum allowed weight. * * Time complexity - O(W*total items) * * References - * http://www.geeksforgeeks.org/dynamic-programming-set-10-0-1-knapsack-problem/ * https://en.wikipedia.org/wiki/Knapsack_problem */ public class Knapsack01 { /** * Solves 0/1 knapsack in bottom up dynamic programming */ public int bottomUpDP(int val[], int wt[], int W){ int K[][] = new int[val.length+1][W+1]; for(int i=0; i <= val.length; i++){ for(int j=0; j <= W; j++){ if(i == 0 || j == 0){ K[i][j] = 0; continue; } if(j - wt[i-1] >= 0){ K[i][j] = Math.max(K[i-1][j], K[i-1][j-wt[i-1]] + val[i-1]); }else{ K[i][j] = K[i-1][j]; } } } return K[val.length][W]; } /** * Key for memoization */ class Index { int remainingWeight; int remainingItems; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Index index = (Index) o; if (remainingWeight != index.remainingWeight) return false; return remainingItems == index.remainingItems; } @Override public int hashCode() { int result = remainingWeight; result = 31 * result + remainingItems; return result; } } /** * Solves 0/1 knapsack in top down DP */ public int topDownRecursive(int values[], int weights[], int W) { //map of key(remainingWeight, remainingCount) to maximumValue they can get. Map<Index, Integer> map = new HashMap<>(); return topDownRecursiveUtil(values, weights, W, values.length, 0, map); } public int topDownRecursiveUtil(int values[], int weights[], int remainingWeight, int totalItems, int currentItem, Map<Index, Integer> map) { //if currentItem exceeds total item count or remainingWeight is less than 0 then //just return with 0; if(currentItem >= totalItems || remainingWeight <= 0) { return 0; } //fom a key based on remainingWeight and remainingCount Index key = new Index(); key.remainingItems = totalItems - currentItem -1; key.remainingWeight = remainingWeight; //see if key exists in map. If so then return the maximumValue for key stored in map. if(map.containsKey(key)) { return map.get(key); } int maxValue; //if weight of item is more than remainingWeight then try next item by skipping current item if(remainingWeight < weights[currentItem]) { maxValue = topDownRecursiveUtil(values, weights, remainingWeight, totalItems, currentItem + 1, map); } else { //try to get maximumValue of either by picking the currentItem or not picking currentItem maxValue = Math.max(values[currentItem] + topDownRecursiveUtil(values, weights, remainingWeight - weights[currentItem], totalItems, currentItem + 1, map), topDownRecursiveUtil(values, weights, remainingWeight, totalItems, currentItem + 1, map)); } //memoize the key with maxValue found to avoid recalculation map.put(key, maxValue); return maxValue; } public static void main(String args[]){ Knapsack01 k = new Knapsack01(); int val[] = {22, 20, 15, 30, 24, 54, 21, 32, 18, 25}; int wt[] = {4, 2, 3, 5, 5, 6, 9, 7, 8, 10}; int r = k.bottomUpDP(val, wt, 30); int r1 = k.topDownRecursive(val, wt, 30); System.out.println(r); System.out.println(r1); } }
src/com/interview/dynamic/Knapsack01.java
package com.interview.dynamic; import java.util.HashMap; import java.util.Map; /** * Date 04/04/2014 * @author Tushar Roy * * 0/1 Knapsack Problem - Given items of certain weights/values and maximum allowed weight * how to pick items to pick items from this set to maximize sum of value of items such that * sum of weights is less than or equal to maximum allowed weight. * * Time complexity - O(W*total items) * * References - * http://www.geeksforgeeks.org/dynamic-programming-set-10-0-1-knapsack-problem/ * https://en.wikipedia.org/wiki/Knapsack_problem */ public class Knapsack01 { /** * Solves 0/1 knapsack in bottom up dynamic programming */ public int bottomUpDP(int val[], int wt[], int W){ int K[][] = new int[val.length+1][W+1]; for(int i=0; i <= val.length; i++){ for(int j=0; j <= W; j++){ if(i == 0 || j == 0){ K[i][j] = 0; continue; } if(j - wt[i-1] >= 0){ K[i][j] = Math.max(K[i-1][j], K[i-1][j-wt[i-1]] + val[i-1]); }else{ K[i][j] = K[i-1][j]; } } } return K[val.length][W]; } /** * Key for memoization */ class Index { int remainingWeight; int remainingItems; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Index index = (Index) o; if (remainingWeight != index.remainingWeight) return false; return remainingItems == index.remainingItems; } @Override public int hashCode() { int result = remainingWeight; result = 31 * result + remainingItems; return result; } } /** * Solves 0/1 knapsack in top down DP */ public int topDownRecursive(int val[], int wt[], int W) { //map of key(remainingWeight, remainingCount) to maximumValue they can get. Map<Index, Integer> map = new HashMap<>(); return topDownRecursiveUtil(val, wt, W, val.length, 0, map); } public int topDownRecursiveUtil(int values[], int weights[], int remainingWeight, int totalItems, int currentItem, Map<Index, Integer> map) { //if currentItem exceeds total item count or remainingWeight is less than 0 then //just return with 0; if(currentItem >= totalItems || remainingWeight <= 0) { return 0; } //fom a key based on remainingWeight and remainingCount Index key = new Index(); key.remainingItems = totalItems - currentItem -1; key.remainingWeight = remainingWeight; //see if key exists in map. If so then return the maximumValue for key stored in map. if(map.containsKey(key)) { return map.get(key); } int maxValue; //if weight of item is more than remainingWeight then try next item by skipping current item if(remainingWeight < weights[currentItem]) { maxValue = topDownRecursiveUtil(values, weights, remainingWeight, totalItems, currentItem + 1, map); } else { //try to get maximumValue of either by picking the currentItem or not picking currentItem maxValue = Math.max(values[currentItem] + topDownRecursiveUtil(values, weights, remainingWeight - weights[currentItem], totalItems, currentItem + 1, map), topDownRecursiveUtil(values, weights, remainingWeight, totalItems, currentItem + 1, map)); } //memoize the key with maxValue found to avoid recalculation map.put(key, maxValue); return maxValue; } public static void main(String args[]){ Knapsack01 k = new Knapsack01(); int val[] = {22, 20, 15, 30, 24, 54, 21, 32, 18, 25}; int wt[] = {4, 2, 3, 5, 5, 6, 9, 7, 8, 10}; int r = k.bottomUpDP(val, wt, 30); int r1 = k.topDownRecursive(val, wt, 30); System.out.println(r); System.out.println(r1); } }
updating 0/1 knapsack
src/com/interview/dynamic/Knapsack01.java
updating 0/1 knapsack
<ide><path>rc/com/interview/dynamic/Knapsack01.java <ide> /** <ide> * Solves 0/1 knapsack in top down DP <ide> */ <del> public int topDownRecursive(int val[], int wt[], int W) { <add> public int topDownRecursive(int values[], int weights[], int W) { <ide> //map of key(remainingWeight, remainingCount) to maximumValue they can get. <ide> Map<Index, Integer> map = new HashMap<>(); <del> return topDownRecursiveUtil(val, wt, W, val.length, 0, map); <add> return topDownRecursiveUtil(values, weights, W, values.length, 0, map); <ide> } <ide> <ide> public int topDownRecursiveUtil(int values[], int weights[], int remainingWeight, int totalItems, int currentItem, Map<Index, Integer> map) { <ide> <ide> } <ide> <del> <ide> public static void main(String args[]){ <ide> Knapsack01 k = new Knapsack01(); <ide> int val[] = {22, 20, 15, 30, 24, 54, 21, 32, 18, 25};
Java
apache-2.0
281cfde628629285ed45698e31a5b05fe3e9b8bf
0
BennyKok/OpenLauncher,OpenLauncherTeam/openlauncher
package com.benny.openlauncher.activity; import android.app.Activity; import android.app.ActivityOptions; import android.app.AlarmManager; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProviderInfo; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ActivityInfo; import android.content.res.Resources; import android.graphics.Point; import android.net.Uri; import android.os.Build.VERSION; import android.os.Bundle; import android.provider.Settings; import android.provider.Settings.SettingNotFoundException; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.DrawerLayout.DrawerListener; import android.util.Log; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.view.ViewGroup.MarginLayoutParams; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.FrameLayout; import android.widget.TextView; import com.afollestad.materialdialogs.DialogAction; import com.afollestad.materialdialogs.MaterialDialog; import com.benny.openlauncher.BuildConfig; import com.benny.openlauncher.R; import com.benny.openlauncher.activity.homeparts.HpAppDrawer; import com.benny.openlauncher.activity.homeparts.HpDesktopPickAction; import com.benny.openlauncher.activity.homeparts.HpDragNDrop; import com.benny.openlauncher.activity.homeparts.HpInitSetup; import com.benny.openlauncher.activity.homeparts.HpSearchBar; import com.benny.openlauncher.interfaces.AppDeleteListener; import com.benny.openlauncher.manager.Setup; import com.benny.openlauncher.manager.Setup.DataManager; import com.benny.openlauncher.model.Item; import com.benny.openlauncher.model.Item.Type; import com.benny.openlauncher.util.App; import com.benny.openlauncher.util.AppManager; import com.benny.openlauncher.util.AppSettings; import com.benny.openlauncher.util.AppUpdateReceiver; import com.benny.openlauncher.util.Definitions.ItemPosition; import com.benny.openlauncher.util.LauncherAction; import com.benny.openlauncher.util.LauncherAction.Action; import com.benny.openlauncher.util.ShortcutReceiver; import com.benny.openlauncher.util.Tool; import com.benny.openlauncher.viewutil.DialogHelper; import com.benny.openlauncher.viewutil.IconListAdapter; import com.benny.openlauncher.viewutil.WidgetHost; import com.benny.openlauncher.widget.AppDrawerController; import com.benny.openlauncher.widget.AppItemView; import com.benny.openlauncher.widget.CalendarDropDownView; import com.benny.openlauncher.widget.CellContainer; import com.benny.openlauncher.widget.Desktop; import com.benny.openlauncher.widget.Desktop.OnDesktopEditListener; import com.benny.openlauncher.widget.DesktopOptionView; import com.benny.openlauncher.widget.DesktopOptionView.DesktopOptionViewListener; import com.benny.openlauncher.widget.Dock; import com.benny.openlauncher.widget.DragNDropLayout; import com.benny.openlauncher.widget.DragOptionView; import com.benny.openlauncher.widget.GroupPopupView; import com.benny.openlauncher.widget.PagerIndicator; import com.benny.openlauncher.widget.SearchBar; import com.benny.openlauncher.widget.SmoothViewPager; import com.benny.openlauncher.widget.SwipeListView; import net.gsantner.opoc.util.ContextUtils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import kotlin.TypeCastException; import kotlin.jvm.JvmOverloads; public final class Home extends Activity implements OnDesktopEditListener, DesktopOptionViewListener, DrawerListener { public static final Companion Companion = new Companion(); public static final int REQUEST_CREATE_APPWIDGET = 0x6475; public static final int REQUEST_PERMISSION_STORAGE = 0x3648; public static final int REQUEST_PICK_APPWIDGET = 0x2678; @Nullable private static Resources _resources; private static final IntentFilter _appUpdateIntentFilter = new IntentFilter(); @Nullable private static WidgetHost _appWidgetHost; @NonNull public static AppWidgetManager _appWidgetManager; private static boolean _consumeNextResume; @NonNull public static DataManager _db; public static float _itemTouchX; public static float _itemTouchY; @Nullable public static Home _launcher; private static final IntentFilter _shortcutIntentFilter = new IntentFilter(); private static final IntentFilter _timeChangesIntentFilter = new IntentFilter(); private HashMap deleteMefindViewCache; private final AppUpdateReceiver _appUpdateReceiver = new AppUpdateReceiver(); private int cx; private int cy; private int rad; private final ShortcutReceiver _shortcutReceiver = new ShortcutReceiver(); private BroadcastReceiver _timeChangedReceiver; public static final class Companion { private Companion() { } @Nullable public final Home getLauncher() { return _launcher; } public final void setLauncher(@Nullable Home v) { _launcher = v; } @Nullable public final Resources get_resources() { return _resources; } public final void set_resources(@Nullable Resources v) { _resources = v; } @NonNull public final DataManager getDb() { return _db; } public final void setDb(@NonNull DataManager v) { _db = v; } @Nullable public final WidgetHost getAppWidgetHost() { return _appWidgetHost; } public final void setAppWidgetHost(@Nullable WidgetHost v) { _appWidgetHost = v; } @NonNull public final AppWidgetManager getAppWidgetManager() { return _appWidgetManager; } public final void setAppWidgetManager(@NonNull AppWidgetManager v) { _appWidgetManager = v; } public final float getItemTouchX() { return _itemTouchX; } public final void setItemTouchX(float v) { _itemTouchX = v; } public final float getItemTouchY() { return _itemTouchY; } public final void setItemTouchY(float v) { _itemTouchY = v; } public final boolean getConsumeNextResume() { return _consumeNextResume; } public final void setConsumeNextResume(boolean v) { _consumeNextResume = v; } private final IntentFilter getTimeChangesIntentFilter() { return _timeChangesIntentFilter; } private final IntentFilter getAppUpdateIntentFilter() { return _appUpdateIntentFilter; } private final IntentFilter getShortcutIntentFilter() { return _shortcutIntentFilter; } } @JvmOverloads public final void openAppDrawer() { openAppDrawer$default(this, null, 0, 0, 7, null); } @JvmOverloads public final void openAppDrawer(@Nullable View view) { openAppDrawer$default(this, view, 0, 0, 6, null); } @JvmOverloads public final void updateDock(boolean z) { updateDock$default(this, z, 0, 2, null); } static { Companion.getTimeChangesIntentFilter().addAction("android.intent.action.TIME_TICK"); Companion.getTimeChangesIntentFilter().addAction("android.intent.action.TIMEZONE_CHANGED"); Companion.getTimeChangesIntentFilter().addAction("android.intent.action.TIME_SET"); Companion.getAppUpdateIntentFilter().addAction("android.intent.action.PACKAGE_ADDED"); Companion.getAppUpdateIntentFilter().addAction("android.intent.action.PACKAGE_REMOVED"); Companion.getAppUpdateIntentFilter().addAction("android.intent.action.PACKAGE_CHANGED"); Companion.getAppUpdateIntentFilter().addDataScheme("package"); Companion.getShortcutIntentFilter().addAction("com.android.launcher.action.INSTALL_SHORTCUT"); } @NonNull public final DrawerLayout getDrawerLayout() { return findViewById(R.id.drawer_layout); } protected void onCreate(@Nullable Bundle savedInstanceState) { Companion.setLauncher(this); Companion.set_resources(getResources()); ContextUtils contextUtils = new ContextUtils(getApplicationContext()); AppSettings appSettings = AppSettings.get(); contextUtils.setAppLanguage(appSettings.getLanguage()); super.onCreate(savedInstanceState); if (!Setup.wasInitialised()) { Setup.init(new HpInitSetup(this)); } AppSettings appSettings2 = Setup.appSettings(); if (appSettings2.isSearchBarTimeEnabled()) { _timeChangedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) { updateSearchClock(); } } }; } Companion.setLauncher(this); Companion companion = Companion; DataManager dataManager = Setup.dataManager(); companion.setDb(dataManager); setContentView(getLayoutInflater().inflate(R.layout.activity_home, null)); if (VERSION.SDK_INT >= 21) { Window window = getWindow(); View decorView = window.getDecorView(); decorView.setSystemUiVisibility(1536); } init(); } public final void onStartApp(@NonNull Context context, @NonNull Intent intent, @Nullable View view) { ComponentName component = intent.getComponent(); if (BuildConfig.APPLICATION_ID.equals(component.getPackageName())) { LauncherAction.RunAction(Action.LauncherSettings, context); Companion.setConsumeNextResume(true); } else { try { context.startActivity(intent, getActivityAnimationOpts(view)); Companion.setConsumeNextResume(true); } catch (Exception e) { Tool.toast(context, (int) R.string.toast_app_uninstalled); } } } public final void onStartApp(@NonNull Context context, @NonNull App app, @Nullable View view) { if (BuildConfig.APPLICATION_ID.equals(app._packageName)) { LauncherAction.RunAction(Action.LauncherSettings, context); Companion.setConsumeNextResume(true); } else { try { Intent intent = new Intent("android.intent.action.MAIN"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setClassName(app._packageName, app._className); context.startActivity(intent, getActivityAnimationOpts(view)); Companion.setConsumeNextResume(true); } catch (Exception e) { Tool.toast(context, (int) R.string.toast_app_uninstalled); } } } protected void initAppManager() { Setup.appLoader().addUpdateListener(new AppManager.AppUpdatedListener() { @Override public boolean onAppUpdated(List<App> it) { if ((getDesktop() == null)) { return false; } AppSettings appSettings = Setup.appSettings(); if (appSettings.getDesktopStyle() != 1) { appSettings = Setup.appSettings(); if (appSettings.isAppFirstLaunch()) { appSettings = Setup.appSettings(); appSettings.setAppFirstLaunch(false); Item appDrawerBtnItem = Item.newActionItem(8); appDrawerBtnItem._x = 2; Companion.getDb().saveItem(appDrawerBtnItem, 0, ItemPosition.Dock); } } appSettings = Setup.appSettings(); if (appSettings.getDesktopStyle() == 0) { getDesktop().initDesktopNormal(Home.this); } else { appSettings = Setup.appSettings(); if (appSettings.getDesktopStyle() == 1) { getDesktop().initDesktopShowAll(Home.this, Home.this); } } getDock().initDockItem(Home.this); return true; } }); Setup.appLoader().addDeleteListener(new AppDeleteListener() { @Override public boolean onAppDeleted(List<App> apps) { AppSettings appSettings = Setup.appSettings(); if (appSettings.getDesktopStyle() == 0) { ((Desktop) findViewById(R.id.desktop)).initDesktopNormal(Home.this); } else { appSettings = Setup.appSettings(); if (appSettings.getDesktopStyle() == 1) { ((Desktop) findViewById(R.id.desktop)).initDesktopShowAll(Home.this, Home.this); } } ((Dock) findViewById(R.id.dock)).initDockItem(Home.this); setToHomePage(); return false; } }); AppManager.getInstance(this).init(); } protected void initViews() { new HpSearchBar(this, (SearchBar) findViewById(R.id.searchBar), (CalendarDropDownView) findViewById(R.id.calendarDropDownView)).initSearchBar(); initDock(); ((AppDrawerController) findViewById(R.id.appDrawerController)).init(); ((AppDrawerController) findViewById(R.id.appDrawerController)).setHome(this); ((DragOptionView) findViewById(R.id.dragOptionPanel)).setHome(this); ((Desktop) findViewById(R.id.desktop)).init(); Desktop desktop = (Desktop) findViewById(R.id.desktop); desktop.setDesktopEditListener(this); ((DesktopOptionView) findViewById(R.id.desktopEditOptionPanel)).setDesktopOptionViewListener(this); DesktopOptionView desktopOptionView = (DesktopOptionView) findViewById(R.id.desktopEditOptionPanel); AppSettings appSettings = Setup.appSettings(); desktopOptionView.updateLockIcon(appSettings.isDesktopLock()); ((Desktop) findViewById(R.id.desktop)).addOnPageChangeListener(new SmoothViewPager.OnPageChangeListener() { public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } public void onPageSelected(int position) { DesktopOptionView desktopOptionView = (DesktopOptionView) findViewById(R.id.desktopEditOptionPanel); AppSettings appSettings = Setup.appSettings(); desktopOptionView.updateHomeIcon(appSettings.getDesktopPageCurrent() == position); } public void onPageScrollStateChanged(int state) { } }); desktop = (Desktop) findViewById(R.id.desktop); desktop.setPageIndicator((PagerIndicator) findViewById(R.id.desktopIndicator)); ((DragOptionView) findViewById(R.id.dragOptionPanel)).setAutoHideView((SearchBar) findViewById(R.id.searchBar)); new HpAppDrawer(this, (PagerIndicator) findViewById(R.id.appDrawerIndicator), (DragOptionView) findViewById(R.id.dragOptionPanel)).initAppDrawer((AppDrawerController) findViewById(R.id.appDrawerController)); initMinibar(); } public final void initSettings() { updateHomeLayout(); AppSettings appSettings = Setup.appSettings(); if (appSettings.isDesktopFullscreen()) { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } else { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); } Desktop desktop = findViewById(R.id.desktop); AppSettings appSettings2 = Setup.appSettings(); desktop.setBackgroundColor(appSettings2.getDesktopBackgroundColor()); Dock dock = findViewById(R.id.dock); appSettings2 = Setup.appSettings(); dock.setBackgroundColor(appSettings2.getDockColor()); getDrawerLayout().setDrawerLockMode(AppSettings.get().getMinibarEnable() ? DrawerLayout.LOCK_MODE_UNLOCKED : DrawerLayout.LOCK_MODE_LOCKED_CLOSED); } public void onRemovePage() { if (getDesktop().isCurrentPageEmpty()) { getDesktop().removeCurrentPage(); return; } DialogHelper.alertDialog(this, getString(R.string.remove), "This page is not empty. Those item will also be removed.", new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { getDesktop().removeCurrentPage(); } }); } public final void initMinibar() { final ArrayList<String> labels = new ArrayList<String>(); final ArrayList<Integer> icons = new ArrayList<>(); for (String act : AppSettings.get().getMinibarArrangement()) { if (act.length() > 1 && act.charAt(0) == '0') { LauncherAction.ActionDisplayItem item = LauncherAction.getActionItemFromString(act.substring(1)); if (item != null) { labels.add(item._label.toString()); icons.add(item._icon); } } } SwipeListView minibar = findViewById(R.id.minibar); minibar.setAdapter(new IconListAdapter(this, labels, icons)); minibar.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int i, long id) { LauncherAction.Action action = LauncherAction.Action.valueOf(labels.get(i)); if (action == LauncherAction.Action.DeviceSettings || action == LauncherAction.Action.LauncherSettings || action == LauncherAction.Action.EditMinBar) { _consumeNextResume = true; } LauncherAction.RunAction(action, Home.this); if (action != LauncherAction.Action.DeviceSettings && action != LauncherAction.Action.LauncherSettings && action != LauncherAction.Action.EditMinBar) { getDrawerLayout().closeDrawers(); } } }); // frame layout spans the entire side while the minibar container has gaps at the top and bottom ((FrameLayout) minibar.getParent()).setBackgroundColor(AppSettings.get().getMinibarBackgroundColor()); } public void onBackPressed() { handleLauncherPause(false); ((DrawerLayout) findViewById(R.id.drawer_layout)).closeDrawers(); } public void onDrawerSlide(@NonNull View drawerView, float slideOffset) { } public void onDrawerOpened(@NonNull View drawerView) { } public void onDrawerClosed(@NonNull View drawerView) { } public void onDrawerStateChanged(int newState) { } protected void onResume() { super.onResume(); AppSettings appSettings = Setup.appSettings(); boolean rotate = false; if (appSettings.getAppRestartRequired()) { appSettings = Setup.appSettings(); appSettings.setAppRestartRequired(false); PendingIntent restartIntentP = PendingIntent.getActivity(this, 123556, new Intent(this, Home.class), PendingIntent.FLAG_CANCEL_CURRENT); AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE); if (mgr == null) { throw new TypeCastException("null cannot be cast to non-null _type android.app.AlarmManager"); } mgr.set(AlarmManager.RTC, System.currentTimeMillis() + ((long) 100), restartIntentP); System.exit(0); return; } Companion.setLauncher(this); WidgetHost appWidgetHost = Companion.getAppWidgetHost(); if (appWidgetHost != null) { appWidgetHost.startListening(); } Intent intent = getIntent(); handleLauncherPause(Intent.ACTION_MAIN.equals(intent.getAction())); boolean user = AppSettings.get().getBool(R.string.pref_key__desktop_rotate, false); boolean system = false; try { system = Settings.System.getInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION) == 1; } catch (SettingNotFoundException e) { Log.d(Home.class.getSimpleName(), "Unable to read settings", e); } boolean rotate2 = false; if (getResources().getBoolean(R.bool.isTablet)) { rotate = system; } else if (user && system) { rotate = true; } if (rotate) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR); } else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } } @NonNull public final Desktop getDesktop() { Desktop desktop = (Desktop) findViewById(R.id.desktop); return desktop; } @NonNull public final Dock getDock() { Dock dock = (Dock) findViewById(R.id.dock); return dock; } @NonNull public final AppDrawerController getAppDrawerController() { AppDrawerController appDrawerController = (AppDrawerController) findViewById(R.id.appDrawerController); return appDrawerController; } @NonNull public final GroupPopupView getGroupPopup() { GroupPopupView groupPopupView = (GroupPopupView) findViewById(R.id.groupPopup); return groupPopupView; } @NonNull public final SearchBar getSearchBar() { SearchBar searchBar = (SearchBar) findViewById(R.id.searchBar); return searchBar; } @NonNull public final View getBackground() { View findViewById = findViewById(R.id.background); return findViewById; } @NonNull public final PagerIndicator getDesktopIndicator() { PagerIndicator pagerIndicator = (PagerIndicator) findViewById(R.id.desktopIndicator); return pagerIndicator; } @NonNull public final DragNDropLayout getDragNDropView() { DragNDropLayout dragNDropLayout = (DragNDropLayout) findViewById(R.id.dragNDropView); return dragNDropLayout; } private final void init() { Companion.setAppWidgetHost(new WidgetHost(getApplicationContext(), R.id.app_widget_host)); Companion companion = Companion; AppWidgetManager instance = AppWidgetManager.getInstance(this); companion.setAppWidgetManager(instance); WidgetHost appWidgetHost = Companion.getAppWidgetHost(); appWidgetHost.startListening(); initViews(); HpDragNDrop hpDragNDrop = new HpDragNDrop(); View findViewById = findViewById(R.id.leftDragHandle); View findViewById2 = findViewById(R.id.rightDragHandle); DragNDropLayout dragNDropLayout = findViewById(R.id.dragNDropView); hpDragNDrop.initDragNDrop(this, findViewById, findViewById2, dragNDropLayout); registerBroadcastReceiver(); initAppManager(); initSettings(); System.runFinalization(); System.gc(); } public final void onUninstallItem(@NonNull Item item) { Companion.setConsumeNextResume(true); Setup.eventHandler().showDeletePackageDialog(this, item); } public final void onRemoveItem(@NonNull Item item) { Desktop desktop = getDesktop(); View coordinateToChildView; switch (item._locationInLauncher) { case 0: coordinateToChildView = desktop.getCurrentPage().coordinateToChildView(new Point(item._x, item._y)); desktop.removeItem(coordinateToChildView, true); break; case 1: Dock dock = getDock(); coordinateToChildView = dock.coordinateToChildView(new Point(item._x, item._y)); dock.removeItem(coordinateToChildView, true); break; default: break; } Companion.getDb().deleteItem(item, true); } public final void onInfoItem(@NonNull Item item) { if (item._type == Type.APP) { try { String str = "android.settings.APPLICATION_DETAILS_SETTINGS"; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("package:"); Intent intent = item._intent; ComponentName component = intent.getComponent(); stringBuilder.append(component.getPackageName()); startActivity(new Intent(str, Uri.parse(stringBuilder.toString()))); } catch (Exception e) { Tool.toast((Context) this, (int) R.string.toast_app_uninstalled); } } } private final Bundle getActivityAnimationOpts(View view) { Bundle bundle = null; if (view == null) { return null; } ActivityOptions opts = null; if (VERSION.SDK_INT >= 23) { int left = 0; int top = 0; int width = view.getMeasuredWidth(); int height = view.getMeasuredHeight(); if (view instanceof AppItemView) { width = (int) ((AppItemView) view).getIconSize(); left = (int) ((AppItemView) view).getDrawIconLeft(); top = (int) ((AppItemView) view).getDrawIconTop(); } opts = ActivityOptions.makeClipRevealAnimation(view, left, top, width, height); } else if (VERSION.SDK_INT < 21) { opts = ActivityOptions.makeScaleUpAnimation(view, 0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); } if (opts != null) { bundle = opts.toBundle(); } return bundle; } public void onDesktopEdit() { Tool.visibleViews(100, 20, (DesktopOptionView) findViewById(R.id.desktopEditOptionPanel)); hideDesktopIndicator(); updateDock$default(this, false, 0, 2, null); updateSearchBar(false); } public void onFinishDesktopEdit() { Tool.invisibleViews(100, 20, (DesktopOptionView) findViewById(R.id.desktopEditOptionPanel)); ((PagerIndicator) findViewById(R.id.desktopIndicator)).hideDelay(); showDesktopIndicator(); updateDock$default(this, true, 0, 2, null); updateSearchBar(true); } public void onSetPageAsHome() { AppSettings appSettings = Setup.appSettings(); Desktop desktop = findViewById(R.id.desktop); appSettings.setDesktopPageCurrent(desktop.getCurrentItem()); } public void onLaunchSettings() { Companion.setConsumeNextResume(true); Setup.eventHandler().showLauncherSettings(this); } public void onPickDesktopAction() { new HpDesktopPickAction(this).onPickDesktopAction(); } public void onPickWidget() { pickWidget(); } private final void initDock() { int iconSize = Setup.appSettings().getDockIconSize(); Dock dock = findViewById(R.id.dock); dock.setHome(this); dock.init(); AppSettings appSettings = Setup.appSettings(); if (appSettings.isDockShowLabel()) { dock.getLayoutParams().height = Tool.dp2px(((16 + iconSize) + 14) + 10, this) + dock.getBottomInset(); } else { dock.getLayoutParams().height = Tool.dp2px((16 + iconSize) + 10, this) + dock.getBottomInset(); } } public final void dimBackground() { Tool.visibleViews(findViewById(R.id.background)); } public final void unDimBackground() { Tool.invisibleViews(findViewById(R.id.background)); } public final void clearRoomForPopUp() { Tool.invisibleViews((Desktop) findViewById(R.id.desktop)); hideDesktopIndicator(); updateDock$default(this, false, 0, 2, null); } public final void unClearRoomForPopUp() { Tool.visibleViews((Desktop) findViewById(R.id.desktop)); showDesktopIndicator(); updateDock$default(this, true, 0, 2, null); } @JvmOverloads public static /* bridge */ /* synthetic */ void updateDock$default(Home home, boolean z, long j, int i, Object obj) { if ((i & 2) != 0) { j = 0; } home.updateDock(z, j); } @JvmOverloads public final void updateDock(boolean show, long delay) { AppSettings appSettings = Setup.appSettings(); Desktop desktop; LayoutParams layoutParams; PagerIndicator pagerIndicator; if (appSettings.getDockEnable() && show) { Tool.visibleViews(100, delay, (Dock) findViewById(R.id.dock)); desktop = findViewById(R.id.desktop); layoutParams = desktop.getLayoutParams(); ((MarginLayoutParams) layoutParams).bottomMargin = Tool.dp2px(4, this); pagerIndicator = findViewById(R.id.desktopIndicator); layoutParams = pagerIndicator.getLayoutParams(); ((MarginLayoutParams) layoutParams).bottomMargin = Tool.dp2px(4, this); } else { appSettings = Setup.appSettings(); if (appSettings.getDockEnable()) { Tool.invisibleViews(100, (Dock) findViewById(R.id.dock)); } else { Tool.goneViews(100, (Dock) findViewById(R.id.dock)); pagerIndicator = findViewById(R.id.desktopIndicator); layoutParams = pagerIndicator.getLayoutParams(); if (layoutParams == null) { throw new TypeCastException("null cannot be cast to non-null _type android.view.ViewGroup.MarginLayoutParams"); } ((MarginLayoutParams) layoutParams).bottomMargin = Desktop._bottomInset + Tool.dp2px(4, (Context) this); desktop = (Desktop) findViewById(R.id.desktop); layoutParams = desktop.getLayoutParams(); if (layoutParams == null) { throw new TypeCastException("null cannot be cast to non-null _type android.view.ViewGroup.MarginLayoutParams"); } ((MarginLayoutParams) layoutParams).bottomMargin = Tool.dp2px(4, (Context) this); } } } public final void updateSearchBar(boolean show) { AppSettings appSettings = Setup.appSettings(); if (appSettings.getSearchBarEnable() && show) { Tool.visibleViews(100, (SearchBar) findViewById(R.id.searchBar)); } else { appSettings = Setup.appSettings(); if (appSettings.getSearchBarEnable()) { Tool.invisibleViews(100, (SearchBar) findViewById(R.id.searchBar)); } else { Tool.goneViews((SearchBar) findViewById(R.id.searchBar)); } } } public final void updateDesktopIndicatorVisibility() { AppSettings appSettings = Setup.appSettings(); if (appSettings.isDesktopShowIndicator()) { Tool.visibleViews(100, (PagerIndicator) findViewById(R.id.desktopIndicator)); return; } Tool.goneViews(100, (PagerIndicator) findViewById(R.id.desktopIndicator)); } public final void hideDesktopIndicator() { AppSettings appSettings = Setup.appSettings(); if (appSettings.isDesktopShowIndicator()) { Tool.invisibleViews(100, (PagerIndicator) findViewById(R.id.desktopIndicator)); } } public final void showDesktopIndicator() { AppSettings appSettings = Setup.appSettings(); if (appSettings.isDesktopShowIndicator()) { Tool.visibleViews(100, (PagerIndicator) findViewById(R.id.desktopIndicator)); } } public final void updateSearchClock() { SearchBar searchBar = (SearchBar) findViewById(R.id.searchBar); TextView textView = searchBar._searchClock; if (textView.getText() != null) { try { searchBar = (SearchBar) findViewById(R.id.searchBar); searchBar.updateClock(); } catch (Exception e) { ((SearchBar) findViewById(R.id.searchBar))._searchClock.setText(R.string.bad_format); } } } public final void updateHomeLayout() { updateSearchBar(true); updateDock$default(this, true, 0, 2, null); updateDesktopIndicatorVisibility(); AppSettings appSettings = Setup.appSettings(); if (!appSettings.getSearchBarEnable()) { View findViewById = findViewById(R.id.leftDragHandle); LayoutParams layoutParams = findViewById.getLayoutParams(); ((MarginLayoutParams) layoutParams).topMargin = Desktop._topInset; findViewById = findViewById(R.id.rightDragHandle); layoutParams = findViewById.getLayoutParams(); Desktop desktop; ((MarginLayoutParams) layoutParams).topMargin = Desktop._topInset; desktop = (Desktop) findViewById(R.id.desktop); desktop.setPadding(0, Desktop._topInset, 0, 0); } appSettings = Setup.appSettings(); if (!appSettings.getDockEnable()) { getDesktop().setPadding(0, 0, 0, Desktop._bottomInset); } } private final void registerBroadcastReceiver() { registerReceiver(_appUpdateReceiver, Companion.getAppUpdateIntentFilter()); if (_timeChangedReceiver != null) { registerReceiver(_timeChangedReceiver, Companion.getTimeChangesIntentFilter()); } registerReceiver(_shortcutReceiver, Companion.getShortcutIntentFilter()); } private final void pickWidget() { Companion.setConsumeNextResume(true); int appWidgetId = Companion.getAppWidgetHost().allocateAppWidgetId(); Intent pickIntent = new Intent("android.appwidget.action.APPWIDGET_PICK"); pickIntent.putExtra("appWidgetId", appWidgetId); startActivityForResult(pickIntent, REQUEST_PICK_APPWIDGET); } private final void configureWidget(Intent data) { Bundle extras = data.getExtras(); int appWidgetId = extras.getInt("appWidgetId", -1); AppWidgetProviderInfo appWidgetInfo = Companion.getAppWidgetManager().getAppWidgetInfo(appWidgetId); if (appWidgetInfo.configure != null) { Intent intent = new Intent("android.appwidget.action.APPWIDGET_CONFIGURE"); intent.setComponent(appWidgetInfo.configure); intent.putExtra("appWidgetId", appWidgetId); startActivityForResult(intent, REQUEST_CREATE_APPWIDGET); } else { createWidget(data); } } private final void createWidget(Intent data) { Bundle extras = data.getExtras(); int appWidgetId = extras.getInt("appWidgetId", -1); AppWidgetProviderInfo appWidgetInfo = Companion.getAppWidgetManager().getAppWidgetInfo(appWidgetId); Item item = Item.newWidgetItem(appWidgetId); int i = appWidgetInfo.minWidth - 1; List pages = getDesktop().getPages(); Home launcher = Companion.getLauncher(); Desktop desktop2 = (Desktop) launcher.findViewById(R.id.desktop); Object obj = pages.get(desktop2.getCurrentItem()); item._spanX = (i / ((CellContainer) obj).getCellWidth()) + 1; i = appWidgetInfo.minHeight - 1; pages = getDesktop().getPages(); launcher = Companion.getLauncher(); obj = pages.get(desktop2.getCurrentItem()); item._spanY = (i / ((CellContainer) obj).getCellHeight()) + 1; Desktop desktop3 = (Desktop) findViewById(R.id.desktop); Point point = desktop3.getCurrentPage().findFreeSpace(item._spanX, item._spanY); if (point != null) { item._x = point.x; item._y = point.y; DataManager db = Companion.getDb(); db.saveItem(item, desktop2.getCurrentItem(), ItemPosition.Desktop); getDesktop().addItemToPage(item, getDesktop().getCurrentItem()); } else { Tool.toast((Context) this, (int) R.string.toast_not_enough_space); } } protected void onDestroy() { WidgetHost appWidgetHost = Companion.getAppWidgetHost(); if (appWidgetHost != null) { appWidgetHost.stopListening(); } Companion.setAppWidgetHost((WidgetHost) null); unregisterReceiver(_appUpdateReceiver); if (_timeChangedReceiver != null) { unregisterReceiver(_timeChangedReceiver); } unregisterReceiver(_shortcutReceiver); Companion.setLauncher((Home) null); super.onDestroy(); } public void onLowMemory() { System.runFinalization(); System.gc(); super.onLowMemory(); } protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { if (resultCode == -1) { if (requestCode == REQUEST_PICK_APPWIDGET) { configureWidget(data); } else if (requestCode == REQUEST_CREATE_APPWIDGET) { createWidget(data); } } else if (resultCode == 0 && data != null) { int appWidgetId = data.getIntExtra("appWidgetId", -1); if (appWidgetId != -1) { WidgetHost appWidgetHost = Companion.getAppWidgetHost(); if (appWidgetHost != null) { appWidgetHost.deleteAppWidgetId(appWidgetId); } } } } protected void onStart() { Companion.setLauncher(this); WidgetHost appWidgetHost = Companion.getAppWidgetHost(); if (appWidgetHost != null) { appWidgetHost.startListening(); } super.onStart(); } private final void handleLauncherPause(boolean wasHomePressed) { if (!Companion.getConsumeNextResume() || wasHomePressed) { onHandleLauncherPause(); } else { Companion.setConsumeNextResume(false); } } protected void onHandleLauncherPause() { ((GroupPopupView) findViewById(R.id.groupPopup)).dismissPopup(); ((CalendarDropDownView) findViewById(R.id.calendarDropDownView)).animateHide(); ((DragNDropLayout) findViewById(R.id.dragNDropView)).hidePopupMenu(); if (!((SearchBar) findViewById(R.id.searchBar)).collapse()) { if (((Desktop) findViewById(R.id.desktop)) != null) { Desktop desktop = (Desktop) findViewById(R.id.desktop); if (desktop.getInEditMode()) { desktop = (Desktop) findViewById(R.id.desktop); List pages = desktop.getPages(); Desktop desktop2 = (Desktop) findViewById(R.id.desktop); ((CellContainer) pages.get(desktop2.getCurrentItem())).performClick(); } else { AppDrawerController appDrawerController = (AppDrawerController) findViewById(R.id.appDrawerController); View drawer = appDrawerController.getDrawer(); if (drawer.getVisibility() == View.VISIBLE) { closeAppDrawer(); } else { setToHomePage(); } } } } } private final void setToHomePage() { Desktop desktop = (Desktop) findViewById(R.id.desktop); AppSettings appSettings = Setup.appSettings(); desktop.setCurrentItem(appSettings.getDesktopPageCurrent()); } @JvmOverloads public static /* bridge */ /* synthetic */ void openAppDrawer$default(Home home, View view, int i, int i2, int i3, Object obj) { if ((i3 & 1) != 0) { view = (Desktop) home.findViewById(R.id.desktop); } if ((i3 & 2) != 0) { i = -1; } if ((i3 & 4) != 0) { i2 = -1; } home.openAppDrawer(view, i, i2); } @JvmOverloads public final void openAppDrawer(@Nullable View view, int x, int y) { if (!(x > 0 && y > 0)) { int[] pos = new int[2]; view.getLocationInWindow(pos); cx = pos[0]; cy = pos[1]; cx += view.getWidth() / 2f; cy += view.getHeight() / 2f; if (view instanceof AppItemView) { AppItemView appItemView = (AppItemView) view; if (appItemView != null && appItemView.getShowLabel()) { cy -= Tool.dp2px(14, this) / 2f; } rad = (int) (appItemView.getIconSize() / 2f - Tool.toPx(4)); } cx -= ((MarginLayoutParams) getAppDrawerController().getDrawer().getLayoutParams()).getMarginStart(); cy -= ((MarginLayoutParams) getAppDrawerController().getDrawer().getLayoutParams()).topMargin; cy -= getAppDrawerController().getPaddingTop(); } else { cx = x; cy = y; rad = 0; } int finalRadius = Math.max(getAppDrawerController().getDrawer().getWidth(), getAppDrawerController().getDrawer().getHeight()); getAppDrawerController().open(cx, cy, rad, finalRadius); } public final void closeAppDrawer() { int finalRadius = Math.max(getAppDrawerController().getDrawer().getWidth(), getAppDrawerController().getDrawer().getHeight()); getAppDrawerController().close(cx, cy, rad, finalRadius); } }
app/src/main/java/com/benny/openlauncher/activity/Home.java
package com.benny.openlauncher.activity; import android.app.Activity; import android.app.ActivityOptions; import android.app.AlarmManager; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProviderInfo; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ActivityInfo; import android.content.res.Resources; import android.graphics.Point; import android.net.Uri; import android.os.Build.VERSION; import android.os.Bundle; import android.provider.Settings; import android.provider.Settings.SettingNotFoundException; import android.support.annotation.NonNull; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.DrawerLayout.DrawerListener; import android.util.Log; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.view.ViewGroup.MarginLayoutParams; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.FrameLayout; import android.widget.TextView; import com.afollestad.materialdialogs.DialogAction; import com.afollestad.materialdialogs.MaterialDialog; import com.benny.openlauncher.BuildConfig; import com.benny.openlauncher.R; import com.benny.openlauncher.activity.homeparts.HpAppDrawer; import com.benny.openlauncher.activity.homeparts.HpDesktopPickAction; import com.benny.openlauncher.activity.homeparts.HpDragNDrop; import com.benny.openlauncher.activity.homeparts.HpInitSetup; import com.benny.openlauncher.activity.homeparts.HpSearchBar; import com.benny.openlauncher.interfaces.AppDeleteListener; import com.benny.openlauncher.manager.Setup; import com.benny.openlauncher.manager.Setup.DataManager; import com.benny.openlauncher.model.Item; import com.benny.openlauncher.model.Item.Type; import com.benny.openlauncher.util.App; import com.benny.openlauncher.util.AppManager; import com.benny.openlauncher.util.AppSettings; import com.benny.openlauncher.util.AppUpdateReceiver; import com.benny.openlauncher.util.Definitions.ItemPosition; import com.benny.openlauncher.util.LauncherAction; import com.benny.openlauncher.util.LauncherAction.Action; import com.benny.openlauncher.util.ShortcutReceiver; import com.benny.openlauncher.util.Tool; import com.benny.openlauncher.viewutil.DialogHelper; import com.benny.openlauncher.viewutil.IconListAdapter; import com.benny.openlauncher.viewutil.WidgetHost; import com.benny.openlauncher.widget.AppDrawerController; import com.benny.openlauncher.widget.AppItemView; import com.benny.openlauncher.widget.CalendarDropDownView; import com.benny.openlauncher.widget.CellContainer; import com.benny.openlauncher.widget.Desktop; import com.benny.openlauncher.widget.Desktop.OnDesktopEditListener; import com.benny.openlauncher.widget.DesktopOptionView; import com.benny.openlauncher.widget.DesktopOptionView.DesktopOptionViewListener; import com.benny.openlauncher.widget.Dock; import com.benny.openlauncher.widget.DragNDropLayout; import com.benny.openlauncher.widget.DragOptionView; import com.benny.openlauncher.widget.GroupPopupView; import com.benny.openlauncher.widget.PagerIndicator; import com.benny.openlauncher.widget.SearchBar; import com.benny.openlauncher.widget.SmoothViewPager; import com.benny.openlauncher.widget.SwipeListView; import net.gsantner.opoc.util.ContextUtils; import android.support.annotation.Nullable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import kotlin.TypeCastException; import kotlin.jvm.JvmOverloads; import kotlin.jvm.internal.Intrinsics; public final class Home extends Activity implements OnDesktopEditListener, DesktopOptionViewListener, DrawerListener { public static final Companion Companion = new Companion(); public static final int REQUEST_CREATE_APPWIDGET = 0x6475; public static final int REQUEST_PERMISSION_STORAGE = 0x3648; public static final int REQUEST_PICK_APPWIDGET = 0x2678; @Nullable private static Resources _resources; private static final IntentFilter _appUpdateIntentFilter = new IntentFilter(); @Nullable private static WidgetHost _appWidgetHost; @NonNull public static AppWidgetManager _appWidgetManager; private static boolean _consumeNextResume; @NonNull public static DataManager _db; public static float _itemTouchX; public static float _itemTouchY; @Nullable public static Home _launcher; private static final IntentFilter _shortcutIntentFilter = new IntentFilter(); private static final IntentFilter _timeChangesIntentFilter = new IntentFilter(); private HashMap deleteMefindViewCache; private final AppUpdateReceiver _appUpdateReceiver = new AppUpdateReceiver(); private int cx; private int cy; private int rad; private final ShortcutReceiver _shortcutReceiver = new ShortcutReceiver(); private BroadcastReceiver _timeChangedReceiver; public static final class Companion { private Companion() { } @Nullable public final Home getLauncher() { return _launcher; } public final void setLauncher(@Nullable Home v) { _launcher = v; } @Nullable public final Resources get_resources() { return _resources; } public final void set_resources(@Nullable Resources v) { _resources = v; } @NonNull public final DataManager getDb() { return _db; } public final void setDb(@NonNull DataManager v) { _db = v; } @Nullable public final WidgetHost getAppWidgetHost() { return _appWidgetHost; } public final void setAppWidgetHost(@Nullable WidgetHost v) { _appWidgetHost = v; } @NonNull public final AppWidgetManager getAppWidgetManager() { AppWidgetManager appWidgetManager = _appWidgetManager; if (appWidgetManager == null) { Intrinsics.throwUninitializedPropertyAccessException("appWidgetManager"); } return appWidgetManager; } public final void setAppWidgetManager(@NonNull AppWidgetManager v) { _appWidgetManager = v; } public final float getItemTouchX() { return _itemTouchX; } public final void setItemTouchX(float v) { _itemTouchX = v; } public final float getItemTouchY() { return _itemTouchY; } public final void setItemTouchY(float v) { _itemTouchY = v; } public final boolean getConsumeNextResume() { return _consumeNextResume; } public final void setConsumeNextResume(boolean v) { _consumeNextResume = v; } private final IntentFilter getTimeChangesIntentFilter() { return _timeChangesIntentFilter; } private final IntentFilter getAppUpdateIntentFilter() { return _appUpdateIntentFilter; } private final IntentFilter getShortcutIntentFilter() { return _shortcutIntentFilter; } } public View _$_findCachedViewById(int i) { if (this.deleteMefindViewCache == null) { this.deleteMefindViewCache = new HashMap(); } View view = (View) this.deleteMefindViewCache.get(Integer.valueOf(i)); if (view != null) { return view; } view = findViewById(i); this.deleteMefindViewCache.put(Integer.valueOf(i), view); return view; } @JvmOverloads public final void openAppDrawer() { openAppDrawer$default(this, null, 0, 0, 7, null); } @JvmOverloads public final void openAppDrawer(@Nullable View view) { openAppDrawer$default(this, view, 0, 0, 6, null); } @JvmOverloads public final void updateDock(boolean z) { updateDock$default(this, z, 0, 2, null); } static { Companion.getTimeChangesIntentFilter().addAction("android.intent.action.TIME_TICK"); Companion.getTimeChangesIntentFilter().addAction("android.intent.action.TIMEZONE_CHANGED"); Companion.getTimeChangesIntentFilter().addAction("android.intent.action.TIME_SET"); Companion.getAppUpdateIntentFilter().addAction("android.intent.action.PACKAGE_ADDED"); Companion.getAppUpdateIntentFilter().addAction("android.intent.action.PACKAGE_REMOVED"); Companion.getAppUpdateIntentFilter().addAction("android.intent.action.PACKAGE_CHANGED"); Companion.getAppUpdateIntentFilter().addDataScheme("package"); Companion.getShortcutIntentFilter().addAction("com.android.launcher.action.INSTALL_SHORTCUT"); } @NonNull public final DrawerLayout getDrawerLayout() { DrawerLayout drawerLayout = (DrawerLayout) _$_findCachedViewById(R.id.drawer_layout); return drawerLayout; } protected void onCreate(@Nullable Bundle savedInstanceState) { Companion.setLauncher(this); Companion.set_resources(getResources()); ContextUtils contextUtils = new ContextUtils(getApplicationContext()); AppSettings appSettings = AppSettings.get(); contextUtils.setAppLanguage(appSettings.getLanguage()); super.onCreate(savedInstanceState); if (!Setup.wasInitialised()) { Setup.init(new HpInitSetup(this)); } AppSettings appSettings2 = Setup.appSettings(); if (appSettings2.isSearchBarTimeEnabled()) { _timeChangedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) { updateSearchClock(); } } }; } Companion.setLauncher(this); Companion companion = Companion; DataManager dataManager = Setup.dataManager(); companion.setDb(dataManager); setContentView(getLayoutInflater().inflate(R.layout.activity_home, null)); if (VERSION.SDK_INT >= 21) { Window window = getWindow(); View decorView = window.getDecorView(); decorView.setSystemUiVisibility(1536); } init(); } public final void onStartApp(@NonNull Context context, @NonNull Intent intent, @Nullable View view) { ComponentName component = intent.getComponent(); if (component == null) { Intrinsics.throwNpe(); } if (Intrinsics.areEqual(component.getPackageName(), BuildConfig.APPLICATION_ID)) { LauncherAction.RunAction(Action.LauncherSettings, context); Companion.setConsumeNextResume(true); } else { try { context.startActivity(intent, getActivityAnimationOpts(view)); Companion.setConsumeNextResume(true); } catch (Exception e) { Tool.toast(context, (int) R.string.toast_app_uninstalled); } } } public final void onStartApp(@NonNull Context context, @NonNull App app, @Nullable View view) { if (Intrinsics.areEqual(app._packageName, BuildConfig.APPLICATION_ID)) { LauncherAction.RunAction(Action.LauncherSettings, context); Companion.setConsumeNextResume(true); } else { try { Intent intent = new Intent("android.intent.action.MAIN"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setClassName(app._packageName, app._className); context.startActivity(intent, getActivityAnimationOpts(view)); Companion.setConsumeNextResume(true); } catch (Exception e) { Tool.toast(context, (int) R.string.toast_app_uninstalled); } } } protected void initAppManager() { Setup.appLoader().addUpdateListener(new AppManager.AppUpdatedListener() { @Override public boolean onAppUpdated(List<App> it) { if ((getDesktop() == null)) { return false; } AppSettings appSettings = Setup.appSettings(); if (appSettings.getDesktopStyle() != 1) { appSettings = Setup.appSettings(); if (appSettings.isAppFirstLaunch()) { appSettings = Setup.appSettings(); appSettings.setAppFirstLaunch(false); Item appDrawerBtnItem = Item.newActionItem(8); appDrawerBtnItem._x = 2; Companion.getDb().saveItem(appDrawerBtnItem, 0, ItemPosition.Dock); } } appSettings = Setup.appSettings(); if (appSettings.getDesktopStyle() == 0) { getDesktop().initDesktopNormal(Home.this); } else { appSettings = Setup.appSettings(); if (appSettings.getDesktopStyle() == 1) { getDesktop().initDesktopShowAll(Home.this, Home.this); } } getDock().initDockItem(Home.this); return true; } }); Setup.appLoader().addDeleteListener(new AppDeleteListener() { @Override public boolean onAppDeleted(List<App> apps) { AppSettings appSettings = Setup.appSettings(); if (appSettings.getDesktopStyle() == 0) { ((Desktop) _$_findCachedViewById(R.id.desktop)).initDesktopNormal(Home.this); } else { appSettings = Setup.appSettings(); if (appSettings.getDesktopStyle() == 1) { ((Desktop) _$_findCachedViewById(R.id.desktop)).initDesktopShowAll(Home.this, Home.this); } } ((Dock) _$_findCachedViewById(R.id.dock)).initDockItem(Home.this); setToHomePage(); return false; } }); AppManager.getInstance(this).init(); } protected void initViews() { new HpSearchBar(this, (SearchBar) _$_findCachedViewById(R.id.searchBar), (CalendarDropDownView) _$_findCachedViewById(R.id.calendarDropDownView)).initSearchBar(); initDock(); ((AppDrawerController) _$_findCachedViewById(R.id.appDrawerController)).init(); ((AppDrawerController) _$_findCachedViewById(R.id.appDrawerController)).setHome(this); ((DragOptionView) _$_findCachedViewById(R.id.dragOptionPanel)).setHome(this); ((Desktop) _$_findCachedViewById(R.id.desktop)).init(); Desktop desktop = (Desktop) _$_findCachedViewById(R.id.desktop); desktop.setDesktopEditListener(this); ((DesktopOptionView) _$_findCachedViewById(R.id.desktopEditOptionPanel)).setDesktopOptionViewListener(this); DesktopOptionView desktopOptionView = (DesktopOptionView) _$_findCachedViewById(R.id.desktopEditOptionPanel); AppSettings appSettings = Setup.appSettings(); desktopOptionView.updateLockIcon(appSettings.isDesktopLock()); ((Desktop) _$_findCachedViewById(R.id.desktop)).addOnPageChangeListener(new SmoothViewPager.OnPageChangeListener() { public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } public void onPageSelected(int position) { DesktopOptionView desktopOptionView = (DesktopOptionView) _$_findCachedViewById(R.id.desktopEditOptionPanel); AppSettings appSettings = Setup.appSettings(); desktopOptionView.updateHomeIcon(appSettings.getDesktopPageCurrent() == position); } public void onPageScrollStateChanged(int state) { } }); desktop = (Desktop) _$_findCachedViewById(R.id.desktop); if (desktop == null) { Intrinsics.throwNpe(); } desktop.setPageIndicator((PagerIndicator) _$_findCachedViewById(R.id.desktopIndicator)); ((DragOptionView) _$_findCachedViewById(R.id.dragOptionPanel)).setAutoHideView((SearchBar) _$_findCachedViewById(R.id.searchBar)); new HpAppDrawer(this, (PagerIndicator) _$_findCachedViewById(R.id.appDrawerIndicator), (DragOptionView) _$_findCachedViewById(R.id.dragOptionPanel)).initAppDrawer((AppDrawerController) _$_findCachedViewById(R.id.appDrawerController)); initMinibar(); } public final void initSettings() { updateHomeLayout(); AppSettings appSettings = Setup.appSettings(); if (appSettings.isDesktopFullscreen()) { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } else { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); } Desktop desktop = (Desktop) _$_findCachedViewById(R.id.desktop); if (desktop == null) { Intrinsics.throwNpe(); } AppSettings appSettings2 = Setup.appSettings(); desktop.setBackgroundColor(appSettings2.getDesktopBackgroundColor()); Dock dock = (Dock) _$_findCachedViewById(R.id.dock); if (dock == null) { Intrinsics.throwNpe(); } appSettings2 = Setup.appSettings(); dock.setBackgroundColor(appSettings2.getDockColor()); DrawerLayout drawerLayout = (DrawerLayout) _$_findCachedViewById(R.id.drawer_layout); appSettings2 = AppSettings.get(); getDrawerLayout().setDrawerLockMode(AppSettings.get().getMinibarEnable() ? DrawerLayout.LOCK_MODE_UNLOCKED : DrawerLayout.LOCK_MODE_LOCKED_CLOSED); } public void onRemovePage() { if (getDesktop().isCurrentPageEmpty()) { Desktop desktop = (Desktop) _$_findCachedViewById(R.id.desktop); if (desktop == null) { Intrinsics.throwNpe(); } desktop.removeCurrentPage(); return; } DialogHelper.alertDialog(this, getString(R.string.remove), "This page is not empty. Those item will also be removed.", new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { Desktop desktop = (Desktop) _$_findCachedViewById(R.id.desktop); if (desktop == null) { Intrinsics.throwNpe(); } desktop.removeCurrentPage(); } }); } public final void initMinibar() { final ArrayList<String> labels = new ArrayList<String>(); final ArrayList<Integer> icons = new ArrayList<>(); for (String act : AppSettings.get().getMinibarArrangement()) { if (act.length() > 1 && act.charAt(0) == '0') { LauncherAction.ActionDisplayItem item = LauncherAction.getActionItemFromString(act.substring(1)); if (item != null) { labels.add(item._label.toString()); icons.add(item._icon); } } } SwipeListView minibar = findViewById(R.id.minibar); minibar.setAdapter(new IconListAdapter(this, labels, icons)); minibar.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int i, long id) { LauncherAction.Action action = LauncherAction.Action.valueOf(labels.get(i)); if (action == LauncherAction.Action.DeviceSettings || action == LauncherAction.Action.LauncherSettings || action == LauncherAction.Action.EditMinBar) { _consumeNextResume = true; } LauncherAction.RunAction(action, Home.this); if (action != LauncherAction.Action.DeviceSettings && action != LauncherAction.Action.LauncherSettings && action != LauncherAction.Action.EditMinBar) { getDrawerLayout().closeDrawers(); } } }); // frame layout spans the entire side while the minibar container has gaps at the top and bottom ((FrameLayout) minibar.getParent()).setBackgroundColor(AppSettings.get().getMinibarBackgroundColor()); } public void onBackPressed() { handleLauncherPause(false); ((DrawerLayout) _$_findCachedViewById(R.id.drawer_layout)).closeDrawers(); } public void onDrawerSlide(@NonNull View drawerView, float slideOffset) { } public void onDrawerOpened(@NonNull View drawerView) { } public void onDrawerClosed(@NonNull View drawerView) { } public void onDrawerStateChanged(int newState) { } protected void onResume() { super.onResume(); AppSettings appSettings = Setup.appSettings(); boolean rotate = false; if (appSettings.getAppRestartRequired()) { appSettings = Setup.appSettings(); appSettings.setAppRestartRequired(false); PendingIntent restartIntentP = PendingIntent.getActivity(this, 123556, new Intent(this, Home.class), PendingIntent.FLAG_CANCEL_CURRENT); AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE); if (mgr == null) { throw new TypeCastException("null cannot be cast to non-null _type android.app.AlarmManager"); } mgr.set(AlarmManager.RTC, System.currentTimeMillis() + ((long) 100), restartIntentP); System.exit(0); return; } Companion.setLauncher(this); WidgetHost appWidgetHost = Companion.getAppWidgetHost(); if (appWidgetHost != null) { appWidgetHost.startListening(); } Intent intent = getIntent(); handleLauncherPause(Intrinsics.areEqual(intent.getAction(), (Object) "android.intent.action.MAIN")); boolean user = AppSettings.get().getBool(R.string.pref_key__desktop_rotate, false); boolean system = false; try { system = Settings.System.getInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION) == 1; } catch (SettingNotFoundException e) { Log.d(Home.class.getSimpleName(), "Unable to read settings", e); } boolean rotate2 = false; if (getResources().getBoolean(R.bool.isTablet)) { rotate = system; } else if (user && system) { rotate = true; } if (rotate) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR); } else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } } @NonNull public final Desktop getDesktop() { Desktop desktop = (Desktop) _$_findCachedViewById(R.id.desktop); return desktop; } @NonNull public final Dock getDock() { Dock dock = (Dock) _$_findCachedViewById(R.id.dock); return dock; } @NonNull public final AppDrawerController getAppDrawerController() { AppDrawerController appDrawerController = (AppDrawerController) _$_findCachedViewById(R.id.appDrawerController); return appDrawerController; } @NonNull public final GroupPopupView getGroupPopup() { GroupPopupView groupPopupView = (GroupPopupView) _$_findCachedViewById(R.id.groupPopup); return groupPopupView; } @NonNull public final SearchBar getSearchBar() { SearchBar searchBar = (SearchBar) _$_findCachedViewById(R.id.searchBar); return searchBar; } @NonNull public final View getBackground() { View _$_findCachedViewById = _$_findCachedViewById(R.id.background); return _$_findCachedViewById; } @NonNull public final PagerIndicator getDesktopIndicator() { PagerIndicator pagerIndicator = (PagerIndicator) _$_findCachedViewById(R.id.desktopIndicator); return pagerIndicator; } @NonNull public final DragNDropLayout getDragNDropView() { DragNDropLayout dragNDropLayout = (DragNDropLayout) _$_findCachedViewById(R.id.dragNDropView); return dragNDropLayout; } private final void init() { Companion.setAppWidgetHost(new WidgetHost(getApplicationContext(), R.id.app_widget_host)); Companion companion = Companion; AppWidgetManager instance = AppWidgetManager.getInstance(this); companion.setAppWidgetManager(instance); WidgetHost appWidgetHost = Companion.getAppWidgetHost(); if (appWidgetHost == null) { Intrinsics.throwNpe(); } appWidgetHost.startListening(); initViews(); HpDragNDrop hpDragNDrop = new HpDragNDrop(); View _$_findCachedViewById = _$_findCachedViewById(R.id.leftDragHandle); View _$_findCachedViewById2 = _$_findCachedViewById(R.id.rightDragHandle); DragNDropLayout dragNDropLayout = (DragNDropLayout) _$_findCachedViewById(R.id.dragNDropView); hpDragNDrop.initDragNDrop(this, _$_findCachedViewById, _$_findCachedViewById2, dragNDropLayout); registerBroadcastReceiver(); initAppManager(); initSettings(); System.runFinalization(); System.gc(); } public final void onUninstallItem(@NonNull Item item) { Companion.setConsumeNextResume(true); Setup.eventHandler().showDeletePackageDialog(this, item); } public final void onRemoveItem(@NonNull Item item) { View coordinateToChildView; switch (item._locationInLauncher) { case 0: Desktop desktop = (Desktop) _$_findCachedViewById(R.id.desktop); Desktop desktop2 = (Desktop) _$_findCachedViewById(R.id.desktop); coordinateToChildView = desktop2.getCurrentPage().coordinateToChildView(new Point(item._x, item._y)); if (coordinateToChildView == null) { Intrinsics.throwNpe(); } desktop.removeItem(coordinateToChildView, true); break; case 1: Dock dock = (Dock) _$_findCachedViewById(R.id.dock); coordinateToChildView = ((Dock) _$_findCachedViewById(R.id.dock)).coordinateToChildView(new Point(item._x, item._y)); if (coordinateToChildView == null) { Intrinsics.throwNpe(); } dock.removeItem(coordinateToChildView, true); break; default: break; } Companion.getDb().deleteItem(item, true); } public final void onInfoItem(@NonNull Item item) { if (item._type == Type.APP) { try { String str = "android.settings.APPLICATION_DETAILS_SETTINGS"; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("package:"); Intent intent = item._intent; if (intent == null) { Intrinsics.throwNpe(); } ComponentName component = intent.getComponent(); if (component == null) { Intrinsics.throwNpe(); } stringBuilder.append(component.getPackageName()); startActivity(new Intent(str, Uri.parse(stringBuilder.toString()))); } catch (Exception e) { Tool.toast((Context) this, (int) R.string.toast_app_uninstalled); } } } private final Bundle getActivityAnimationOpts(View view) { Bundle bundle = null; if (view == null) { return null; } ActivityOptions opts = null; if (VERSION.SDK_INT >= 23) { int left = 0; int top = 0; int width = view.getMeasuredWidth(); int height = view.getMeasuredHeight(); if (view instanceof AppItemView) { width = (int) ((AppItemView) view).getIconSize(); left = (int) ((AppItemView) view).getDrawIconLeft(); top = (int) ((AppItemView) view).getDrawIconTop(); } opts = ActivityOptions.makeClipRevealAnimation(view, left, top, width, height); } else if (VERSION.SDK_INT < 21) { opts = ActivityOptions.makeScaleUpAnimation(view, 0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); } if (opts != null) { bundle = opts.toBundle(); } return bundle; } public void onDesktopEdit() { Tool.visibleViews(100, 20, (DesktopOptionView) _$_findCachedViewById(R.id.desktopEditOptionPanel)); hideDesktopIndicator(); updateDock$default(this, false, 0, 2, null); updateSearchBar(false); } public void onFinishDesktopEdit() { Tool.invisibleViews(100, 20, (DesktopOptionView) _$_findCachedViewById(R.id.desktopEditOptionPanel)); ((PagerIndicator) _$_findCachedViewById(R.id.desktopIndicator)).hideDelay(); showDesktopIndicator(); updateDock$default(this, true, 0, 2, null); updateSearchBar(true); } public void onSetPageAsHome() { AppSettings appSettings = Setup.appSettings(); Desktop desktop = (Desktop) _$_findCachedViewById(R.id.desktop); if (desktop == null) { Intrinsics.throwNpe(); } appSettings.setDesktopPageCurrent(desktop.getCurrentItem()); } public void onLaunchSettings() { Companion.setConsumeNextResume(true); Setup.eventHandler().showLauncherSettings(this); } public void onPickDesktopAction() { new HpDesktopPickAction(this).onPickDesktopAction(); } public void onPickWidget() { pickWidget(); } private final void initDock() { int iconSize = Setup.appSettings().getDockIconSize(); Dock dock = (Dock) _$_findCachedViewById(R.id.dock); if (dock == null) { Intrinsics.throwNpe(); } dock.setHome(this); dock.init(); AppSettings appSettings = Setup.appSettings(); if (appSettings.isDockShowLabel()) { dock = (Dock) _$_findCachedViewById(R.id.dock); if (dock == null) { Intrinsics.throwNpe(); } dock.getLayoutParams().height = Tool.dp2px(((16 + iconSize) + 14) + 10, (Context) this) + dock.getBottomInset(); } else { dock = (Dock) _$_findCachedViewById(R.id.dock); if (dock == null) { Intrinsics.throwNpe(); } dock.getLayoutParams().height = Tool.dp2px((16 + iconSize) + 10, (Context) this) + dock.getBottomInset(); } } public final void dimBackground() { Tool.visibleViews(_$_findCachedViewById(R.id.background)); } public final void unDimBackground() { Tool.invisibleViews(_$_findCachedViewById(R.id.background)); } public final void clearRoomForPopUp() { Tool.invisibleViews((Desktop) _$_findCachedViewById(R.id.desktop)); hideDesktopIndicator(); updateDock$default(this, false, 0, 2, null); } public final void unClearRoomForPopUp() { Tool.visibleViews((Desktop) _$_findCachedViewById(R.id.desktop)); showDesktopIndicator(); updateDock$default(this, true, 0, 2, null); } @JvmOverloads public static /* bridge */ /* synthetic */ void updateDock$default(Home home, boolean z, long j, int i, Object obj) { if ((i & 2) != 0) { j = 0; } home.updateDock(z, j); } @JvmOverloads public final void updateDock(boolean show, long delay) { AppSettings appSettings = Setup.appSettings(); Desktop desktop; LayoutParams layoutParams; PagerIndicator pagerIndicator; if (appSettings.getDockEnable() && show) { Tool.visibleViews(100, delay, (Dock) _$_findCachedViewById(R.id.dock)); desktop = (Desktop) _$_findCachedViewById(R.id.desktop); if (desktop == null) { Intrinsics.throwNpe(); } layoutParams = desktop.getLayoutParams(); if (layoutParams == null) { throw new TypeCastException("null cannot be cast to non-null _type android.view.ViewGroup.MarginLayoutParams"); } ((MarginLayoutParams) layoutParams).bottomMargin = Tool.dp2px(4, (Context) this); pagerIndicator = (PagerIndicator) _$_findCachedViewById(R.id.desktopIndicator); if (pagerIndicator == null) { Intrinsics.throwNpe(); } layoutParams = pagerIndicator.getLayoutParams(); if (layoutParams == null) { throw new TypeCastException("null cannot be cast to non-null _type android.view.ViewGroup.MarginLayoutParams"); } ((MarginLayoutParams) layoutParams).bottomMargin = Tool.dp2px(4, (Context) this); } else { appSettings = Setup.appSettings(); if (appSettings.getDockEnable()) { Tool.invisibleViews(100, (Dock) _$_findCachedViewById(R.id.dock)); } else { Tool.goneViews(100, (Dock) _$_findCachedViewById(R.id.dock)); pagerIndicator = (PagerIndicator) _$_findCachedViewById(R.id.desktopIndicator); if (pagerIndicator == null) { Intrinsics.throwNpe(); } layoutParams = pagerIndicator.getLayoutParams(); if (layoutParams == null) { throw new TypeCastException("null cannot be cast to non-null _type android.view.ViewGroup.MarginLayoutParams"); } ((MarginLayoutParams) layoutParams).bottomMargin = Desktop._bottomInset + Tool.dp2px(4, (Context) this); desktop = (Desktop) _$_findCachedViewById(R.id.desktop); if (desktop == null) { Intrinsics.throwNpe(); } layoutParams = desktop.getLayoutParams(); if (layoutParams == null) { throw new TypeCastException("null cannot be cast to non-null _type android.view.ViewGroup.MarginLayoutParams"); } ((MarginLayoutParams) layoutParams).bottomMargin = Tool.dp2px(4, (Context) this); } } } public final void updateSearchBar(boolean show) { AppSettings appSettings = Setup.appSettings(); if (appSettings.getSearchBarEnable() && show) { Tool.visibleViews(100, (SearchBar) _$_findCachedViewById(R.id.searchBar)); } else { appSettings = Setup.appSettings(); if (appSettings.getSearchBarEnable()) { Tool.invisibleViews(100, (SearchBar) _$_findCachedViewById(R.id.searchBar)); } else { Tool.goneViews((SearchBar) _$_findCachedViewById(R.id.searchBar)); } } } public final void updateDesktopIndicatorVisibility() { AppSettings appSettings = Setup.appSettings(); if (appSettings.isDesktopShowIndicator()) { Tool.visibleViews(100, (PagerIndicator) _$_findCachedViewById(R.id.desktopIndicator)); return; } Tool.goneViews(100, (PagerIndicator) _$_findCachedViewById(R.id.desktopIndicator)); } public final void hideDesktopIndicator() { AppSettings appSettings = Setup.appSettings(); if (appSettings.isDesktopShowIndicator()) { Tool.invisibleViews(100, (PagerIndicator) _$_findCachedViewById(R.id.desktopIndicator)); } } public final void showDesktopIndicator() { AppSettings appSettings = Setup.appSettings(); if (appSettings.isDesktopShowIndicator()) { Tool.visibleViews(100, (PagerIndicator) _$_findCachedViewById(R.id.desktopIndicator)); } } public final void updateSearchClock() { SearchBar searchBar = (SearchBar) _$_findCachedViewById(R.id.searchBar); if (searchBar == null) { Intrinsics.throwNpe(); } TextView textView = searchBar._searchClock; if (textView.getText() != null) { try { searchBar = (SearchBar) _$_findCachedViewById(R.id.searchBar); if (searchBar == null) { Intrinsics.throwNpe(); } searchBar.updateClock(); } catch (Exception e) { ((SearchBar) _$_findCachedViewById(R.id.searchBar))._searchClock.setText(R.string.bad_format); } } } public final void updateHomeLayout() { updateSearchBar(true); updateDock$default(this, true, 0, 2, null); updateDesktopIndicatorVisibility(); AppSettings appSettings = Setup.appSettings(); if (!appSettings.getSearchBarEnable()) { View _$_findCachedViewById = _$_findCachedViewById(R.id.leftDragHandle); if (_$_findCachedViewById == null) { Intrinsics.throwNpe(); } LayoutParams layoutParams = _$_findCachedViewById.getLayoutParams(); if (layoutParams == null) { throw new TypeCastException("null cannot be cast to non-null _type android.view.ViewGroup.MarginLayoutParams"); } ((MarginLayoutParams) layoutParams).topMargin = Desktop._topInset; _$_findCachedViewById = _$_findCachedViewById(R.id.rightDragHandle); if (_$_findCachedViewById == null) { Intrinsics.throwNpe(); } layoutParams = _$_findCachedViewById.getLayoutParams(); if (layoutParams == null) { throw new TypeCastException("null cannot be cast to non-null _type android.view.ViewGroup.MarginLayoutParams"); } Desktop desktop; ((MarginLayoutParams) layoutParams).topMargin = Desktop._topInset; desktop = (Desktop) _$_findCachedViewById(R.id.desktop); if (desktop == null) { Intrinsics.throwNpe(); } desktop.setPadding(0, Desktop._topInset, 0, 0); } appSettings = Setup.appSettings(); if (!appSettings.getDockEnable()) { getDesktop().setPadding(0, 0, 0, Desktop._bottomInset); } } private final void registerBroadcastReceiver() { registerReceiver(_appUpdateReceiver, Companion.getAppUpdateIntentFilter()); if (_timeChangedReceiver != null) { registerReceiver(_timeChangedReceiver, Companion.getTimeChangesIntentFilter()); } registerReceiver(_shortcutReceiver, Companion.getShortcutIntentFilter()); } private final void pickWidget() { Companion.setConsumeNextResume(true); int appWidgetId = Companion.getAppWidgetHost().allocateAppWidgetId(); Intent pickIntent = new Intent("android.appwidget.action.APPWIDGET_PICK"); pickIntent.putExtra("appWidgetId", appWidgetId); startActivityForResult(pickIntent, REQUEST_PICK_APPWIDGET); } private final void configureWidget(Intent data) { if (data == null) { Intrinsics.throwNpe(); } Bundle extras = data.getExtras(); if (extras == null) { Intrinsics.throwNpe(); } int appWidgetId = extras.getInt("appWidgetId", -1); AppWidgetProviderInfo appWidgetInfo = Companion.getAppWidgetManager().getAppWidgetInfo(appWidgetId); if (appWidgetInfo.configure != null) { Intent intent = new Intent("android.appwidget.action.APPWIDGET_CONFIGURE"); intent.setComponent(appWidgetInfo.configure); intent.putExtra("appWidgetId", appWidgetId); startActivityForResult(intent, REQUEST_CREATE_APPWIDGET); } else { createWidget(data); } } private final void createWidget(Intent data) { if (data == null) { Intrinsics.throwNpe(); } Bundle extras = data.getExtras(); if (extras == null) { Intrinsics.throwNpe(); } int appWidgetId = extras.getInt("appWidgetId", -1); AppWidgetProviderInfo appWidgetInfo = Companion.getAppWidgetManager().getAppWidgetInfo(appWidgetId); Item item = Item.newWidgetItem(appWidgetId); int i = appWidgetInfo.minWidth - 1; Desktop desktop = (Desktop) _$_findCachedViewById(R.id.desktop); if (desktop == null) { Intrinsics.throwNpe(); } List pages = desktop.getPages(); Home launcher = Companion.getLauncher(); if (launcher == null) { Intrinsics.throwNpe(); } Desktop desktop2 = (Desktop) launcher._$_findCachedViewById(R.id.desktop); if (desktop2 == null) { Intrinsics.throwNpe(); } Object obj = pages.get(desktop2.getCurrentItem()); item._spanX = (i / ((CellContainer) obj).getCellWidth()) + 1; i = appWidgetInfo.minHeight - 1; desktop = (Desktop) _$_findCachedViewById(R.id.desktop); if (desktop == null) { Intrinsics.throwNpe(); } pages = desktop.getPages(); launcher = Companion.getLauncher(); if (launcher == null) { Intrinsics.throwNpe(); } desktop2 = (Desktop) launcher._$_findCachedViewById(R.id.desktop); if (desktop2 == null) { Intrinsics.throwNpe(); } obj = pages.get(desktop2.getCurrentItem()); item._spanY = (i / ((CellContainer) obj).getCellHeight()) + 1; Desktop desktop3 = (Desktop) _$_findCachedViewById(R.id.desktop); if (desktop3 == null) { Intrinsics.throwNpe(); } Point point = desktop3.getCurrentPage().findFreeSpace(item._spanX, item._spanY); if (point != null) { item._x = point.x; item._y = point.y; DataManager db = Companion.getDb(); desktop2 = (Desktop) _$_findCachedViewById(R.id.desktop); if (desktop2 == null) { Intrinsics.throwNpe(); } db.saveItem(item, desktop2.getCurrentItem(), ItemPosition.Desktop); desktop = (Desktop) _$_findCachedViewById(R.id.desktop); if (desktop == null) { Intrinsics.throwNpe(); } desktop2 = (Desktop) _$_findCachedViewById(R.id.desktop); if (desktop2 == null) { Intrinsics.throwNpe(); } desktop.addItemToPage(item, desktop2.getCurrentItem()); } else { Tool.toast((Context) this, (int) R.string.toast_not_enough_space); } } protected void onDestroy() { WidgetHost appWidgetHost = Companion.getAppWidgetHost(); if (appWidgetHost != null) { appWidgetHost.stopListening(); } Companion.setAppWidgetHost((WidgetHost) null); unregisterReceiver(_appUpdateReceiver); if (_timeChangedReceiver != null) { unregisterReceiver(_timeChangedReceiver); } unregisterReceiver(_shortcutReceiver); Companion.setLauncher((Home) null); super.onDestroy(); } public void onLowMemory() { System.runFinalization(); System.gc(); super.onLowMemory(); } protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { if (resultCode == -1) { if (requestCode == REQUEST_PICK_APPWIDGET) { configureWidget(data); } else if (requestCode == REQUEST_CREATE_APPWIDGET) { createWidget(data); } } else if (resultCode == 0 && data != null) { int appWidgetId = data.getIntExtra("appWidgetId", -1); if (appWidgetId != -1) { WidgetHost appWidgetHost = Companion.getAppWidgetHost(); if (appWidgetHost != null) { appWidgetHost.deleteAppWidgetId(appWidgetId); } } } } protected void onStart() { Companion.setLauncher(this); WidgetHost appWidgetHost = Companion.getAppWidgetHost(); if (appWidgetHost != null) { appWidgetHost.startListening(); } super.onStart(); } private final void handleLauncherPause(boolean wasHomePressed) { if (!Companion.getConsumeNextResume() || wasHomePressed) { onHandleLauncherPause(); } else { Companion.setConsumeNextResume(false); } } protected void onHandleLauncherPause() { ((GroupPopupView) _$_findCachedViewById(R.id.groupPopup)).dismissPopup(); ((CalendarDropDownView) _$_findCachedViewById(R.id.calendarDropDownView)).animateHide(); ((DragNDropLayout) _$_findCachedViewById(R.id.dragNDropView)).hidePopupMenu(); if (!((SearchBar) _$_findCachedViewById(R.id.searchBar)).collapse()) { if (((Desktop) _$_findCachedViewById(R.id.desktop)) != null) { Desktop desktop = (Desktop) _$_findCachedViewById(R.id.desktop); if (desktop.getInEditMode()) { desktop = (Desktop) _$_findCachedViewById(R.id.desktop); List pages = desktop.getPages(); Desktop desktop2 = (Desktop) _$_findCachedViewById(R.id.desktop); ((CellContainer) pages.get(desktop2.getCurrentItem())).performClick(); } else { AppDrawerController appDrawerController = (AppDrawerController) _$_findCachedViewById(R.id.appDrawerController); View drawer = appDrawerController.getDrawer(); if (drawer.getVisibility() == View.VISIBLE) { closeAppDrawer(); } else { setToHomePage(); } } } } } private final void setToHomePage() { Desktop desktop = (Desktop) _$_findCachedViewById(R.id.desktop); AppSettings appSettings = Setup.appSettings(); desktop.setCurrentItem(appSettings.getDesktopPageCurrent()); } @JvmOverloads public static /* bridge */ /* synthetic */ void openAppDrawer$default(Home home, View view, int i, int i2, int i3, Object obj) { if ((i3 & 1) != 0) { view = (Desktop) home._$_findCachedViewById(R.id.desktop); } if ((i3 & 2) != 0) { i = -1; } if ((i3 & 4) != 0) { i2 = -1; } home.openAppDrawer(view, i, i2); } @JvmOverloads public final void openAppDrawer(@Nullable View view, int x, int y) { if (!(x > 0 && y > 0)) { int[] pos = new int[2]; view.getLocationInWindow(pos); cx = pos[0]; cy = pos[1]; cx += view.getWidth() / 2f; cy += view.getHeight() / 2f; if (view instanceof AppItemView) { AppItemView appItemView = (AppItemView) view; if (appItemView != null && appItemView.getShowLabel()) { cy -= Tool.dp2px(14, this) / 2f; } rad = (int) (appItemView.getIconSize() / 2f - Tool.toPx(4)); } cx -= ((MarginLayoutParams) getAppDrawerController().getDrawer().getLayoutParams()).getMarginStart(); cy -= ((MarginLayoutParams) getAppDrawerController().getDrawer().getLayoutParams()).topMargin; cy -= getAppDrawerController().getPaddingTop(); } else { cx = x; cy = y; rad = 0; } int finalRadius = Math.max(getAppDrawerController().getDrawer().getWidth(), getAppDrawerController().getDrawer().getHeight()); getAppDrawerController().open(cx, cy, rad, finalRadius); } public final void closeAppDrawer() { int finalRadius = Math.max(getAppDrawerController().getDrawer().getWidth(), getAppDrawerController().getDrawer().getHeight()); getAppDrawerController().close(cx, cy, rad, finalRadius); } }
Remove intrinsics
app/src/main/java/com/benny/openlauncher/activity/Home.java
Remove intrinsics
<ide><path>pp/src/main/java/com/benny/openlauncher/activity/Home.java <ide> import android.provider.Settings; <ide> import android.provider.Settings.SettingNotFoundException; <ide> import android.support.annotation.NonNull; <add>import android.support.annotation.Nullable; <ide> import android.support.v4.widget.DrawerLayout; <ide> import android.support.v4.widget.DrawerLayout.DrawerListener; <ide> import android.util.Log; <ide> <ide> import net.gsantner.opoc.util.ContextUtils; <ide> <del>import android.support.annotation.Nullable; <del> <ide> import java.util.ArrayList; <ide> import java.util.HashMap; <ide> import java.util.List; <ide> <ide> import kotlin.TypeCastException; <ide> import kotlin.jvm.JvmOverloads; <del>import kotlin.jvm.internal.Intrinsics; <ide> <ide> <ide> public final class Home extends Activity implements OnDesktopEditListener, DesktopOptionViewListener, DrawerListener { <ide> <ide> @NonNull <ide> public final AppWidgetManager getAppWidgetManager() { <del> AppWidgetManager appWidgetManager = _appWidgetManager; <del> if (appWidgetManager == null) { <del> Intrinsics.throwUninitializedPropertyAccessException("appWidgetManager"); <del> } <del> return appWidgetManager; <add> return _appWidgetManager; <ide> } <ide> <ide> public final void setAppWidgetManager(@NonNull AppWidgetManager v) { <ide> private final IntentFilter getShortcutIntentFilter() { <ide> return _shortcutIntentFilter; <ide> } <del> } <del> <del> <del> public View _$_findCachedViewById(int i) { <del> if (this.deleteMefindViewCache == null) { <del> this.deleteMefindViewCache = new HashMap(); <del> } <del> View view = (View) this.deleteMefindViewCache.get(Integer.valueOf(i)); <del> if (view != null) { <del> return view; <del> } <del> view = findViewById(i); <del> this.deleteMefindViewCache.put(Integer.valueOf(i), view); <del> return view; <ide> } <ide> <ide> @JvmOverloads <ide> <ide> @NonNull <ide> public final DrawerLayout getDrawerLayout() { <del> DrawerLayout drawerLayout = (DrawerLayout) _$_findCachedViewById(R.id.drawer_layout); <del> return drawerLayout; <add> return findViewById(R.id.drawer_layout); <ide> } <ide> <ide> protected void onCreate(@Nullable Bundle savedInstanceState) { <ide> } <ide> <ide> public final void onStartApp(@NonNull Context context, @NonNull Intent intent, @Nullable View view) { <del> <del> <ide> ComponentName component = intent.getComponent(); <del> if (component == null) { <del> Intrinsics.throwNpe(); <del> } <del> if (Intrinsics.areEqual(component.getPackageName(), BuildConfig.APPLICATION_ID)) { <add> <add> if (BuildConfig.APPLICATION_ID.equals(component.getPackageName())) { <ide> LauncherAction.RunAction(Action.LauncherSettings, context); <ide> Companion.setConsumeNextResume(true); <ide> } else { <ide> public final void onStartApp(@NonNull Context context, @NonNull App app, @Nullable View view) { <ide> <ide> <del> if (Intrinsics.areEqual(app._packageName, BuildConfig.APPLICATION_ID)) { <add> if (BuildConfig.APPLICATION_ID.equals(app._packageName)) { <ide> LauncherAction.RunAction(Action.LauncherSettings, context); <ide> Companion.setConsumeNextResume(true); <ide> } else { <ide> AppSettings appSettings = Setup.appSettings(); <ide> <ide> if (appSettings.getDesktopStyle() == 0) { <del> ((Desktop) _$_findCachedViewById(R.id.desktop)).initDesktopNormal(Home.this); <add> ((Desktop) findViewById(R.id.desktop)).initDesktopNormal(Home.this); <ide> } else { <ide> appSettings = Setup.appSettings(); <ide> <ide> if (appSettings.getDesktopStyle() == 1) { <del> ((Desktop) _$_findCachedViewById(R.id.desktop)).initDesktopShowAll(Home.this, Home.this); <add> ((Desktop) findViewById(R.id.desktop)).initDesktopShowAll(Home.this, Home.this); <ide> } <ide> } <del> ((Dock) _$_findCachedViewById(R.id.dock)).initDockItem(Home.this); <add> ((Dock) findViewById(R.id.dock)).initDockItem(Home.this); <ide> setToHomePage(); <ide> return false; <ide> } <ide> } <ide> <ide> protected void initViews() { <del> new HpSearchBar(this, (SearchBar) _$_findCachedViewById(R.id.searchBar), (CalendarDropDownView) _$_findCachedViewById(R.id.calendarDropDownView)).initSearchBar(); <add> new HpSearchBar(this, (SearchBar) findViewById(R.id.searchBar), (CalendarDropDownView) findViewById(R.id.calendarDropDownView)).initSearchBar(); <ide> initDock(); <del> ((AppDrawerController) _$_findCachedViewById(R.id.appDrawerController)).init(); <del> ((AppDrawerController) _$_findCachedViewById(R.id.appDrawerController)).setHome(this); <del> ((DragOptionView) _$_findCachedViewById(R.id.dragOptionPanel)).setHome(this); <del> ((Desktop) _$_findCachedViewById(R.id.desktop)).init(); <del> Desktop desktop = (Desktop) _$_findCachedViewById(R.id.desktop); <add> ((AppDrawerController) findViewById(R.id.appDrawerController)).init(); <add> ((AppDrawerController) findViewById(R.id.appDrawerController)).setHome(this); <add> ((DragOptionView) findViewById(R.id.dragOptionPanel)).setHome(this); <add> ((Desktop) findViewById(R.id.desktop)).init(); <add> Desktop desktop = (Desktop) findViewById(R.id.desktop); <ide> <ide> desktop.setDesktopEditListener(this); <del> ((DesktopOptionView) _$_findCachedViewById(R.id.desktopEditOptionPanel)).setDesktopOptionViewListener(this); <del> DesktopOptionView desktopOptionView = (DesktopOptionView) _$_findCachedViewById(R.id.desktopEditOptionPanel); <add> ((DesktopOptionView) findViewById(R.id.desktopEditOptionPanel)).setDesktopOptionViewListener(this); <add> DesktopOptionView desktopOptionView = (DesktopOptionView) findViewById(R.id.desktopEditOptionPanel); <ide> AppSettings appSettings = Setup.appSettings(); <ide> <ide> desktopOptionView.updateLockIcon(appSettings.isDesktopLock()); <del> ((Desktop) _$_findCachedViewById(R.id.desktop)).addOnPageChangeListener(new SmoothViewPager.OnPageChangeListener() { <add> ((Desktop) findViewById(R.id.desktop)).addOnPageChangeListener(new SmoothViewPager.OnPageChangeListener() { <ide> public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { <ide> } <ide> <ide> public void onPageSelected(int position) { <del> DesktopOptionView desktopOptionView = (DesktopOptionView) _$_findCachedViewById(R.id.desktopEditOptionPanel); <add> DesktopOptionView desktopOptionView = (DesktopOptionView) findViewById(R.id.desktopEditOptionPanel); <ide> AppSettings appSettings = Setup.appSettings(); <ide> <ide> desktopOptionView.updateHomeIcon(appSettings.getDesktopPageCurrent() == position); <ide> public void onPageScrollStateChanged(int state) { <ide> } <ide> }); <del> desktop = (Desktop) _$_findCachedViewById(R.id.desktop); <del> if (desktop == null) { <del> Intrinsics.throwNpe(); <del> } <del> desktop.setPageIndicator((PagerIndicator) _$_findCachedViewById(R.id.desktopIndicator)); <del> ((DragOptionView) _$_findCachedViewById(R.id.dragOptionPanel)).setAutoHideView((SearchBar) _$_findCachedViewById(R.id.searchBar)); <del> new HpAppDrawer(this, (PagerIndicator) _$_findCachedViewById(R.id.appDrawerIndicator), (DragOptionView) _$_findCachedViewById(R.id.dragOptionPanel)).initAppDrawer((AppDrawerController) _$_findCachedViewById(R.id.appDrawerController)); <add> desktop = (Desktop) findViewById(R.id.desktop); <add> desktop.setPageIndicator((PagerIndicator) findViewById(R.id.desktopIndicator)); <add> ((DragOptionView) findViewById(R.id.dragOptionPanel)).setAutoHideView((SearchBar) findViewById(R.id.searchBar)); <add> new HpAppDrawer(this, (PagerIndicator) findViewById(R.id.appDrawerIndicator), (DragOptionView) findViewById(R.id.dragOptionPanel)).initAppDrawer((AppDrawerController) findViewById(R.id.appDrawerController)); <ide> initMinibar(); <ide> } <ide> <ide> } else { <ide> getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); <ide> } <del> Desktop desktop = (Desktop) _$_findCachedViewById(R.id.desktop); <del> if (desktop == null) { <del> Intrinsics.throwNpe(); <del> } <add> Desktop desktop = findViewById(R.id.desktop); <ide> AppSettings appSettings2 = Setup.appSettings(); <ide> <ide> desktop.setBackgroundColor(appSettings2.getDesktopBackgroundColor()); <del> Dock dock = (Dock) _$_findCachedViewById(R.id.dock); <del> if (dock == null) { <del> Intrinsics.throwNpe(); <del> } <add> Dock dock = findViewById(R.id.dock); <ide> appSettings2 = Setup.appSettings(); <ide> <ide> dock.setBackgroundColor(appSettings2.getDockColor()); <del> DrawerLayout drawerLayout = (DrawerLayout) _$_findCachedViewById(R.id.drawer_layout); <del> appSettings2 = AppSettings.get(); <del> <ide> getDrawerLayout().setDrawerLockMode(AppSettings.get().getMinibarEnable() ? DrawerLayout.LOCK_MODE_UNLOCKED : DrawerLayout.LOCK_MODE_LOCKED_CLOSED); <ide> } <ide> <ide> <ide> public void onRemovePage() { <ide> if (getDesktop().isCurrentPageEmpty()) { <del> Desktop desktop = (Desktop) _$_findCachedViewById(R.id.desktop); <del> if (desktop == null) { <del> Intrinsics.throwNpe(); <del> } <del> desktop.removeCurrentPage(); <add> <add> getDesktop().removeCurrentPage(); <ide> return; <ide> } <ide> DialogHelper.alertDialog(this, getString(R.string.remove), "This page is not empty. Those item will also be removed.", new MaterialDialog.SingleButtonCallback() { <ide> @Override <ide> public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { <del> Desktop desktop = (Desktop) _$_findCachedViewById(R.id.desktop); <del> if (desktop == null) { <del> Intrinsics.throwNpe(); <del> } <del> desktop.removeCurrentPage(); <add> getDesktop().removeCurrentPage(); <ide> } <ide> }); <ide> } <ide> <ide> public void onBackPressed() { <ide> handleLauncherPause(false); <del> ((DrawerLayout) _$_findCachedViewById(R.id.drawer_layout)).closeDrawers(); <add> ((DrawerLayout) findViewById(R.id.drawer_layout)).closeDrawers(); <ide> } <ide> <ide> public void onDrawerSlide(@NonNull View drawerView, float slideOffset) { <ide> } <ide> Intent intent = getIntent(); <ide> <del> handleLauncherPause(Intrinsics.areEqual(intent.getAction(), (Object) "android.intent.action.MAIN")); <add> handleLauncherPause(Intent.ACTION_MAIN.equals(intent.getAction())); <ide> boolean user = AppSettings.get().getBool(R.string.pref_key__desktop_rotate, false); <ide> boolean system = false; <ide> try { <ide> <ide> @NonNull <ide> public final Desktop getDesktop() { <del> Desktop desktop = (Desktop) _$_findCachedViewById(R.id.desktop); <add> Desktop desktop = (Desktop) findViewById(R.id.desktop); <ide> <ide> return desktop; <ide> } <ide> <ide> @NonNull <ide> public final Dock getDock() { <del> Dock dock = (Dock) _$_findCachedViewById(R.id.dock); <add> Dock dock = (Dock) findViewById(R.id.dock); <ide> <ide> return dock; <ide> } <ide> <ide> @NonNull <ide> public final AppDrawerController getAppDrawerController() { <del> AppDrawerController appDrawerController = (AppDrawerController) _$_findCachedViewById(R.id.appDrawerController); <add> AppDrawerController appDrawerController = (AppDrawerController) findViewById(R.id.appDrawerController); <ide> <ide> return appDrawerController; <ide> } <ide> <ide> @NonNull <ide> public final GroupPopupView getGroupPopup() { <del> GroupPopupView groupPopupView = (GroupPopupView) _$_findCachedViewById(R.id.groupPopup); <add> GroupPopupView groupPopupView = (GroupPopupView) findViewById(R.id.groupPopup); <ide> <ide> return groupPopupView; <ide> } <ide> <ide> @NonNull <ide> public final SearchBar getSearchBar() { <del> SearchBar searchBar = (SearchBar) _$_findCachedViewById(R.id.searchBar); <add> SearchBar searchBar = (SearchBar) findViewById(R.id.searchBar); <ide> <ide> return searchBar; <ide> } <ide> <ide> @NonNull <ide> public final View getBackground() { <del> View _$_findCachedViewById = _$_findCachedViewById(R.id.background); <del> <del> return _$_findCachedViewById; <add> View findViewById = findViewById(R.id.background); <add> <add> return findViewById; <ide> } <ide> <ide> @NonNull <ide> public final PagerIndicator getDesktopIndicator() { <del> PagerIndicator pagerIndicator = (PagerIndicator) _$_findCachedViewById(R.id.desktopIndicator); <add> PagerIndicator pagerIndicator = (PagerIndicator) findViewById(R.id.desktopIndicator); <ide> <ide> return pagerIndicator; <ide> } <ide> <ide> @NonNull <ide> public final DragNDropLayout getDragNDropView() { <del> DragNDropLayout dragNDropLayout = (DragNDropLayout) _$_findCachedViewById(R.id.dragNDropView); <add> DragNDropLayout dragNDropLayout = (DragNDropLayout) findViewById(R.id.dragNDropView); <ide> <ide> return dragNDropLayout; <ide> } <ide> <ide> companion.setAppWidgetManager(instance); <ide> WidgetHost appWidgetHost = Companion.getAppWidgetHost(); <del> if (appWidgetHost == null) { <del> Intrinsics.throwNpe(); <del> } <ide> appWidgetHost.startListening(); <ide> initViews(); <ide> HpDragNDrop hpDragNDrop = new HpDragNDrop(); <del> View _$_findCachedViewById = _$_findCachedViewById(R.id.leftDragHandle); <del> <del> View _$_findCachedViewById2 = _$_findCachedViewById(R.id.rightDragHandle); <del> <del> DragNDropLayout dragNDropLayout = (DragNDropLayout) _$_findCachedViewById(R.id.dragNDropView); <del> <del> hpDragNDrop.initDragNDrop(this, _$_findCachedViewById, _$_findCachedViewById2, dragNDropLayout); <add> View findViewById = findViewById(R.id.leftDragHandle); <add> <add> View findViewById2 = findViewById(R.id.rightDragHandle); <add> <add> DragNDropLayout dragNDropLayout = findViewById(R.id.dragNDropView); <add> <add> hpDragNDrop.initDragNDrop(this, findViewById, findViewById2, dragNDropLayout); <ide> registerBroadcastReceiver(); <ide> initAppManager(); <ide> initSettings(); <ide> } <ide> <ide> public final void onRemoveItem(@NonNull Item item) { <del> <add> Desktop desktop = getDesktop(); <ide> View coordinateToChildView; <ide> switch (item._locationInLauncher) { <ide> case 0: <del> Desktop desktop = (Desktop) _$_findCachedViewById(R.id.desktop); <del> Desktop desktop2 = (Desktop) _$_findCachedViewById(R.id.desktop); <del> <del> coordinateToChildView = desktop2.getCurrentPage().coordinateToChildView(new Point(item._x, item._y)); <del> if (coordinateToChildView == null) { <del> Intrinsics.throwNpe(); <del> } <add> coordinateToChildView = desktop.getCurrentPage().coordinateToChildView(new Point(item._x, item._y)); <ide> desktop.removeItem(coordinateToChildView, true); <ide> break; <ide> case 1: <del> Dock dock = (Dock) _$_findCachedViewById(R.id.dock); <del> coordinateToChildView = ((Dock) _$_findCachedViewById(R.id.dock)).coordinateToChildView(new Point(item._x, item._y)); <del> if (coordinateToChildView == null) { <del> Intrinsics.throwNpe(); <del> } <add> Dock dock = getDock(); <add> coordinateToChildView = dock.coordinateToChildView(new Point(item._x, item._y)); <ide> dock.removeItem(coordinateToChildView, true); <ide> break; <ide> default: <ide> StringBuilder stringBuilder = new StringBuilder(); <ide> stringBuilder.append("package:"); <ide> Intent intent = item._intent; <del> if (intent == null) { <del> Intrinsics.throwNpe(); <del> } <ide> ComponentName component = intent.getComponent(); <del> if (component == null) { <del> Intrinsics.throwNpe(); <del> } <ide> stringBuilder.append(component.getPackageName()); <ide> startActivity(new Intent(str, Uri.parse(stringBuilder.toString()))); <ide> } catch (Exception e) { <ide> } <ide> <ide> public void onDesktopEdit() { <del> Tool.visibleViews(100, 20, (DesktopOptionView) _$_findCachedViewById(R.id.desktopEditOptionPanel)); <add> Tool.visibleViews(100, 20, (DesktopOptionView) findViewById(R.id.desktopEditOptionPanel)); <ide> hideDesktopIndicator(); <ide> updateDock$default(this, false, 0, 2, null); <ide> updateSearchBar(false); <ide> } <ide> <ide> public void onFinishDesktopEdit() { <del> Tool.invisibleViews(100, 20, (DesktopOptionView) _$_findCachedViewById(R.id.desktopEditOptionPanel)); <del> ((PagerIndicator) _$_findCachedViewById(R.id.desktopIndicator)).hideDelay(); <add> Tool.invisibleViews(100, 20, (DesktopOptionView) findViewById(R.id.desktopEditOptionPanel)); <add> ((PagerIndicator) findViewById(R.id.desktopIndicator)).hideDelay(); <ide> showDesktopIndicator(); <ide> updateDock$default(this, true, 0, 2, null); <ide> updateSearchBar(true); <ide> public void onSetPageAsHome() { <ide> AppSettings appSettings = Setup.appSettings(); <ide> <del> Desktop desktop = (Desktop) _$_findCachedViewById(R.id.desktop); <del> if (desktop == null) { <del> Intrinsics.throwNpe(); <del> } <add> Desktop desktop = findViewById(R.id.desktop); <ide> appSettings.setDesktopPageCurrent(desktop.getCurrentItem()); <ide> } <ide> <ide> <ide> private final void initDock() { <ide> int iconSize = Setup.appSettings().getDockIconSize(); <del> Dock dock = (Dock) _$_findCachedViewById(R.id.dock); <del> if (dock == null) { <del> Intrinsics.throwNpe(); <del> } <add> Dock dock = findViewById(R.id.dock); <ide> dock.setHome(this); <ide> dock.init(); <ide> AppSettings appSettings = Setup.appSettings(); <ide> <ide> if (appSettings.isDockShowLabel()) { <del> dock = (Dock) _$_findCachedViewById(R.id.dock); <del> if (dock == null) { <del> Intrinsics.throwNpe(); <del> } <del> dock.getLayoutParams().height = Tool.dp2px(((16 + iconSize) + 14) + 10, (Context) this) + dock.getBottomInset(); <add> dock.getLayoutParams().height = Tool.dp2px(((16 + iconSize) + 14) + 10, this) + dock.getBottomInset(); <ide> } else { <del> dock = (Dock) _$_findCachedViewById(R.id.dock); <del> if (dock == null) { <del> Intrinsics.throwNpe(); <del> } <del> dock.getLayoutParams().height = Tool.dp2px((16 + iconSize) + 10, (Context) this) + dock.getBottomInset(); <add> dock.getLayoutParams().height = Tool.dp2px((16 + iconSize) + 10, this) + dock.getBottomInset(); <ide> } <ide> } <ide> <ide> public final void dimBackground() { <del> Tool.visibleViews(_$_findCachedViewById(R.id.background)); <add> Tool.visibleViews(findViewById(R.id.background)); <ide> } <ide> <ide> public final void unDimBackground() { <del> Tool.invisibleViews(_$_findCachedViewById(R.id.background)); <add> Tool.invisibleViews(findViewById(R.id.background)); <ide> } <ide> <ide> public final void clearRoomForPopUp() { <del> Tool.invisibleViews((Desktop) _$_findCachedViewById(R.id.desktop)); <add> Tool.invisibleViews((Desktop) findViewById(R.id.desktop)); <ide> hideDesktopIndicator(); <ide> updateDock$default(this, false, 0, 2, null); <ide> } <ide> <ide> public final void unClearRoomForPopUp() { <del> Tool.visibleViews((Desktop) _$_findCachedViewById(R.id.desktop)); <add> Tool.visibleViews((Desktop) findViewById(R.id.desktop)); <ide> showDesktopIndicator(); <ide> updateDock$default(this, true, 0, 2, null); <ide> } <ide> LayoutParams layoutParams; <ide> PagerIndicator pagerIndicator; <ide> if (appSettings.getDockEnable() && show) { <del> Tool.visibleViews(100, delay, (Dock) _$_findCachedViewById(R.id.dock)); <del> desktop = (Desktop) _$_findCachedViewById(R.id.desktop); <del> if (desktop == null) { <del> Intrinsics.throwNpe(); <del> } <add> Tool.visibleViews(100, delay, (Dock) findViewById(R.id.dock)); <add> desktop = findViewById(R.id.desktop); <ide> layoutParams = desktop.getLayoutParams(); <del> if (layoutParams == null) { <del> throw new TypeCastException("null cannot be cast to non-null _type android.view.ViewGroup.MarginLayoutParams"); <del> } <del> ((MarginLayoutParams) layoutParams).bottomMargin = Tool.dp2px(4, (Context) this); <del> pagerIndicator = (PagerIndicator) _$_findCachedViewById(R.id.desktopIndicator); <del> if (pagerIndicator == null) { <del> Intrinsics.throwNpe(); <del> } <add> ((MarginLayoutParams) layoutParams).bottomMargin = Tool.dp2px(4, this); <add> pagerIndicator = findViewById(R.id.desktopIndicator); <ide> layoutParams = pagerIndicator.getLayoutParams(); <del> if (layoutParams == null) { <del> throw new TypeCastException("null cannot be cast to non-null _type android.view.ViewGroup.MarginLayoutParams"); <del> } <del> ((MarginLayoutParams) layoutParams).bottomMargin = Tool.dp2px(4, (Context) this); <add> ((MarginLayoutParams) layoutParams).bottomMargin = Tool.dp2px(4, this); <ide> } else { <ide> appSettings = Setup.appSettings(); <ide> <ide> if (appSettings.getDockEnable()) { <del> Tool.invisibleViews(100, (Dock) _$_findCachedViewById(R.id.dock)); <add> Tool.invisibleViews(100, (Dock) findViewById(R.id.dock)); <ide> } else { <del> Tool.goneViews(100, (Dock) _$_findCachedViewById(R.id.dock)); <del> pagerIndicator = (PagerIndicator) _$_findCachedViewById(R.id.desktopIndicator); <del> if (pagerIndicator == null) { <del> Intrinsics.throwNpe(); <del> } <add> Tool.goneViews(100, (Dock) findViewById(R.id.dock)); <add> pagerIndicator = findViewById(R.id.desktopIndicator); <ide> layoutParams = pagerIndicator.getLayoutParams(); <ide> if (layoutParams == null) { <ide> throw new TypeCastException("null cannot be cast to non-null _type android.view.ViewGroup.MarginLayoutParams"); <ide> } <ide> ((MarginLayoutParams) layoutParams).bottomMargin = Desktop._bottomInset + Tool.dp2px(4, (Context) this); <del> desktop = (Desktop) _$_findCachedViewById(R.id.desktop); <del> if (desktop == null) { <del> Intrinsics.throwNpe(); <del> } <add> desktop = (Desktop) findViewById(R.id.desktop); <ide> layoutParams = desktop.getLayoutParams(); <ide> if (layoutParams == null) { <ide> throw new TypeCastException("null cannot be cast to non-null _type android.view.ViewGroup.MarginLayoutParams"); <ide> AppSettings appSettings = Setup.appSettings(); <ide> <ide> if (appSettings.getSearchBarEnable() && show) { <del> Tool.visibleViews(100, (SearchBar) _$_findCachedViewById(R.id.searchBar)); <add> Tool.visibleViews(100, (SearchBar) findViewById(R.id.searchBar)); <ide> } else { <ide> appSettings = Setup.appSettings(); <ide> <ide> if (appSettings.getSearchBarEnable()) { <del> Tool.invisibleViews(100, (SearchBar) _$_findCachedViewById(R.id.searchBar)); <add> Tool.invisibleViews(100, (SearchBar) findViewById(R.id.searchBar)); <ide> } else { <del> Tool.goneViews((SearchBar) _$_findCachedViewById(R.id.searchBar)); <add> Tool.goneViews((SearchBar) findViewById(R.id.searchBar)); <ide> } <ide> } <ide> } <ide> AppSettings appSettings = Setup.appSettings(); <ide> <ide> if (appSettings.isDesktopShowIndicator()) { <del> Tool.visibleViews(100, (PagerIndicator) _$_findCachedViewById(R.id.desktopIndicator)); <add> Tool.visibleViews(100, (PagerIndicator) findViewById(R.id.desktopIndicator)); <ide> return; <ide> } <del> Tool.goneViews(100, (PagerIndicator) _$_findCachedViewById(R.id.desktopIndicator)); <add> Tool.goneViews(100, (PagerIndicator) findViewById(R.id.desktopIndicator)); <ide> } <ide> <ide> public final void hideDesktopIndicator() { <ide> AppSettings appSettings = Setup.appSettings(); <ide> <ide> if (appSettings.isDesktopShowIndicator()) { <del> Tool.invisibleViews(100, (PagerIndicator) _$_findCachedViewById(R.id.desktopIndicator)); <add> Tool.invisibleViews(100, (PagerIndicator) findViewById(R.id.desktopIndicator)); <ide> } <ide> } <ide> <ide> AppSettings appSettings = Setup.appSettings(); <ide> <ide> if (appSettings.isDesktopShowIndicator()) { <del> Tool.visibleViews(100, (PagerIndicator) _$_findCachedViewById(R.id.desktopIndicator)); <add> Tool.visibleViews(100, (PagerIndicator) findViewById(R.id.desktopIndicator)); <ide> } <ide> } <ide> <ide> public final void updateSearchClock() { <del> SearchBar searchBar = (SearchBar) _$_findCachedViewById(R.id.searchBar); <del> if (searchBar == null) { <del> Intrinsics.throwNpe(); <del> } <add> SearchBar searchBar = (SearchBar) findViewById(R.id.searchBar); <ide> TextView textView = searchBar._searchClock; <ide> <ide> if (textView.getText() != null) { <ide> try { <del> searchBar = (SearchBar) _$_findCachedViewById(R.id.searchBar); <del> if (searchBar == null) { <del> Intrinsics.throwNpe(); <del> } <add> searchBar = (SearchBar) findViewById(R.id.searchBar); <ide> searchBar.updateClock(); <ide> } catch (Exception e) { <del> ((SearchBar) _$_findCachedViewById(R.id.searchBar))._searchClock.setText(R.string.bad_format); <add> ((SearchBar) findViewById(R.id.searchBar))._searchClock.setText(R.string.bad_format); <ide> } <ide> } <ide> } <ide> AppSettings appSettings = Setup.appSettings(); <ide> <ide> if (!appSettings.getSearchBarEnable()) { <del> View _$_findCachedViewById = _$_findCachedViewById(R.id.leftDragHandle); <del> if (_$_findCachedViewById == null) { <del> Intrinsics.throwNpe(); <del> } <del> LayoutParams layoutParams = _$_findCachedViewById.getLayoutParams(); <del> if (layoutParams == null) { <del> throw new TypeCastException("null cannot be cast to non-null _type android.view.ViewGroup.MarginLayoutParams"); <del> } <add> View findViewById = findViewById(R.id.leftDragHandle); <add> LayoutParams layoutParams = findViewById.getLayoutParams(); <ide> ((MarginLayoutParams) layoutParams).topMargin = Desktop._topInset; <del> _$_findCachedViewById = _$_findCachedViewById(R.id.rightDragHandle); <del> if (_$_findCachedViewById == null) { <del> Intrinsics.throwNpe(); <del> } <del> layoutParams = _$_findCachedViewById.getLayoutParams(); <del> if (layoutParams == null) { <del> throw new TypeCastException("null cannot be cast to non-null _type android.view.ViewGroup.MarginLayoutParams"); <del> } <add> findViewById = findViewById(R.id.rightDragHandle); <add> layoutParams = findViewById.getLayoutParams(); <ide> Desktop desktop; <ide> ((MarginLayoutParams) layoutParams).topMargin = Desktop._topInset; <del> desktop = (Desktop) _$_findCachedViewById(R.id.desktop); <del> if (desktop == null) { <del> Intrinsics.throwNpe(); <del> } <add> desktop = (Desktop) findViewById(R.id.desktop); <ide> desktop.setPadding(0, Desktop._topInset, 0, 0); <ide> } <ide> appSettings = Setup.appSettings(); <ide> } <ide> <ide> private final void configureWidget(Intent data) { <del> if (data == null) { <del> Intrinsics.throwNpe(); <del> } <ide> Bundle extras = data.getExtras(); <del> if (extras == null) { <del> Intrinsics.throwNpe(); <del> } <ide> int appWidgetId = extras.getInt("appWidgetId", -1); <ide> AppWidgetProviderInfo appWidgetInfo = Companion.getAppWidgetManager().getAppWidgetInfo(appWidgetId); <ide> if (appWidgetInfo.configure != null) { <ide> } <ide> <ide> private final void createWidget(Intent data) { <del> if (data == null) { <del> Intrinsics.throwNpe(); <del> } <ide> Bundle extras = data.getExtras(); <del> if (extras == null) { <del> Intrinsics.throwNpe(); <del> } <ide> int appWidgetId = extras.getInt("appWidgetId", -1); <ide> AppWidgetProviderInfo appWidgetInfo = Companion.getAppWidgetManager().getAppWidgetInfo(appWidgetId); <ide> Item item = Item.newWidgetItem(appWidgetId); <ide> int i = appWidgetInfo.minWidth - 1; <del> Desktop desktop = (Desktop) _$_findCachedViewById(R.id.desktop); <del> if (desktop == null) { <del> Intrinsics.throwNpe(); <del> } <del> List pages = desktop.getPages(); <add> List pages = getDesktop().getPages(); <ide> Home launcher = Companion.getLauncher(); <del> if (launcher == null) { <del> Intrinsics.throwNpe(); <del> } <del> Desktop desktop2 = (Desktop) launcher._$_findCachedViewById(R.id.desktop); <del> if (desktop2 == null) { <del> Intrinsics.throwNpe(); <del> } <add> Desktop desktop2 = (Desktop) launcher.findViewById(R.id.desktop); <ide> Object obj = pages.get(desktop2.getCurrentItem()); <ide> <ide> item._spanX = (i / ((CellContainer) obj).getCellWidth()) + 1; <ide> i = appWidgetInfo.minHeight - 1; <del> desktop = (Desktop) _$_findCachedViewById(R.id.desktop); <del> if (desktop == null) { <del> Intrinsics.throwNpe(); <del> } <del> pages = desktop.getPages(); <add> pages = getDesktop().getPages(); <ide> launcher = Companion.getLauncher(); <del> if (launcher == null) { <del> Intrinsics.throwNpe(); <del> } <del> desktop2 = (Desktop) launcher._$_findCachedViewById(R.id.desktop); <del> if (desktop2 == null) { <del> Intrinsics.throwNpe(); <del> } <ide> obj = pages.get(desktop2.getCurrentItem()); <ide> <ide> item._spanY = (i / ((CellContainer) obj).getCellHeight()) + 1; <del> Desktop desktop3 = (Desktop) _$_findCachedViewById(R.id.desktop); <del> if (desktop3 == null) { <del> Intrinsics.throwNpe(); <del> } <add> Desktop desktop3 = (Desktop) findViewById(R.id.desktop); <ide> Point point = desktop3.getCurrentPage().findFreeSpace(item._spanX, item._spanY); <ide> if (point != null) { <ide> item._x = point.x; <ide> item._y = point.y; <ide> DataManager db = Companion.getDb(); <del> desktop2 = (Desktop) _$_findCachedViewById(R.id.desktop); <del> if (desktop2 == null) { <del> Intrinsics.throwNpe(); <del> } <ide> db.saveItem(item, desktop2.getCurrentItem(), ItemPosition.Desktop); <del> desktop = (Desktop) _$_findCachedViewById(R.id.desktop); <del> if (desktop == null) { <del> Intrinsics.throwNpe(); <del> } <del> desktop2 = (Desktop) _$_findCachedViewById(R.id.desktop); <del> if (desktop2 == null) { <del> Intrinsics.throwNpe(); <del> } <del> desktop.addItemToPage(item, desktop2.getCurrentItem()); <add> getDesktop().addItemToPage(item, getDesktop().getCurrentItem()); <ide> } else { <ide> Tool.toast((Context) this, (int) R.string.toast_not_enough_space); <ide> } <ide> } <ide> <ide> protected void onHandleLauncherPause() { <del> ((GroupPopupView) _$_findCachedViewById(R.id.groupPopup)).dismissPopup(); <del> ((CalendarDropDownView) _$_findCachedViewById(R.id.calendarDropDownView)).animateHide(); <del> ((DragNDropLayout) _$_findCachedViewById(R.id.dragNDropView)).hidePopupMenu(); <del> if (!((SearchBar) _$_findCachedViewById(R.id.searchBar)).collapse()) { <del> if (((Desktop) _$_findCachedViewById(R.id.desktop)) != null) { <del> Desktop desktop = (Desktop) _$_findCachedViewById(R.id.desktop); <add> ((GroupPopupView) findViewById(R.id.groupPopup)).dismissPopup(); <add> ((CalendarDropDownView) findViewById(R.id.calendarDropDownView)).animateHide(); <add> ((DragNDropLayout) findViewById(R.id.dragNDropView)).hidePopupMenu(); <add> if (!((SearchBar) findViewById(R.id.searchBar)).collapse()) { <add> if (((Desktop) findViewById(R.id.desktop)) != null) { <add> Desktop desktop = (Desktop) findViewById(R.id.desktop); <ide> <ide> if (desktop.getInEditMode()) { <del> desktop = (Desktop) _$_findCachedViewById(R.id.desktop); <add> desktop = (Desktop) findViewById(R.id.desktop); <ide> <ide> List pages = desktop.getPages(); <del> Desktop desktop2 = (Desktop) _$_findCachedViewById(R.id.desktop); <add> Desktop desktop2 = (Desktop) findViewById(R.id.desktop); <ide> <ide> ((CellContainer) pages.get(desktop2.getCurrentItem())).performClick(); <ide> } else { <del> AppDrawerController appDrawerController = (AppDrawerController) _$_findCachedViewById(R.id.appDrawerController); <add> AppDrawerController appDrawerController = (AppDrawerController) findViewById(R.id.appDrawerController); <ide> <ide> View drawer = appDrawerController.getDrawer(); <ide> <ide> } <ide> <ide> private final void setToHomePage() { <del> Desktop desktop = (Desktop) _$_findCachedViewById(R.id.desktop); <add> Desktop desktop = (Desktop) findViewById(R.id.desktop); <ide> <ide> AppSettings appSettings = Setup.appSettings(); <ide> <ide> @JvmOverloads <ide> public static /* bridge */ /* synthetic */ void openAppDrawer$default(Home home, View view, int i, int i2, int i3, Object obj) { <ide> if ((i3 & 1) != 0) { <del> view = (Desktop) home._$_findCachedViewById(R.id.desktop); <add> view = (Desktop) home.findViewById(R.id.desktop); <ide> } <ide> if ((i3 & 2) != 0) { <ide> i = -1;
Java
mit
c70ccbde346d0e6416d3ba5f42f829af5a58deeb
0
zalando/problem-spring-web,zalando/problem-spring-web
package org.zalando.problem.spring.web.advice; import com.google.gag.annotation.remark.Hack; import lombok.SneakyThrows; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.server.ServerHttpResponse; import org.springframework.http.server.ServletServerHttpResponse; import org.springframework.stereotype.Controller; import org.springframework.web.HttpMediaTypeNotAcceptableException; import org.springframework.web.accept.HeaderContentNegotiationStrategy; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver; import org.zalando.problem.Problem; import org.zalando.problem.ProblemBuilder; import org.zalando.problem.Status; import org.zalando.problem.StatusType; import org.zalando.problem.ThrowableProblem; import org.zalando.problem.spring.web.advice.custom.CustomAdviceTrait; import org.zalando.problem.spring.web.advice.general.GeneralAdviceTrait; import org.zalando.problem.spring.web.advice.http.HttpAdviceTrait; import org.zalando.problem.spring.web.advice.io.IOAdviceTrait; import org.zalando.problem.spring.web.advice.routing.RoutingAdviceTrait; import org.zalando.problem.spring.web.advice.validation.ValidationAdviceTrait; import javax.annotation.Nullable; import javax.servlet.http.HttpServletResponse; import java.net.URI; import java.util.List; import java.util.Optional; import static java.util.Arrays.asList; import static javax.servlet.RequestDispatcher.ERROR_EXCEPTION; import static org.springframework.core.annotation.AnnotatedElementUtils.findMergedAnnotation; import static org.springframework.http.HttpStatus.NOT_ACCEPTABLE; import static org.springframework.http.MediaType.APPLICATION_JSON; import static org.springframework.web.context.request.RequestAttributes.SCOPE_REQUEST; import static org.zalando.fauxpas.FauxPas.throwingSupplier; import static org.zalando.problem.spring.web.advice.Lists.lengthOfTrailingPartialSubList; import static org.zalando.problem.spring.web.advice.MediaTypes.PROBLEM; import static org.zalando.problem.spring.web.advice.MediaTypes.WILDCARD_JSON; import static org.zalando.problem.spring.web.advice.MediaTypes.X_PROBLEM; /** * <p> * Advice traits are simple interfaces that provide a single method with a default * implementation. They are used to provide {@link ExceptionHandler} implementations to be used in * {@link Controller Controllers} and/or in a {@link ControllerAdvice}. Clients can choose which traits they what to * use à la carte. * </p> * <p> * Advice traits are grouped in packages, based on they use cases. Every package has a composite advice trait that * bundles all traits of that package. Additionally there is one {@link ProblemHandling major composite advice trait} * that in turn bundles all other composites. * </p> * * @see ControllerAdvice * @see ExceptionHandler * @see Throwable * @see Exception * @see Problem * @see ProblemHandling * @see CustomAdviceTrait * @see GeneralAdviceTrait * @see HttpAdviceTrait * @see IOAdviceTrait * @see RoutingAdviceTrait * @see ValidationAdviceTrait */ public interface AdviceTrait { Logger LOG = LoggerFactory.getLogger(AdviceTrait.class); /** * Creates a {@link Problem problem} {@link ResponseEntity response} for the given {@link Throwable throwable} * by taking any {@link ResponseStatus} annotation on the exception type or one of the causes into account. * * @param throwable exception being caught * @param request incoming request * @return the problem response * @see ResponseStatusExceptionResolver */ default ResponseEntity<Problem> create(final Throwable throwable, final NativeWebRequest request) { final ThrowableProblem problem = toProblem(throwable); return create(throwable, problem, request); } default ResponseEntity<Problem> create(final StatusType status, final Throwable throwable, final NativeWebRequest request) { return create(status, throwable, request, new HttpHeaders()); } default ResponseEntity<Problem> create(final StatusType status, final Throwable throwable, final NativeWebRequest request, final HttpHeaders headers) { return create(throwable, toProblem(throwable, status), request, headers); } default ResponseEntity<Problem> create(final StatusType status, final Throwable throwable, final NativeWebRequest request, final URI type) { return create(status, throwable, request, new HttpHeaders(), type); } default ResponseEntity<Problem> create(final StatusType status, final Throwable throwable, final NativeWebRequest request, final HttpHeaders headers, final URI type) { return create(throwable, toProblem(throwable, status, type), request, headers); } default ThrowableProblem toProblem(final Throwable throwable) { final StatusType status = Optional.ofNullable(resolveResponseStatus(throwable)) .<StatusType>map(ResponseStatusAdapter::new) .orElse(Status.INTERNAL_SERVER_ERROR); return toProblem(throwable, status); } default ResponseStatus resolveResponseStatus(final Throwable type) { @Nullable final ResponseStatus candidate = findMergedAnnotation(type.getClass(), ResponseStatus.class); return candidate == null && type.getCause() != null ? resolveResponseStatus(type.getCause()) : candidate; } default ThrowableProblem toProblem(final Throwable throwable, final StatusType status) { return toProblem(throwable, status, Problem.DEFAULT_TYPE); } default ThrowableProblem toProblem(final Throwable throwable, final StatusType status, final URI type) { final ThrowableProblem problem = prepare(throwable, type, status).build(); final StackTraceElement[] stackTrace = createStackTrace(throwable); problem.setStackTrace(stackTrace); return problem; } default ProblemBuilder prepare(final Throwable throwable, final URI type, final StatusType status) { return Problem.builder() .withType(type) .withTitle(status.getReasonPhrase()) .withStatus(status) .withDetail(throwable.getMessage()) .withCause(Optional.ofNullable(throwable.getCause()) .filter(cause -> isCausalChainsEnabled()) .map(this::toProblem) .orElse(null)); } default StackTraceElement[] createStackTrace(final Throwable throwable) { final Throwable cause = throwable.getCause(); if (cause == null || !isCausalChainsEnabled()) { return throwable.getStackTrace(); } else { final StackTraceElement[] next = cause.getStackTrace(); final StackTraceElement[] current = throwable.getStackTrace(); final int length = current.length - lengthOfTrailingPartialSubList(asList(next), asList(current)); final StackTraceElement[] stackTrace = new StackTraceElement[length]; System.arraycopy(current, 0, stackTrace, 0, length); return stackTrace; } } default boolean isCausalChainsEnabled() { return false; } default ResponseEntity<Problem> create(final ThrowableProblem problem, final NativeWebRequest request) { return create(problem, request, new HttpHeaders()); } default ResponseEntity<Problem> create(final ThrowableProblem problem, final NativeWebRequest request, final HttpHeaders headers) { return create(problem, problem, request, headers); } default ResponseEntity<Problem> create(final Throwable throwable, final Problem problem, final NativeWebRequest request) { return create(throwable, problem, request, new HttpHeaders()); } default ResponseEntity<Problem> create(final Throwable throwable, final Problem problem, final NativeWebRequest request, final HttpHeaders headers) { final HttpStatus status = HttpStatus.valueOf(Optional.ofNullable(problem.getStatus()) .orElse(Status.INTERNAL_SERVER_ERROR) .getStatusCode()); log(throwable, problem, request, status); if (status == HttpStatus.INTERNAL_SERVER_ERROR) { request.setAttribute(ERROR_EXCEPTION, throwable, SCOPE_REQUEST); } return process(negotiate(request).map(contentType -> ResponseEntity.status(status) .headers(headers) .contentType(contentType) .body(problem)) .orElseGet(throwingSupplier(() -> { final ResponseEntity<Problem> fallback = fallback(throwable, problem, request, headers); if (fallback.getBody() == null) { /* * Ugly hack to workaround an issue with Tomcat and Spring as described in * https://github.com/zalando/problem-spring-web/issues/84. * * The default fallback in case content negotiation failed is a 406 Not Acceptable without * a body. Tomcat will then display its error page since no body was written and the response * was not committed. In order to force Spring to flush/commit one would need to provide a * body but that in turn would fail because Spring would then fail to negotiate the correct * content type. * * Writing the status code, headers and flushing the body manually is a dirty way to bypass * both parties, Tomcat and Spring, at the same time. */ final ServerHttpResponse response = new ServletServerHttpResponse( request.getNativeResponse(HttpServletResponse.class)); response.setStatusCode(fallback.getStatusCode()); response.getHeaders().putAll(fallback.getHeaders()); response.getBody(); // just so we're actually flushing the body... response.flush(); } return fallback; })), request); } default void log( @SuppressWarnings("UnusedParameters") final Throwable throwable, @SuppressWarnings("UnusedParameters") final Problem problem, @SuppressWarnings("UnusedParameters") final NativeWebRequest request, final HttpStatus status) { if (status.is4xxClientError()) { LOG.warn("{}: {}", status.getReasonPhrase(), throwable.getMessage()); } else if (status.is5xxServerError()) { LOG.error(status.getReasonPhrase(), throwable); } } @SneakyThrows(HttpMediaTypeNotAcceptableException.class) default Optional<MediaType> negotiate(final NativeWebRequest request) { final HeaderContentNegotiationStrategy negotiator = new HeaderContentNegotiationStrategy(); final List<MediaType> mediaTypes = negotiator.resolveMediaTypes(request); if (mediaTypes.isEmpty()) { return Optional.of(PROBLEM); } for (final MediaType mediaType : mediaTypes) { if (mediaType.includes(APPLICATION_JSON) || mediaType.includes(PROBLEM)) { return Optional.of(PROBLEM); } else if (mediaType.includes(X_PROBLEM)) { return Optional.of(X_PROBLEM); } } @Hack("Accepting application/something+json doesn't make you understand application/problem+json, " + "but a lot of clients miss to send it correctly") final boolean isNeitherAcceptingJsonNorProblemJsonButSomeVendorSpecificJson = mediaTypes.stream().anyMatch(WILDCARD_JSON::includes); if (isNeitherAcceptingJsonNorProblemJsonButSomeVendorSpecificJson) { return Optional.of(PROBLEM); } return Optional.empty(); } default ResponseEntity<Problem> fallback( @SuppressWarnings("UnusedParameters") final Throwable throwable, @SuppressWarnings("UnusedParameters") final Problem problem, @SuppressWarnings("UnusedParameters") final NativeWebRequest request, @SuppressWarnings("UnusedParameters") final HttpHeaders headers) { return ResponseEntity.status(NOT_ACCEPTABLE).body(null); } default ResponseEntity<Problem> process( final ResponseEntity<Problem> entity, @SuppressWarnings("UnusedParameters") final NativeWebRequest request) { return process(entity); } default ResponseEntity<Problem> process(final ResponseEntity<Problem> entity) { return entity; } }
src/main/java/org/zalando/problem/spring/web/advice/AdviceTrait.java
package org.zalando.problem.spring.web.advice; import com.google.gag.annotation.remark.Hack; import lombok.SneakyThrows; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.server.ServerHttpResponse; import org.springframework.http.server.ServletServerHttpResponse; import org.springframework.stereotype.Controller; import org.springframework.web.HttpMediaTypeNotAcceptableException; import org.springframework.web.accept.HeaderContentNegotiationStrategy; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver; import org.zalando.problem.Problem; import org.zalando.problem.ProblemBuilder; import org.zalando.problem.Status; import org.zalando.problem.StatusType; import org.zalando.problem.ThrowableProblem; import org.zalando.problem.spring.web.advice.custom.CustomAdviceTrait; import org.zalando.problem.spring.web.advice.general.GeneralAdviceTrait; import org.zalando.problem.spring.web.advice.http.HttpAdviceTrait; import org.zalando.problem.spring.web.advice.io.IOAdviceTrait; import org.zalando.problem.spring.web.advice.routing.RoutingAdviceTrait; import org.zalando.problem.spring.web.advice.validation.ValidationAdviceTrait; import javax.annotation.Nullable; import javax.servlet.http.HttpServletResponse; import java.net.URI; import java.util.List; import java.util.Optional; import static java.util.Arrays.asList; import static javax.servlet.RequestDispatcher.ERROR_EXCEPTION; import static org.springframework.core.annotation.AnnotatedElementUtils.findMergedAnnotation; import static org.springframework.http.HttpStatus.NOT_ACCEPTABLE; import static org.springframework.http.MediaType.APPLICATION_JSON; import static org.springframework.web.context.request.RequestAttributes.SCOPE_REQUEST; import static org.zalando.fauxpas.FauxPas.throwingSupplier; import static org.zalando.problem.spring.web.advice.Lists.lengthOfTrailingPartialSubList; import static org.zalando.problem.spring.web.advice.MediaTypes.PROBLEM; import static org.zalando.problem.spring.web.advice.MediaTypes.WILDCARD_JSON; import static org.zalando.problem.spring.web.advice.MediaTypes.X_PROBLEM; /** * <p> * Advice traits are simple interfaces that provide a single method with a default * implementation. They are used to provide {@link ExceptionHandler} implementations to be used in * {@link Controller Controllers} and/or in a {@link ControllerAdvice}. Clients can choose which traits they what to * use à la carte. * </p> * <p> * Advice traits are grouped in packages, based on they use cases. Every package has a composite advice trait that * bundles all traits of that package. Additionally there is one {@link ProblemHandling major composite advice trait} * that in turn bundles all other composites. * </p> * * @see ControllerAdvice * @see ExceptionHandler * @see Throwable * @see Exception * @see Problem * @see ProblemHandling * @see CustomAdviceTrait * @see GeneralAdviceTrait * @see HttpAdviceTrait * @see IOAdviceTrait * @see RoutingAdviceTrait * @see ValidationAdviceTrait */ public interface AdviceTrait { Logger LOG = LoggerFactory.getLogger(AdviceTrait.class); /** * Creates a {@link Problem problem} {@link ResponseEntity response} for the given {@link Throwable throwable} * by taking any {@link ResponseStatus} annotation on the exception type or one of the causes into account. * * @param throwable exception being caught * @param request incoming request * @return the problem response * @see ResponseStatusExceptionResolver */ default ResponseEntity<Problem> create(final Throwable throwable, final NativeWebRequest request) { final ThrowableProblem problem = toProblem(throwable); return create(throwable, problem, request); } default ResponseEntity<Problem> create(final StatusType status, final Throwable throwable, final NativeWebRequest request) { return create(status, throwable, request, new HttpHeaders()); } default ResponseEntity<Problem> create(final StatusType status, final Throwable throwable, final NativeWebRequest request, final HttpHeaders headers) { return create(throwable, toProblem(throwable, status), request, headers); } default ResponseEntity<Problem> create(final StatusType status, final Throwable throwable, final NativeWebRequest request, final URI type) { return create(status, throwable, request, new HttpHeaders(), type); } default ResponseEntity<Problem> create(final StatusType status, final Throwable throwable, final NativeWebRequest request, final HttpHeaders headers, final URI type) { return create(throwable, toProblem(throwable, status, type), request, headers); } default ThrowableProblem toProblem(final Throwable throwable) { final StatusType status = Optional.ofNullable(resolveResponseStatus(throwable)) .<StatusType>map(ResponseStatusAdapter::new) .orElse(Status.INTERNAL_SERVER_ERROR); return toProblem(throwable, status); } default ResponseStatus resolveResponseStatus(final Throwable type) { @Nullable final ResponseStatus candidate = findMergedAnnotation(type.getClass(), ResponseStatus.class); return candidate == null && type.getCause() != null ? resolveResponseStatus(type.getCause()) : candidate; } default ThrowableProblem toProblem(final Throwable throwable, final StatusType status) { return toProblem(throwable, status, Problem.DEFAULT_TYPE); } default ThrowableProblem toProblem(final Throwable throwable, final StatusType status, final URI type) { final ThrowableProblem problem = prepare(throwable, type, status).build(); problem.setStackTrace(createStackTrace(throwable, prepare(throwable, type, status))); return problem; } default ProblemBuilder prepare(final Throwable throwable, final URI type, final StatusType status) { return Problem.builder() .withType(type) .withTitle(status.getReasonPhrase()) .withStatus(status) .withDetail(throwable.getMessage()); } default StackTraceElement[] createStackTrace(final Throwable throwable, final ProblemBuilder builder) { final Throwable cause = throwable.getCause(); if (cause == null || !isCausalChainsEnabled()) { return throwable.getStackTrace(); } else { builder.withCause(toProblem(cause)); final StackTraceElement[] next = cause.getStackTrace(); final StackTraceElement[] current = throwable.getStackTrace(); final int length = current.length - lengthOfTrailingPartialSubList(asList(next), asList(current)); final StackTraceElement[] stackTrace = new StackTraceElement[length]; System.arraycopy(current, 0, stackTrace, 0, length); return stackTrace; } } default boolean isCausalChainsEnabled() { return false; } default ResponseEntity<Problem> create(final ThrowableProblem problem, final NativeWebRequest request) { return create(problem, request, new HttpHeaders()); } default ResponseEntity<Problem> create(final ThrowableProblem problem, final NativeWebRequest request, final HttpHeaders headers) { return create(problem, problem, request, headers); } default ResponseEntity<Problem> create(final Throwable throwable, final Problem problem, final NativeWebRequest request) { return create(throwable, problem, request, new HttpHeaders()); } default ResponseEntity<Problem> create(final Throwable throwable, final Problem problem, final NativeWebRequest request, final HttpHeaders headers) { final HttpStatus status = HttpStatus.valueOf(Optional.ofNullable(problem.getStatus()) .orElse(Status.INTERNAL_SERVER_ERROR) .getStatusCode()); log(throwable, problem, request, status); if (status == HttpStatus.INTERNAL_SERVER_ERROR) { request.setAttribute(ERROR_EXCEPTION, throwable, SCOPE_REQUEST); } return process(negotiate(request).map(contentType -> ResponseEntity.status(status) .headers(headers) .contentType(contentType) .body(problem)) .orElseGet(throwingSupplier(() -> { final ResponseEntity<Problem> fallback = fallback(throwable, problem, request, headers); if (fallback.getBody() == null) { /* * Ugly hack to workaround an issue with Tomcat and Spring as described in * https://github.com/zalando/problem-spring-web/issues/84. * * The default fallback in case content negotiation failed is a 406 Not Acceptable without * a body. Tomcat will then display its error page since no body was written and the response * was not committed. In order to force Spring to flush/commit one would need to provide a * body but that in turn would fail because Spring would then fail to negotiate the correct * content type. * * Writing the status code, headers and flushing the body manually is a dirty way to bypass * both parties, Tomcat and Spring, at the same time. */ final ServerHttpResponse response = new ServletServerHttpResponse( request.getNativeResponse(HttpServletResponse.class)); response.setStatusCode(fallback.getStatusCode()); response.getHeaders().putAll(fallback.getHeaders()); response.getBody(); // just so we're actually flushing the body... response.flush(); } return fallback; })), request); } default void log( @SuppressWarnings("UnusedParameters") final Throwable throwable, @SuppressWarnings("UnusedParameters") final Problem problem, @SuppressWarnings("UnusedParameters") final NativeWebRequest request, final HttpStatus status) { if (status.is4xxClientError()) { LOG.warn("{}: {}", status.getReasonPhrase(), throwable.getMessage()); } else if (status.is5xxServerError()) { LOG.error(status.getReasonPhrase(), throwable); } } @SneakyThrows(HttpMediaTypeNotAcceptableException.class) default Optional<MediaType> negotiate(final NativeWebRequest request) { final HeaderContentNegotiationStrategy negotiator = new HeaderContentNegotiationStrategy(); final List<MediaType> mediaTypes = negotiator.resolveMediaTypes(request); if (mediaTypes.isEmpty()) { return Optional.of(PROBLEM); } for (final MediaType mediaType : mediaTypes) { if (mediaType.includes(APPLICATION_JSON) || mediaType.includes(PROBLEM)) { return Optional.of(PROBLEM); } else if (mediaType.includes(X_PROBLEM)) { return Optional.of(X_PROBLEM); } } @Hack("Accepting application/something+json doesn't make you understand application/problem+json, " + "but a lot of clients miss to send it correctly") final boolean isNeitherAcceptingJsonNorProblemJsonButSomeVendorSpecificJson = mediaTypes.stream().anyMatch(WILDCARD_JSON::includes); if (isNeitherAcceptingJsonNorProblemJsonButSomeVendorSpecificJson) { return Optional.of(PROBLEM); } return Optional.empty(); } default ResponseEntity<Problem> fallback( @SuppressWarnings("UnusedParameters") final Throwable throwable, @SuppressWarnings("UnusedParameters") final Problem problem, @SuppressWarnings("UnusedParameters") final NativeWebRequest request, @SuppressWarnings("UnusedParameters") final HttpHeaders headers) { return ResponseEntity.status(NOT_ACCEPTABLE).body(null); } default ResponseEntity<Problem> process( final ResponseEntity<Problem> entity, @SuppressWarnings("UnusedParameters") final NativeWebRequest request) { return process(entity); } default ResponseEntity<Problem> process(final ResponseEntity<Problem> entity) { return entity; } }
Fixed test
src/main/java/org/zalando/problem/spring/web/advice/AdviceTrait.java
Fixed test
<ide><path>rc/main/java/org/zalando/problem/spring/web/advice/AdviceTrait.java <ide> <ide> default ThrowableProblem toProblem(final Throwable throwable, final StatusType status, final URI type) { <ide> final ThrowableProblem problem = prepare(throwable, type, status).build(); <del> problem.setStackTrace(createStackTrace(throwable, prepare(throwable, type, status))); <add> final StackTraceElement[] stackTrace = createStackTrace(throwable); <add> problem.setStackTrace(stackTrace); <ide> return problem; <ide> } <ide> <ide> .withType(type) <ide> .withTitle(status.getReasonPhrase()) <ide> .withStatus(status) <del> .withDetail(throwable.getMessage()); <del> } <del> <del> default StackTraceElement[] createStackTrace(final Throwable throwable, final ProblemBuilder builder) { <add> .withDetail(throwable.getMessage()) <add> .withCause(Optional.ofNullable(throwable.getCause()) <add> .filter(cause -> isCausalChainsEnabled()) <add> .map(this::toProblem) <add> .orElse(null)); <add> } <add> <add> default StackTraceElement[] createStackTrace(final Throwable throwable) { <ide> final Throwable cause = throwable.getCause(); <ide> <ide> if (cause == null || !isCausalChainsEnabled()) { <ide> return throwable.getStackTrace(); <ide> } else { <del> builder.withCause(toProblem(cause)); <ide> <ide> final StackTraceElement[] next = cause.getStackTrace(); <ide> final StackTraceElement[] current = throwable.getStackTrace();
Java
epl-1.0
d384b0b1528b49527c6571ee74fc55fc1b1b8dc1
0
ForgeEssentials/ForgeEssentialsMain
package com.forgeessentials.util; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.util.UUID; import javax.net.ssl.HttpsURLConnection; import com.forgeessentials.util.output.LoggingHandler; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; public class UserIdentUtils { public static String reformatUUID(String s) { if (s.length() != 32) throw new IllegalArgumentException(); return s.substring(0,8) + "-" + s.substring(8,12) + "-" + s.substring(12,16) + "-" + s.substring(16,20) + "-" + s.substring(20,32); } public static UUID stringToUUID(String s) { if (s.length() == 32) s = reformatUUID(s); return UUID.fromString(s); } public static UUID resolveMissingUUID(String name) { String url = "https://api.mojang.com/users/profiles/minecraft/" + name; String data = fetchData(url, "id"); if (data != null) return stringToUUID(data); return null; } public static String resolveMissingUsername(UUID id) { String url = "https://api.mojang.com/user/profiles/" + id.toString().replace("-", "") + "/names"; return fetchData(url, "name"); } public static String fetchData(String url, String id) { try { LoggingHandler.felog.debug("Fetching " + id + " from " + url); URL uri = new URL(url); HttpsURLConnection huc = (HttpsURLConnection) uri.openConnection(); InputStream is; try (JsonReader jr = new JsonReader(new InputStreamReader(is = huc.getInputStream()))) { if (is.available() > 0 && jr.hasNext()) { if (jr.peek() == JsonToken.BEGIN_ARRAY) jr.beginArray(); JsonToken t = jr.peek(); while (t != JsonToken.END_ARRAY && t != JsonToken.END_DOCUMENT) { jr.beginObject(); String name = null; while (jr.hasNext()) if (jr.peek() == JsonToken.NAME) name = jr.nextName(); else { if (jr.peek() == JsonToken.STRING) if (name.equals(id)) return jr.nextString(); //This should return before the array finishes name = null; } jr.endObject(); } jr.endArray(); } } return null; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } }
src/main/java/com/forgeessentials/util/UserIdentUtils.java
package com.forgeessentials.util; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.util.UUID; import javax.net.ssl.HttpsURLConnection; import com.forgeessentials.util.output.LoggingHandler; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; public class UserIdentUtils { public static UUID hexStringToUUID(String s) { if (s.length() != 32) throw new IllegalArgumentException(); byte[] data = new byte[32]; for (int i = 0; i < 32; i++) { data[i] = (byte) s.charAt(i); } return UUID.nameUUIDFromBytes(data); } public static UUID stringToUUID(String s) { if (s.length() == 32) return hexStringToUUID(s); else return UUID.fromString(s); } public static UUID resolveMissingUUID(String name) { String url = "https://api.mojang.com/users/profiles/minecraft/" + name; String data = fetchData(url, "id"); if (data != null) return stringToUUID(data); return null; } public static String resolveMissingUsername(UUID id) { String url = "https://api.mojang.com/user/profiles/" + id.toString().replace("-", "") + "/names"; return fetchData(url, "name"); } public static String fetchData(String url, String id) { try { LoggingHandler.felog.debug("Fetching " + id + " from " + url); URL uri = new URL(url); HttpsURLConnection huc = (HttpsURLConnection) uri.openConnection(); InputStream is; try (JsonReader jr = new JsonReader(new InputStreamReader(is = huc.getInputStream()))) { if (is.available() > 0 && jr.hasNext()) { jr.beginObject(); String name = null; while (jr.hasNext()) if (jr.peek() == JsonToken.NAME) name = jr.nextName(); else { if (jr.peek() == JsonToken.STRING) if (name.equals(id)) return jr.nextString(); name = null; } jr.endObject(); } } return null; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } }
Fixes #2252 #2253 (cherry picked from commit 1e5c5e4)
src/main/java/com/forgeessentials/util/UserIdentUtils.java
Fixes #2252 #2253
<ide><path>rc/main/java/com/forgeessentials/util/UserIdentUtils.java <ide> public class UserIdentUtils <ide> { <ide> <del> public static UUID hexStringToUUID(String s) <add> public static String reformatUUID(String s) <ide> { <ide> if (s.length() != 32) <ide> throw new IllegalArgumentException(); <del> byte[] data = new byte[32]; <del> for (int i = 0; i < 32; i++) <del> { <del> data[i] = (byte) s.charAt(i); <del> } <del> return UUID.nameUUIDFromBytes(data); <add> return s.substring(0,8) + "-" + s.substring(8,12) + "-" + s.substring(12,16) + "-" + s.substring(16,20) + "-" + s.substring(20,32); <ide> } <ide> <ide> public static UUID stringToUUID(String s) <ide> { <ide> if (s.length() == 32) <del> return hexStringToUUID(s); <del> else <del> return UUID.fromString(s); <add> s = reformatUUID(s); <add> return UUID.fromString(s); <ide> <ide> } <ide> <ide> { <ide> if (is.available() > 0 && jr.hasNext()) <ide> { <del> jr.beginObject(); <del> String name = null; <add> if (jr.peek() == JsonToken.BEGIN_ARRAY) <add> jr.beginArray(); <add> JsonToken t = jr.peek(); <add> while (t != JsonToken.END_ARRAY && t != JsonToken.END_DOCUMENT) <add> { <add> jr.beginObject(); <add> String name = null; <ide> <del> while (jr.hasNext()) <del> if (jr.peek() == JsonToken.NAME) <del> name = jr.nextName(); <del> else <del> { <del> if (jr.peek() == JsonToken.STRING) <del> if (name.equals(id)) <del> return jr.nextString(); <del> name = null; <del> } <del> jr.endObject(); <add> while (jr.hasNext()) <add> if (jr.peek() == JsonToken.NAME) <add> name = jr.nextName(); <add> else <add> { <add> if (jr.peek() == JsonToken.STRING) <add> if (name.equals(id)) <add> return jr.nextString(); //This should return before the array finishes <add> name = null; <add> } <add> jr.endObject(); <add> } <add> jr.endArray(); <ide> } <ide> } <ide> return null;
Java
apache-2.0
9261a6e099ecb85acdc9df41a10f9db35eb29aca
0
apache/pdfbox,apache/pdfbox
/* * 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.pdfbox.examples.signature.validation; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.Security; import java.security.cert.CertificateEncodingException; import java.security.cert.X509CRL; import java.security.cert.X509Certificate; import java.util.Calendar; import java.util.HashSet; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.pdfbox.Loader; import org.apache.pdfbox.cos.COSArray; import org.apache.pdfbox.cos.COSBase; import org.apache.pdfbox.cos.COSDictionary; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.cos.COSStream; import org.apache.pdfbox.cos.COSUpdateInfo; import org.apache.pdfbox.examples.signature.SigUtils; import org.apache.pdfbox.examples.signature.cert.CRLVerifier; import org.apache.pdfbox.examples.signature.cert.CertificateVerificationException; import org.apache.pdfbox.examples.signature.cert.OcspHelper; import org.apache.pdfbox.examples.signature.cert.RevokedCertificateException; import org.apache.pdfbox.examples.signature.validation.CertInformationCollector.CertSignatureInformation; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDDocumentCatalog; import org.apache.pdfbox.pdmodel.encryption.SecurityProvider; import org.apache.pdfbox.pdmodel.interactive.digitalsignature.PDSignature; import org.apache.pdfbox.util.Hex; import org.bouncycastle.asn1.BEROctetString; import org.bouncycastle.asn1.ocsp.OCSPObjectIdentifiers; import org.bouncycastle.cert.ocsp.BasicOCSPResp; import org.bouncycastle.cert.ocsp.OCSPException; import org.bouncycastle.cert.ocsp.OCSPResp; import org.bouncycastle.cms.CMSException; import org.bouncycastle.cms.CMSSignedData; import org.bouncycastle.tsp.TSPException; import org.bouncycastle.tsp.TimeStampToken; import org.bouncycastle.tsp.TimeStampTokenInfo; /** * An example for adding Validation Information to a signed PDF, inspired by ETSI TS 102 778-4 * V1.1.2 (2009-12), Part 4: PAdES Long Term - PAdES-LTV Profile. This procedure appends the * Validation Information of the last signature (more precise its signer(s)) to a copy of the * document. The signature and the signed data will not be touched and stay valid. * <p> * See also <a href="http://eprints.hsr.ch/id/eprint/616">Bachelor thesis (in German) about LTV</a> * * @author Alexis Suter */ public class AddValidationInformation { private static final Log LOG = LogFactory.getLog(AddValidationInformation.class); private CertInformationCollector certInformationHelper; private COSArray correspondingOCSPs; private COSArray correspondingCRLs; private COSDictionary vriBase; private COSArray ocsps; private COSArray crls; private COSArray certs; private PDDocument document; private final Set<X509Certificate> foundRevocationInformation = new HashSet<>(); private Calendar signDate; private final Set<X509Certificate> ocspChecked = new HashSet<>(); //TODO foundRevocationInformation and ocspChecked have a similar purpose. One of them should likely // be removed and the code improved. When doing so, keep in mind that ocspChecked was added last, // because of a problem with freetsa. /** * Signs the given PDF file. * * @param inFile input PDF file * @param outFile output PDF file * @throws IOException if the input file could not be read */ public void validateSignature(File inFile, File outFile) throws IOException { if (inFile == null || !inFile.exists()) { String err = "Document for signing "; if (null == inFile) { err += "is null"; } else { err += "does not exist: " + inFile.getAbsolutePath(); } throw new FileNotFoundException(err); } try (PDDocument doc = Loader.loadPDF(inFile); FileOutputStream fos = new FileOutputStream(outFile)) { int accessPermissions = SigUtils.getMDPPermission(doc); if (accessPermissions == 1) { System.out.println("PDF is certified to forbid changes, " + "some readers may report the document as invalid despite that " + "the PDF specification allows DSS additions"); } document = doc; doValidation(inFile.getAbsolutePath(), fos); } } /** * Fetches certificate information from the last signature of the document and appends a DSS * with the validation information to the document. * * @param filename in file to extract signature * @param output where to write the changed document * @throws IOException */ private void doValidation(String filename, OutputStream output) throws IOException { certInformationHelper = new CertInformationCollector(); CertSignatureInformation certInfo = null; try { PDSignature signature = SigUtils.getLastRelevantSignature(document); if (signature != null) { certInfo = certInformationHelper.getLastCertInfo(signature, filename); signDate = signature.getSignDate(); if ("ETSI.RFC3161".equals(signature.getSubFilter())) { byte[] contents = signature.getContents(); TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(contents)); TimeStampTokenInfo timeStampInfo = timeStampToken.getTimeStampInfo(); signDate = Calendar.getInstance(); signDate.setTime(timeStampInfo.getGenTime()); } } } catch (TSPException | CMSException | CertificateProccessingException e) { throw new IOException("An Error occurred processing the Signature", e); } if (certInfo == null) { throw new IOException( "No Certificate information or signature found in the given document"); } PDDocumentCatalog docCatalog = document.getDocumentCatalog(); COSDictionary catalog = docCatalog.getCOSObject(); catalog.setNeedToBeUpdated(true); COSDictionary dss = getOrCreateDictionaryEntry(COSDictionary.class, catalog, "DSS"); addExtensions(docCatalog); vriBase = getOrCreateDictionaryEntry(COSDictionary.class, dss, "VRI"); ocsps = getOrCreateDictionaryEntry(COSArray.class, dss, "OCSPs"); crls = getOrCreateDictionaryEntry(COSArray.class, dss, "CRLs"); certs = getOrCreateDictionaryEntry(COSArray.class, dss, "Certs"); addRevocationData(certInfo); addAllCertsToCertArray(); // write incremental document.saveIncremental(output); } /** * Gets or creates a dictionary entry. If existing checks for the type and sets need to be * updated. * * @param clazz the class of the dictionary entry, must implement COSUpdateInfo * @param parent where to find the element * @param name of the element * @return a Element of given class, new or existing * @throws IOException when the type of the element is wrong */ private static <T extends COSBase & COSUpdateInfo> T getOrCreateDictionaryEntry(Class<T> clazz, COSDictionary parent, String name) throws IOException { T result; COSBase element = parent.getDictionaryObject(name); if (element != null && clazz.isInstance(element)) { result = clazz.cast(element); result.setNeedToBeUpdated(true); } else if (element != null) { throw new IOException("Element " + name + " from dictionary is not of type " + clazz.getCanonicalName()); } else { try { result = clazz.getDeclaredConstructor().newInstance(); } catch (ReflectiveOperationException | SecurityException e) { throw new IOException("Failed to create new instance of " + clazz.getCanonicalName(), e); } result.setDirect(false); parent.setItem(COSName.getPDFName(name), result); } return result; } /** * Fetches and adds revocation information based on the certInfo to the DSS. * * @param certInfo Certificate information from CertInformationHelper containing certificate * chains. * @throws IOException */ private void addRevocationData(CertSignatureInformation certInfo) throws IOException { COSDictionary vri = new COSDictionary(); vriBase.setItem(certInfo.getSignatureHash(), vri); updateVRI(certInfo, vri); if (certInfo.getTsaCerts() != null) { // Don't add RevocationInfo from tsa to VRI's correspondingOCSPs = null; correspondingCRLs = null; addRevocationDataRecursive(certInfo.getTsaCerts()); } } /** * Tries to get Revocation Data (first OCSP, else CRL) from the given Certificate Chain. * * @param certInfo from which to fetch revocation data. Will work recursively through its * chains. * @throws IOException when failed to fetch an revocation data. */ private void addRevocationDataRecursive(CertSignatureInformation certInfo) throws IOException { if (certInfo.isSelfSigned()) { return; } // To avoid getting same revocation information twice. boolean isRevocationInfoFound = foundRevocationInformation.contains(certInfo.getCertificate()); if (!isRevocationInfoFound) { if (certInfo.getOcspUrl() != null && certInfo.getIssuerCertificate() != null) { isRevocationInfoFound = fetchOcspData(certInfo); } if (!isRevocationInfoFound && certInfo.getCrlUrl() != null) { fetchCrlData(certInfo); isRevocationInfoFound = true; } if (certInfo.getOcspUrl() == null && certInfo.getCrlUrl() == null) { LOG.info("No revocation information for cert " + certInfo.getCertificate().getSubjectX500Principal()); } else if (!isRevocationInfoFound) { throw new IOException("Could not fetch Revocation Info for Cert: " + certInfo.getCertificate().getSubjectX500Principal()); } } if (certInfo.getAlternativeCertChain() != null) { addRevocationDataRecursive(certInfo.getAlternativeCertChain()); } if (certInfo.getCertChain() != null && certInfo.getCertChain().getCertificate() != null) { addRevocationDataRecursive(certInfo.getCertChain()); } } /** * Tries to fetch and add OCSP Data to its containers. * * @param certInfo the certificate info, for it to check OCSP data. * @return true when the OCSP data has successfully been fetched and added * @throws IOException when Certificate is revoked. */ private boolean fetchOcspData(CertSignatureInformation certInfo) throws IOException { try { addOcspData(certInfo); return true; } catch (OCSPException | CertificateProccessingException | IOException e) { LOG.error("Failed fetching OCSP at " + certInfo.getOcspUrl(), e); return false; } catch (RevokedCertificateException e) { throw new IOException(e); } } /** * Tries to fetch and add CRL Data to its containers. * * @param certInfo the certificate info, for it to check CRL data. * @throws IOException when failed to fetch, because no validation data could be fetched for * data. */ private void fetchCrlData(CertSignatureInformation certInfo) throws IOException { try { addCrlRevocationInfo(certInfo); } catch (GeneralSecurityException | IOException | RevokedCertificateException | CertificateVerificationException e) { LOG.warn("Failed fetching CRL", e); throw new IOException(e); } } /** * Fetches and adds OCSP data to storage for the given Certificate. * * @param certInfo the certificate info, for it to check OCSP data. * @throws IOException * @throws OCSPException * @throws CertificateProccessingException * @throws RevokedCertificateException */ private void addOcspData(CertSignatureInformation certInfo) throws IOException, OCSPException, CertificateProccessingException, RevokedCertificateException { if (ocspChecked.contains(certInfo.getCertificate())) { // This certificate has been OCSP-checked before return; } OcspHelper ocspHelper = new OcspHelper( certInfo.getCertificate(), signDate.getTime(), certInfo.getIssuerCertificate(), new HashSet<>(certInformationHelper.getCertificateSet()), certInfo.getOcspUrl()); OCSPResp ocspResp = ocspHelper.getResponseOcsp(); ocspChecked.add(certInfo.getCertificate()); BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResp.getResponseObject(); X509Certificate ocspResponderCertificate = ocspHelper.getOcspResponderCertificate(); certInformationHelper.addAllCertsFromHolders(basicResponse.getCerts()); byte[] signatureHash; try { // https://www.etsi.org/deliver/etsi_ts/102700_102799/10277804/01.01.02_60/ts_10277804v010102p.pdf // "For the signatures of the CRL and OCSP response, it is the respective signature // object represented as a BER-encoded OCTET STRING encoded with primitive encoding" BEROctetString encodedSignature = new BEROctetString(basicResponse.getSignature()); signatureHash = MessageDigest.getInstance("SHA-1").digest(encodedSignature.getEncoded()); } catch (NoSuchAlgorithmException ex) { throw new CertificateProccessingException(ex); } String signatureHashHex = Hex.getString(signatureHash); if (!vriBase.containsKey(signatureHashHex)) { COSArray savedCorrespondingOCSPs = correspondingOCSPs; COSArray savedCorrespondingCRLs = correspondingCRLs; COSDictionary vri = new COSDictionary(); vriBase.setItem(signatureHashHex, vri); CertSignatureInformation ocspCertInfo = certInformationHelper.getCertInfo(ocspResponderCertificate); updateVRI(ocspCertInfo, vri); correspondingOCSPs = savedCorrespondingOCSPs; correspondingCRLs = savedCorrespondingCRLs; } byte[] ocspData = ocspResp.getEncoded(); COSStream ocspStream = writeDataToStream(ocspData); ocsps.add(ocspStream); if (correspondingOCSPs != null) { correspondingOCSPs.add(ocspStream); } foundRevocationInformation.add(certInfo.getCertificate()); } /** * Fetches and adds CRL data to storage for the given Certificate. * * @param certInfo the certificate info, for it to check CRL data. * @throws IOException * @throws RevokedCertificateException * @throws GeneralSecurityException * @throws CertificateVerificationException */ private void addCrlRevocationInfo(CertSignatureInformation certInfo) throws IOException, RevokedCertificateException, GeneralSecurityException, CertificateVerificationException { X509CRL crl = CRLVerifier.downloadCRLFromWeb(certInfo.getCrlUrl()); X509Certificate issuerCertificate = certInfo.getIssuerCertificate(); // find the issuer certificate (usually issuer of signature certificate) for (X509Certificate certificate : certInformationHelper.getCertificateSet()) { if (certificate.getSubjectX500Principal().equals(crl.getIssuerX500Principal())) { issuerCertificate = certificate; break; } } crl.verify(issuerCertificate.getPublicKey(), SecurityProvider.getProvider().getName()); CRLVerifier.checkRevocation(crl, certInfo.getCertificate(), signDate.getTime(), certInfo.getCrlUrl()); COSStream crlStream = writeDataToStream(crl.getEncoded()); crls.add(crlStream); if (correspondingCRLs != null) { correspondingCRLs.add(crlStream); byte[] signatureHash; try { // https://www.etsi.org/deliver/etsi_ts/102700_102799/10277804/01.01.02_60/ts_10277804v010102p.pdf // "For the signatures of the CRL and OCSP response, it is the respective signature // object represented as a BER-encoded OCTET STRING encoded with primitive encoding" BEROctetString berEncodedSignature = new BEROctetString(crl.getSignature()); signatureHash = MessageDigest.getInstance("SHA-1").digest(berEncodedSignature.getEncoded()); } catch (NoSuchAlgorithmException ex) { throw new CertificateVerificationException(ex.getMessage(), ex); } String signatureHashHex = Hex.getString(signatureHash); if (!vriBase.containsKey(signatureHashHex)) { COSArray savedCorrespondingOCSPs = correspondingOCSPs; COSArray savedCorrespondingCRLs = correspondingCRLs; COSDictionary vri = new COSDictionary(); vriBase.setItem(signatureHashHex, vri); CertSignatureInformation crlCertInfo; try { crlCertInfo = certInformationHelper.getCertInfo(issuerCertificate); } catch (CertificateProccessingException ex) { throw new CertificateVerificationException(ex.getMessage(), ex); } updateVRI(crlCertInfo, vri); correspondingOCSPs = savedCorrespondingOCSPs; correspondingCRLs = savedCorrespondingCRLs; } } foundRevocationInformation.add(certInfo.getCertificate()); } private void updateVRI(CertSignatureInformation certInfo, COSDictionary vri) throws IOException { if (certInfo.getCertificate().getExtensionValue(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId()) == null) { correspondingOCSPs = new COSArray(); correspondingCRLs = new COSArray(); addRevocationDataRecursive(certInfo); if (correspondingOCSPs.size() > 0) { vri.setItem("OCSP", correspondingOCSPs); } if (correspondingCRLs.size() > 0) { vri.setItem("CRL", correspondingCRLs); } } COSArray correspondingCerts = new COSArray(); CertSignatureInformation ci = certInfo; do { X509Certificate cert = ci.getCertificate(); try { COSStream certStream = writeDataToStream(cert.getEncoded()); correspondingCerts.add(certStream); certs.add(certStream); // may lead to duplicate certificates. Important? } catch (CertificateEncodingException ex) { // should not happen because these are existing certificates LOG.error(ex, ex); } if (cert.getExtensionValue(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId()) != null) { break; } ci = ci.getCertChain(); } while (ci != null); vri.setItem(COSName.CERT, correspondingCerts); vri.setDate(COSName.TU, Calendar.getInstance()); } /** * Adds all certs to the certs-array. Make sure, all certificates are inside the * certificateStore of certInformationHelper * * @throws IOException */ private void addAllCertsToCertArray() throws IOException { try { for (X509Certificate cert : certInformationHelper.getCertificateSet()) { COSStream stream = writeDataToStream(cert.getEncoded()); certs.add(stream); } } catch (CertificateEncodingException e) { throw new IOException(e); } } /** * Creates a Flate encoded <code>COSStream</code> object with the given data. * * @param data to write into the COSStream * @return COSStream a COSStream object that can be added to the document * @throws IOException */ private COSStream writeDataToStream(byte[] data) throws IOException { COSStream stream = document.getDocument().createCOSStream(); try (OutputStream os = stream.createOutputStream(COSName.FLATE_DECODE)) { os.write(data); } return stream; } /** * Adds Extensions to the document catalog. So that the use of DSS is identified. Described in * PAdES Part 4, Chapter 4.4. * * @param catalog to add Extensions into */ private void addExtensions(PDDocumentCatalog catalog) { COSDictionary dssExtensions = new COSDictionary(); dssExtensions.setDirect(true); catalog.getCOSObject().setItem("Extensions", dssExtensions); COSDictionary adbeExtension = new COSDictionary(); adbeExtension.setDirect(true); dssExtensions.setItem("ADBE", adbeExtension); adbeExtension.setName("BaseVersion", "1.7"); adbeExtension.setInt("ExtensionLevel", 5); catalog.setVersion("1.7"); } public static void main(String[] args) throws IOException { if (args.length != 1) { usage(); System.exit(1); } // register BouncyCastle provider, needed for "exotic" algorithms Security.addProvider(SecurityProvider.getProvider()); // add ocspInformation AddValidationInformation addOcspInformation = new AddValidationInformation(); File inFile = new File(args[0]); String name = inFile.getName(); String substring = name.substring(0, name.lastIndexOf('.')); File outFile = new File(inFile.getParent(), substring + "_LTV.pdf"); addOcspInformation.validateSignature(inFile, outFile); } private static void usage() { System.err.println("usage: java " + AddValidationInformation.class.getName() + " " + "<pdf_to_add_ocsp>\n"); } }
examples/src/main/java/org/apache/pdfbox/examples/signature/validation/AddValidationInformation.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.pdfbox.examples.signature.validation; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.Security; import java.security.cert.CertificateEncodingException; import java.security.cert.X509CRL; import java.security.cert.X509Certificate; import java.util.Calendar; import java.util.HashSet; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.pdfbox.Loader; import org.apache.pdfbox.cos.COSArray; import org.apache.pdfbox.cos.COSBase; import org.apache.pdfbox.cos.COSDictionary; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.cos.COSStream; import org.apache.pdfbox.cos.COSUpdateInfo; import org.apache.pdfbox.examples.signature.SigUtils; import org.apache.pdfbox.examples.signature.cert.CRLVerifier; import org.apache.pdfbox.examples.signature.cert.CertificateVerificationException; import org.apache.pdfbox.examples.signature.cert.OcspHelper; import org.apache.pdfbox.examples.signature.cert.RevokedCertificateException; import org.apache.pdfbox.examples.signature.validation.CertInformationCollector.CertSignatureInformation; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDDocumentCatalog; import org.apache.pdfbox.pdmodel.encryption.SecurityProvider; import org.apache.pdfbox.pdmodel.interactive.digitalsignature.PDSignature; import org.apache.pdfbox.util.Hex; import org.bouncycastle.asn1.BEROctetString; import org.bouncycastle.asn1.ocsp.OCSPObjectIdentifiers; import org.bouncycastle.cert.ocsp.BasicOCSPResp; import org.bouncycastle.cert.ocsp.OCSPException; import org.bouncycastle.cert.ocsp.OCSPResp; import org.bouncycastle.cms.CMSException; import org.bouncycastle.cms.CMSSignedData; import org.bouncycastle.tsp.TSPException; import org.bouncycastle.tsp.TimeStampToken; import org.bouncycastle.tsp.TimeStampTokenInfo; /** * An example for adding Validation Information to a signed PDF, inspired by ETSI TS 102 778-4 * V1.1.2 (2009-12), Part 4: PAdES Long Term - PAdES-LTV Profile. This procedure appends the * Validation Information of the last signature (more precise its signer(s)) to a copy of the * document. The signature and the signed data will not be touched and stay valid. * <p> * See also <a href="http://eprints.hsr.ch/id/eprint/616">Bachelor thesis (in German) about LTV</a> * * @author Alexis Suter */ public class AddValidationInformation { private static final Log LOG = LogFactory.getLog(AddValidationInformation.class); private CertInformationCollector certInformationHelper; private COSArray correspondingOCSPs; private COSArray correspondingCRLs; private COSDictionary vriBase; private COSArray ocsps; private COSArray crls; private COSArray certs; private PDDocument document; private final Set<X509Certificate> foundRevocationInformation = new HashSet<>(); private Calendar signDate; private final Set<X509Certificate> ocspChecked = new HashSet<>(); //TODO foundRevocationInformation and ocspChecked have a similar purpose. One of them should likely // be removed and the code improved. When doing so, keep in mind that ocspChecked was added last, // because of a problem with freetsa. /** * Signs the given PDF file. * * @param inFile input PDF file * @param outFile output PDF file * @throws IOException if the input file could not be read */ public void validateSignature(File inFile, File outFile) throws IOException { if (inFile == null || !inFile.exists()) { String err = "Document for signing "; if (null == inFile) { err += "is null"; } else { err += "does not exist: " + inFile.getAbsolutePath(); } throw new FileNotFoundException(err); } try (PDDocument doc = Loader.loadPDF(inFile); FileOutputStream fos = new FileOutputStream(outFile)) { int accessPermissions = SigUtils.getMDPPermission(doc); if (accessPermissions == 1) { System.out.println("PDF is certified to forbid changes, " + "some readers may report the document as invalid despite that " + "the PDF specification allows DSS additions"); } document = doc; doValidation(inFile.getAbsolutePath(), fos); } } /** * Fetches certificate information from the last signature of the document and appends a DSS * with the validation information to the document. * * @param filename in file to extract signature * @param output where to write the changed document * @throws IOException */ private void doValidation(String filename, OutputStream output) throws IOException { certInformationHelper = new CertInformationCollector(); CertSignatureInformation certInfo = null; try { PDSignature signature = SigUtils.getLastRelevantSignature(document); if (signature != null) { certInfo = certInformationHelper.getLastCertInfo(signature, filename); signDate = signature.getSignDate(); if ("ETSI.RFC3161".equals(signature.getSubFilter())) { byte[] contents = signature.getContents(); TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(contents)); TimeStampTokenInfo timeStampInfo = timeStampToken.getTimeStampInfo(); signDate = Calendar.getInstance(); signDate.setTime(timeStampInfo.getGenTime()); } } } catch (TSPException | CMSException | CertificateProccessingException e) { throw new IOException("An Error occurred processing the Signature", e); } if (certInfo == null) { throw new IOException( "No Certificate information or signature found in the given document"); } PDDocumentCatalog docCatalog = document.getDocumentCatalog(); COSDictionary catalog = docCatalog.getCOSObject(); catalog.setNeedToBeUpdated(true); COSDictionary dss = getOrCreateDictionaryEntry(COSDictionary.class, catalog, "DSS"); addExtensions(docCatalog); vriBase = getOrCreateDictionaryEntry(COSDictionary.class, dss, "VRI"); ocsps = getOrCreateDictionaryEntry(COSArray.class, dss, "OCSPs"); crls = getOrCreateDictionaryEntry(COSArray.class, dss, "CRLs"); certs = getOrCreateDictionaryEntry(COSArray.class, dss, "Certs"); addRevocationData(certInfo); addAllCertsToCertArray(); // write incremental document.saveIncremental(output); } /** * Gets or creates a dictionary entry. If existing checks for the type and sets need to be * updated. * * @param clazz the class of the dictionary entry, must implement COSUpdateInfo * @param parent where to find the element * @param name of the element * @return a Element of given class, new or existing * @throws IOException when the type of the element is wrong */ private static <T extends COSBase & COSUpdateInfo> T getOrCreateDictionaryEntry(Class<T> clazz, COSDictionary parent, String name) throws IOException { T result; COSBase element = parent.getDictionaryObject(name); if (element != null && clazz.isInstance(element)) { result = clazz.cast(element); result.setNeedToBeUpdated(true); } else if (element != null) { throw new IOException("Element " + name + " from dictionary is not of type " + clazz.getCanonicalName()); } else { try { result = clazz.getDeclaredConstructor().newInstance(); } catch (ReflectiveOperationException | SecurityException e) { throw new IOException("Failed to create new instance of " + clazz.getCanonicalName(), e); } result.setDirect(false); parent.setItem(COSName.getPDFName(name), result); } return result; } /** * Fetches and adds revocation information based on the certInfo to the DSS. * * @param certInfo Certificate information from CertInformationHelper containing certificate * chains. * @throws IOException */ private void addRevocationData(CertSignatureInformation certInfo) throws IOException { COSDictionary vri = new COSDictionary(); vriBase.setItem(certInfo.getSignatureHash(), vri); updateVRI(certInfo, vri); if (certInfo.getTsaCerts() != null) { // Don't add RevocationInfo from tsa to VRI's correspondingOCSPs = null; correspondingCRLs = null; addRevocationDataRecursive(certInfo.getTsaCerts()); } } /** * Tries to get Revocation Data (first OCSP, else CRL) from the given Certificate Chain. * * @param certInfo from which to fetch revocation data. Will work recursively through its * chains. * @throws IOException when failed to fetch an revocation data. */ private void addRevocationDataRecursive(CertSignatureInformation certInfo) throws IOException { if (certInfo.isSelfSigned()) { return; } // To avoid getting same revocation information twice. boolean isRevocationInfoFound = foundRevocationInformation.contains(certInfo.getCertificate()); if (!isRevocationInfoFound) { if (certInfo.getOcspUrl() != null && certInfo.getIssuerCertificate() != null) { isRevocationInfoFound = fetchOcspData(certInfo); } if (!isRevocationInfoFound && certInfo.getCrlUrl() != null) { fetchCrlData(certInfo); isRevocationInfoFound = true; } if (certInfo.getOcspUrl() == null && certInfo.getCrlUrl() == null) { LOG.info("No revocation information for cert " + certInfo.getCertificate().getSubjectX500Principal()); } else if (!isRevocationInfoFound) { throw new IOException("Could not fetch Revocation Info for Cert: " + certInfo.getCertificate().getSubjectX500Principal()); } } if (certInfo.getAlternativeCertChain() != null) { addRevocationDataRecursive(certInfo.getAlternativeCertChain()); } if (certInfo.getCertChain() != null && certInfo.getCertChain().getCertificate() != null) { addRevocationDataRecursive(certInfo.getCertChain()); } } /** * Tries to fetch and add OCSP Data to its containers. * * @param certInfo the certificate info, for it to check OCSP data. * @return true when the OCSP data has successfully been fetched and added * @throws IOException when Certificate is revoked. */ private boolean fetchOcspData(CertSignatureInformation certInfo) throws IOException { try { addOcspData(certInfo); return true; } catch (OCSPException | CertificateProccessingException | IOException e) { LOG.error("Failed fetching OCSP at " + certInfo.getOcspUrl(), e); return false; } catch (RevokedCertificateException e) { throw new IOException(e); } } /** * Tries to fetch and add CRL Data to its containers. * * @param certInfo the certificate info, for it to check CRL data. * @throws IOException when failed to fetch, because no validation data could be fetched for * data. */ private void fetchCrlData(CertSignatureInformation certInfo) throws IOException { try { addCrlRevocationInfo(certInfo); } catch (GeneralSecurityException | IOException | RevokedCertificateException | CertificateVerificationException e) { LOG.warn("Failed fetching CRL", e); throw new IOException(e); } } /** * Fetches and adds OCSP data to storage for the given Certificate. * * @param certInfo the certificate info, for it to check OCSP data. * @throws IOException * @throws OCSPException * @throws CertificateProccessingException * @throws RevokedCertificateException */ private void addOcspData(CertSignatureInformation certInfo) throws IOException, OCSPException, CertificateProccessingException, RevokedCertificateException { if (ocspChecked.contains(certInfo.getCertificate())) { // This certificate has been OCSP-checked before return; } OcspHelper ocspHelper = new OcspHelper( certInfo.getCertificate(), signDate.getTime(), certInfo.getIssuerCertificate(), new HashSet<>(certInformationHelper.getCertificateSet()), certInfo.getOcspUrl()); OCSPResp ocspResp = ocspHelper.getResponseOcsp(); ocspChecked.add(certInfo.getCertificate()); BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResp.getResponseObject(); X509Certificate ocspResponderCertificate = ocspHelper.getOcspResponderCertificate(); certInformationHelper.addAllCertsFromHolders(basicResponse.getCerts()); byte[] signatureHash; try { // https://www.etsi.org/deliver/etsi_ts/102700_102799/10277804/01.01.02_60/ts_10277804v010102p.pdf // "For the signatures of the CRL and OCSP response, it is the respective signature // object represented as a BER-encoded OCTET STRING encoded with primitive encoding" @SuppressWarnings("java:S4790") BEROctetString encodedSignature = new BEROctetString(basicResponse.getSignature()); signatureHash = MessageDigest.getInstance("SHA-1").digest(encodedSignature.getEncoded()); } catch (NoSuchAlgorithmException ex) { throw new CertificateProccessingException(ex); } String signatureHashHex = Hex.getString(signatureHash); if (!vriBase.containsKey(signatureHashHex)) { COSArray savedCorrespondingOCSPs = correspondingOCSPs; COSArray savedCorrespondingCRLs = correspondingCRLs; COSDictionary vri = new COSDictionary(); vriBase.setItem(signatureHashHex, vri); CertSignatureInformation ocspCertInfo = certInformationHelper.getCertInfo(ocspResponderCertificate); updateVRI(ocspCertInfo, vri); correspondingOCSPs = savedCorrespondingOCSPs; correspondingCRLs = savedCorrespondingCRLs; } byte[] ocspData = ocspResp.getEncoded(); COSStream ocspStream = writeDataToStream(ocspData); ocsps.add(ocspStream); if (correspondingOCSPs != null) { correspondingOCSPs.add(ocspStream); } foundRevocationInformation.add(certInfo.getCertificate()); } /** * Fetches and adds CRL data to storage for the given Certificate. * * @param certInfo the certificate info, for it to check CRL data. * @throws IOException * @throws RevokedCertificateException * @throws GeneralSecurityException * @throws CertificateVerificationException */ private void addCrlRevocationInfo(CertSignatureInformation certInfo) throws IOException, RevokedCertificateException, GeneralSecurityException, CertificateVerificationException { X509CRL crl = CRLVerifier.downloadCRLFromWeb(certInfo.getCrlUrl()); X509Certificate issuerCertificate = certInfo.getIssuerCertificate(); // find the issuer certificate (usually issuer of signature certificate) for (X509Certificate certificate : certInformationHelper.getCertificateSet()) { if (certificate.getSubjectX500Principal().equals(crl.getIssuerX500Principal())) { issuerCertificate = certificate; break; } } crl.verify(issuerCertificate.getPublicKey(), SecurityProvider.getProvider().getName()); CRLVerifier.checkRevocation(crl, certInfo.getCertificate(), signDate.getTime(), certInfo.getCrlUrl()); COSStream crlStream = writeDataToStream(crl.getEncoded()); crls.add(crlStream); if (correspondingCRLs != null) { correspondingCRLs.add(crlStream); byte[] signatureHash; try { // https://www.etsi.org/deliver/etsi_ts/102700_102799/10277804/01.01.02_60/ts_10277804v010102p.pdf // "For the signatures of the CRL and OCSP response, it is the respective signature // object represented as a BER-encoded OCTET STRING encoded with primitive encoding" @SuppressWarnings("java:S4790") BEROctetString berEncodedSignature = new BEROctetString(crl.getSignature()); signatureHash = MessageDigest.getInstance("SHA-1").digest(berEncodedSignature.getEncoded()); } catch (NoSuchAlgorithmException ex) { throw new CertificateVerificationException(ex.getMessage(), ex); } String signatureHashHex = Hex.getString(signatureHash); if (!vriBase.containsKey(signatureHashHex)) { COSArray savedCorrespondingOCSPs = correspondingOCSPs; COSArray savedCorrespondingCRLs = correspondingCRLs; COSDictionary vri = new COSDictionary(); vriBase.setItem(signatureHashHex, vri); CertSignatureInformation crlCertInfo; try { crlCertInfo = certInformationHelper.getCertInfo(issuerCertificate); } catch (CertificateProccessingException ex) { throw new CertificateVerificationException(ex.getMessage(), ex); } updateVRI(crlCertInfo, vri); correspondingOCSPs = savedCorrespondingOCSPs; correspondingCRLs = savedCorrespondingCRLs; } } foundRevocationInformation.add(certInfo.getCertificate()); } private void updateVRI(CertSignatureInformation certInfo, COSDictionary vri) throws IOException { if (certInfo.getCertificate().getExtensionValue(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId()) == null) { correspondingOCSPs = new COSArray(); correspondingCRLs = new COSArray(); addRevocationDataRecursive(certInfo); if (correspondingOCSPs.size() > 0) { vri.setItem("OCSP", correspondingOCSPs); } if (correspondingCRLs.size() > 0) { vri.setItem("CRL", correspondingCRLs); } } COSArray correspondingCerts = new COSArray(); CertSignatureInformation ci = certInfo; do { X509Certificate cert = ci.getCertificate(); try { COSStream certStream = writeDataToStream(cert.getEncoded()); correspondingCerts.add(certStream); certs.add(certStream); // may lead to duplicate certificates. Important? } catch (CertificateEncodingException ex) { // should not happen because these are existing certificates LOG.error(ex, ex); } if (cert.getExtensionValue(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId()) != null) { break; } ci = ci.getCertChain(); } while (ci != null); vri.setItem(COSName.CERT, correspondingCerts); vri.setDate(COSName.TU, Calendar.getInstance()); } /** * Adds all certs to the certs-array. Make sure, all certificates are inside the * certificateStore of certInformationHelper * * @throws IOException */ private void addAllCertsToCertArray() throws IOException { try { for (X509Certificate cert : certInformationHelper.getCertificateSet()) { COSStream stream = writeDataToStream(cert.getEncoded()); certs.add(stream); } } catch (CertificateEncodingException e) { throw new IOException(e); } } /** * Creates a Flate encoded <code>COSStream</code> object with the given data. * * @param data to write into the COSStream * @return COSStream a COSStream object that can be added to the document * @throws IOException */ private COSStream writeDataToStream(byte[] data) throws IOException { COSStream stream = document.getDocument().createCOSStream(); try (OutputStream os = stream.createOutputStream(COSName.FLATE_DECODE)) { os.write(data); } return stream; } /** * Adds Extensions to the document catalog. So that the use of DSS is identified. Described in * PAdES Part 4, Chapter 4.4. * * @param catalog to add Extensions into */ private void addExtensions(PDDocumentCatalog catalog) { COSDictionary dssExtensions = new COSDictionary(); dssExtensions.setDirect(true); catalog.getCOSObject().setItem("Extensions", dssExtensions); COSDictionary adbeExtension = new COSDictionary(); adbeExtension.setDirect(true); dssExtensions.setItem("ADBE", adbeExtension); adbeExtension.setName("BaseVersion", "1.7"); adbeExtension.setInt("ExtensionLevel", 5); catalog.setVersion("1.7"); } public static void main(String[] args) throws IOException { if (args.length != 1) { usage(); System.exit(1); } // register BouncyCastle provider, needed for "exotic" algorithms Security.addProvider(SecurityProvider.getProvider()); // add ocspInformation AddValidationInformation addOcspInformation = new AddValidationInformation(); File inFile = new File(args[0]); String name = inFile.getName(); String substring = name.substring(0, name.lastIndexOf('.')); File outFile = new File(inFile.getParent(), substring + "_LTV.pdf"); addOcspInformation.validateSignature(inFile, outFile); } private static void usage() { System.err.println("usage: java " + AddValidationInformation.class.getName() + " " + "<pdf_to_add_ocsp>\n"); } }
PDFBOX-5385: revert Sonar fix, has no effect; security hotspot has now been marked as reviewed on the website instead git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1898857 13f79535-47bb-0310-9956-ffa450edef68
examples/src/main/java/org/apache/pdfbox/examples/signature/validation/AddValidationInformation.java
PDFBOX-5385: revert Sonar fix, has no effect; security hotspot has now been marked as reviewed on the website instead
<ide><path>xamples/src/main/java/org/apache/pdfbox/examples/signature/validation/AddValidationInformation.java <ide> // https://www.etsi.org/deliver/etsi_ts/102700_102799/10277804/01.01.02_60/ts_10277804v010102p.pdf <ide> // "For the signatures of the CRL and OCSP response, it is the respective signature <ide> // object represented as a BER-encoded OCTET STRING encoded with primitive encoding" <del> @SuppressWarnings("java:S4790") <ide> BEROctetString encodedSignature = new BEROctetString(basicResponse.getSignature()); <ide> signatureHash = MessageDigest.getInstance("SHA-1").digest(encodedSignature.getEncoded()); <ide> } <ide> // https://www.etsi.org/deliver/etsi_ts/102700_102799/10277804/01.01.02_60/ts_10277804v010102p.pdf <ide> // "For the signatures of the CRL and OCSP response, it is the respective signature <ide> // object represented as a BER-encoded OCTET STRING encoded with primitive encoding" <del> @SuppressWarnings("java:S4790") <ide> BEROctetString berEncodedSignature = new BEROctetString(crl.getSignature()); <ide> signatureHash = MessageDigest.getInstance("SHA-1").digest(berEncodedSignature.getEncoded()); <ide> }
Java
apache-2.0
70f88d0f8f264c56307b5dff8757a5b8876f3d00
0
tdiesler/camel,nikvaessen/camel,CandleCandle/camel,nboukhed/camel,koscejev/camel,josefkarasek/camel,jameszkw/camel,ge0ffrey/camel,aaronwalker/camel,grgrzybek/camel,veithen/camel,ssharma/camel,tdiesler/camel,haku/camel,joakibj/camel,mnki/camel,manuelh9r/camel,YMartsynkevych/camel,MohammedHammam/camel,snadakuduru/camel,chanakaudaya/camel,sebi-hgdata/camel,neoramon/camel,zregvart/camel,jmandawg/camel,engagepoint/camel,mohanaraosv/camel,salikjan/camel,NickCis/camel,nikvaessen/camel,davidkarlsen/camel,adessaigne/camel,logzio/camel,edigrid/camel,duro1/camel,CandleCandle/camel,mike-kukla/camel,dvankleef/camel,satishgummadelli/camel,igarashitm/camel,jameszkw/camel,stravag/camel,YMartsynkevych/camel,FingolfinTEK/camel,koscejev/camel,yuruki/camel,ekprayas/camel,stravag/camel,manuelh9r/camel,edigrid/camel,dkhanolkar/camel,pplatek/camel,adessaigne/camel,oscerd/camel,curso007/camel,bdecoste/camel,isavin/camel,joakibj/camel,curso007/camel,CodeSmell/camel,jonmcewen/camel,MrCoder/camel,duro1/camel,jarst/camel,gilfernandes/camel,trohovsky/camel,ramonmaruko/camel,jpav/camel,mike-kukla/camel,qst-jdc-labs/camel,partis/camel,RohanHart/camel,anton-k11/camel,Thopap/camel,oscerd/camel,ge0ffrey/camel,stalet/camel,yuruki/camel,davidwilliams1978/camel,atoulme/camel,edigrid/camel,josefkarasek/camel,lowwool/camel,jameszkw/camel,tarilabs/camel,YMartsynkevych/camel,lburgazzoli/apache-camel,punkhorn/camel-upstream,lasombra/camel,mnki/camel,JYBESSON/camel,qst-jdc-labs/camel,johnpoth/camel,stravag/camel,scranton/camel,neoramon/camel,pax95/camel,Fabryprog/camel,yogamaha/camel,tdiesler/camel,snurmine/camel,driseley/camel,lowwool/camel,hqstevenson/camel,neoramon/camel,grange74/camel,NetNow/camel,yuruki/camel,bhaveshdt/camel,mzapletal/camel,isururanawaka/camel,adessaigne/camel,tadayosi/camel,erwelch/camel,eformat/camel,bdecoste/camel,rmarting/camel,ssharma/camel,NickCis/camel,veithen/camel,pmoerenhout/camel,punkhorn/camel-upstream,jlpedrosa/camel,onders86/camel,snadakuduru/camel,christophd/camel,bgaudaen/camel,anoordover/camel,sebi-hgdata/camel,grgrzybek/camel,lowwool/camel,apache/camel,alvinkwekel/camel,lburgazzoli/camel,yogamaha/camel,tkopczynski/camel,ullgren/camel,erwelch/camel,bgaudaen/camel,prashant2402/camel,isavin/camel,sabre1041/camel,johnpoth/camel,lburgazzoli/apache-camel,dsimansk/camel,tlehoux/camel,igarashitm/camel,isavin/camel,borcsokj/camel,gautric/camel,johnpoth/camel,haku/camel,bhaveshdt/camel,coderczp/camel,qst-jdc-labs/camel,sirlatrom/camel,bdecoste/camel,chirino/camel,jmandawg/camel,coderczp/camel,bfitzpat/camel,onders86/camel,tdiesler/camel,chirino/camel,logzio/camel,nikhilvibhav/camel,yogamaha/camel,cunningt/camel,jameszkw/camel,mcollovati/camel,NickCis/camel,lburgazzoli/apache-camel,skinzer/camel,veithen/camel,chanakaudaya/camel,pkletsko/camel,maschmid/camel,grange74/camel,jmandawg/camel,tarilabs/camel,borcsokj/camel,onders86/camel,sebi-hgdata/camel,gautric/camel,MrCoder/camel,trohovsky/camel,satishgummadelli/camel,atoulme/camel,ssharma/camel,iweiss/camel,kevinearls/camel,borcsokj/camel,chirino/camel,akhettar/camel,bhaveshdt/camel,sabre1041/camel,gyc567/camel,anton-k11/camel,igarashitm/camel,brreitme/camel,tkopczynski/camel,MohammedHammam/camel,acartapanis/camel,jollygeorge/camel,sebi-hgdata/camel,stravag/camel,koscejev/camel,nikvaessen/camel,noelo/camel,dkhanolkar/camel,YoshikiHigo/camel,scranton/camel,sebi-hgdata/camel,noelo/camel,stalet/camel,koscejev/camel,jollygeorge/camel,RohanHart/camel,dmvolod/camel,dsimansk/camel,mohanaraosv/camel,bgaudaen/camel,sverkera/camel,lowwool/camel,maschmid/camel,ekprayas/camel,askannon/camel,yury-vashchyla/camel,aaronwalker/camel,tkopczynski/camel,sirlatrom/camel,w4tson/camel,FingolfinTEK/camel,mcollovati/camel,tadayosi/camel,zregvart/camel,scranton/camel,joakibj/camel,pkletsko/camel,w4tson/camel,oalles/camel,logzio/camel,gautric/camel,rparree/camel,akhettar/camel,davidkarlsen/camel,isururanawaka/camel,pmoerenhout/camel,kevinearls/camel,curso007/camel,atoulme/camel,erwelch/camel,prashant2402/camel,joakibj/camel,apache/camel,ekprayas/camel,woj-i/camel,skinzer/camel,jkorab/camel,jamesnetherton/camel,rmarting/camel,sabre1041/camel,MohammedHammam/camel,gilfernandes/camel,rmarting/camel,edigrid/camel,iweiss/camel,pmoerenhout/camel,salikjan/camel,jollygeorge/camel,hqstevenson/camel,stravag/camel,maschmid/camel,davidwilliams1978/camel,brreitme/camel,anton-k11/camel,bfitzpat/camel,dmvolod/camel,mgyongyosi/camel,borcsokj/camel,maschmid/camel,dvankleef/camel,satishgummadelli/camel,oscerd/camel,snurmine/camel,anoordover/camel,tlehoux/camel,gyc567/camel,dpocock/camel,veithen/camel,dpocock/camel,snadakuduru/camel,oscerd/camel,w4tson/camel,royopa/camel,YoshikiHigo/camel,stalet/camel,royopa/camel,YoshikiHigo/camel,qst-jdc-labs/camel,iweiss/camel,NetNow/camel,jarst/camel,dkhanolkar/camel,dvankleef/camel,duro1/camel,lburgazzoli/apache-camel,RohanHart/camel,pmoerenhout/camel,aaronwalker/camel,duro1/camel,jamesnetherton/camel,dvankleef/camel,allancth/camel,royopa/camel,erwelch/camel,chirino/camel,jonmcewen/camel,brreitme/camel,mnki/camel,igarashitm/camel,isavin/camel,jonmcewen/camel,prashant2402/camel,skinzer/camel,mnki/camel,jonmcewen/camel,stalet/camel,mnki/camel,Thopap/camel,joakibj/camel,grgrzybek/camel,acartapanis/camel,ge0ffrey/camel,YoshikiHigo/camel,davidwilliams1978/camel,bhaveshdt/camel,jlpedrosa/camel,onders86/camel,snadakuduru/camel,ramonmaruko/camel,MrCoder/camel,lburgazzoli/camel,royopa/camel,jarst/camel,CandleCandle/camel,igarashitm/camel,duro1/camel,yuruki/camel,pplatek/camel,borcsokj/camel,veithen/camel,Thopap/camel,chirino/camel,allancth/camel,dkhanolkar/camel,prashant2402/camel,mcollovati/camel,apache/camel,jamesnetherton/camel,driseley/camel,prashant2402/camel,mzapletal/camel,gilfernandes/camel,driseley/camel,manuelh9r/camel,anoordover/camel,isavin/camel,rmarting/camel,aaronwalker/camel,ssharma/camel,acartapanis/camel,CodeSmell/camel,tlehoux/camel,christophd/camel,pplatek/camel,jkorab/camel,pkletsko/camel,driseley/camel,askannon/camel,rparree/camel,ramonmaruko/camel,w4tson/camel,mnki/camel,noelo/camel,tarilabs/camel,jmandawg/camel,davidwilliams1978/camel,onders86/camel,drsquidop/camel,sirlatrom/camel,bfitzpat/camel,w4tson/camel,maschmid/camel,ge0ffrey/camel,ekprayas/camel,brreitme/camel,partis/camel,jlpedrosa/camel,mohanaraosv/camel,woj-i/camel,tdiesler/camel,bdecoste/camel,NickCis/camel,haku/camel,brreitme/camel,mohanaraosv/camel,skinzer/camel,w4tson/camel,rmarting/camel,YMartsynkevych/camel,gnodet/camel,brreitme/camel,rmarting/camel,dsimansk/camel,qst-jdc-labs/camel,christophd/camel,johnpoth/camel,NetNow/camel,kevinearls/camel,bdecoste/camel,bgaudaen/camel,koscejev/camel,christophd/camel,neoramon/camel,woj-i/camel,grange74/camel,rparree/camel,yury-vashchyla/camel,trohovsky/camel,davidkarlsen/camel,MrCoder/camel,mike-kukla/camel,askannon/camel,partis/camel,eformat/camel,CodeSmell/camel,jpav/camel,kevinearls/camel,logzio/camel,lburgazzoli/camel,jpav/camel,ullgren/camel,lburgazzoli/apache-camel,cunningt/camel,woj-i/camel,eformat/camel,scranton/camel,FingolfinTEK/camel,bhaveshdt/camel,dkhanolkar/camel,davidwilliams1978/camel,hqstevenson/camel,josefkarasek/camel,logzio/camel,tkopczynski/camel,coderczp/camel,bhaveshdt/camel,nboukhed/camel,davidkarlsen/camel,anoordover/camel,scranton/camel,dmvolod/camel,gilfernandes/camel,pax95/camel,jmandawg/camel,Thopap/camel,JYBESSON/camel,maschmid/camel,josefkarasek/camel,koscejev/camel,neoramon/camel,manuelh9r/camel,josefkarasek/camel,sverkera/camel,atoulme/camel,Fabryprog/camel,woj-i/camel,neoramon/camel,bdecoste/camel,tkopczynski/camel,mike-kukla/camel,sirlatrom/camel,chanakaudaya/camel,nicolaferraro/camel,partis/camel,grgrzybek/camel,akhettar/camel,ge0ffrey/camel,josefkarasek/camel,jarst/camel,bfitzpat/camel,bfitzpat/camel,manuelh9r/camel,gyc567/camel,acartapanis/camel,arnaud-deprez/camel,engagepoint/camel,adessaigne/camel,anton-k11/camel,JYBESSON/camel,oscerd/camel,iweiss/camel,yogamaha/camel,sverkera/camel,arnaud-deprez/camel,stalet/camel,tdiesler/camel,jameszkw/camel,mcollovati/camel,oalles/camel,mgyongyosi/camel,oalles/camel,JYBESSON/camel,gnodet/camel,mohanaraosv/camel,drsquidop/camel,eformat/camel,tarilabs/camel,grange74/camel,ramonmaruko/camel,lburgazzoli/camel,arnaud-deprez/camel,mgyongyosi/camel,yury-vashchyla/camel,mzapletal/camel,mzapletal/camel,hqstevenson/camel,isururanawaka/camel,allancth/camel,chanakaudaya/camel,ullgren/camel,alvinkwekel/camel,isururanawaka/camel,hqstevenson/camel,Thopap/camel,sirlatrom/camel,sebi-hgdata/camel,ramonmaruko/camel,gyc567/camel,dpocock/camel,sverkera/camel,RohanHart/camel,logzio/camel,yury-vashchyla/camel,lasombra/camel,partis/camel,nikhilvibhav/camel,CandleCandle/camel,dkhanolkar/camel,pmoerenhout/camel,DariusX/camel,lasombra/camel,jameszkw/camel,curso007/camel,rparree/camel,tadayosi/camel,cunningt/camel,pmoerenhout/camel,DariusX/camel,grange74/camel,punkhorn/camel-upstream,joakibj/camel,hqstevenson/camel,sverkera/camel,nboukhed/camel,sirlatrom/camel,ramonmaruko/camel,jkorab/camel,chanakaudaya/camel,CodeSmell/camel,lowwool/camel,atoulme/camel,kevinearls/camel,snadakuduru/camel,nboukhed/camel,ekprayas/camel,gautric/camel,aaronwalker/camel,jollygeorge/camel,mohanaraosv/camel,NetNow/camel,bgaudaen/camel,coderczp/camel,NickCis/camel,tarilabs/camel,oalles/camel,gnodet/camel,pax95/camel,skinzer/camel,jollygeorge/camel,curso007/camel,mike-kukla/camel,tadayosi/camel,lasombra/camel,zregvart/camel,nboukhed/camel,akhettar/camel,FingolfinTEK/camel,jpav/camel,stravag/camel,driseley/camel,jamesnetherton/camel,noelo/camel,jonmcewen/camel,tkopczynski/camel,mgyongyosi/camel,gautric/camel,lburgazzoli/apache-camel,adessaigne/camel,johnpoth/camel,DariusX/camel,dpocock/camel,gyc567/camel,kevinearls/camel,mzapletal/camel,tadayosi/camel,dmvolod/camel,nikhilvibhav/camel,pplatek/camel,satishgummadelli/camel,jlpedrosa/camel,anoordover/camel,mzapletal/camel,nikvaessen/camel,skinzer/camel,drsquidop/camel,DariusX/camel,haku/camel,iweiss/camel,ullgren/camel,JYBESSON/camel,akhettar/camel,objectiser/camel,eformat/camel,manuelh9r/camel,tlehoux/camel,oalles/camel,coderczp/camel,pkletsko/camel,MohammedHammam/camel,RohanHart/camel,pax95/camel,lowwool/camel,acartapanis/camel,MrCoder/camel,apache/camel,lburgazzoli/camel,pax95/camel,gilfernandes/camel,RohanHart/camel,pplatek/camel,rparree/camel,jarst/camel,jpav/camel,Fabryprog/camel,nikvaessen/camel,aaronwalker/camel,YoshikiHigo/camel,jkorab/camel,FingolfinTEK/camel,allancth/camel,pplatek/camel,cunningt/camel,alvinkwekel/camel,dvankleef/camel,borcsokj/camel,onders86/camel,objectiser/camel,edigrid/camel,partis/camel,jkorab/camel,akhettar/camel,snurmine/camel,veithen/camel,jonmcewen/camel,arnaud-deprez/camel,snurmine/camel,tlehoux/camel,grgrzybek/camel,dmvolod/camel,allancth/camel,grange74/camel,arnaud-deprez/camel,JYBESSON/camel,jlpedrosa/camel,pkletsko/camel,adessaigne/camel,isavin/camel,duro1/camel,YoshikiHigo/camel,nicolaferraro/camel,lburgazzoli/camel,nboukhed/camel,tarilabs/camel,edigrid/camel,NetNow/camel,bgaudaen/camel,anoordover/camel,arnaud-deprez/camel,haku/camel,rparree/camel,ekprayas/camel,johnpoth/camel,dmvolod/camel,trohovsky/camel,NickCis/camel,jamesnetherton/camel,tlehoux/camel,isururanawaka/camel,snadakuduru/camel,ssharma/camel,gnodet/camel,NetNow/camel,pkletsko/camel,gautric/camel,lasombra/camel,oscerd/camel,dsimansk/camel,bfitzpat/camel,noelo/camel,FingolfinTEK/camel,trohovsky/camel,qst-jdc-labs/camel,CandleCandle/camel,royopa/camel,mgyongyosi/camel,erwelch/camel,Thopap/camel,chirino/camel,noelo/camel,curso007/camel,acartapanis/camel,jollygeorge/camel,sverkera/camel,satishgummadelli/camel,yogamaha/camel,allancth/camel,yury-vashchyla/camel,objectiser/camel,pax95/camel,engagepoint/camel,dpocock/camel,isururanawaka/camel,logzio/camel,apache/camel,apache/camel,YMartsynkevych/camel,CandleCandle/camel,nikvaessen/camel,askannon/camel,tadayosi/camel,stalet/camel,woj-i/camel,gnodet/camel,jarst/camel,drsquidop/camel,erwelch/camel,pplatek/camel,askannon/camel,eformat/camel,nicolaferraro/camel,grgrzybek/camel,YMartsynkevych/camel,sabre1041/camel,scranton/camel,lasombra/camel,dsimansk/camel,MrCoder/camel,snurmine/camel,davidwilliams1978/camel,jlpedrosa/camel,yogamaha/camel,askannon/camel,gilfernandes/camel,ge0ffrey/camel,MohammedHammam/camel,ssharma/camel,mike-kukla/camel,zregvart/camel,jamesnetherton/camel,dpocock/camel,atoulme/camel,mgyongyosi/camel,chanakaudaya/camel,oalles/camel,anton-k11/camel,drsquidop/camel,dvankleef/camel,christophd/camel,sabre1041/camel,igarashitm/camel,driseley/camel,prashant2402/camel,MohammedHammam/camel,punkhorn/camel-upstream,Fabryprog/camel,iweiss/camel,nicolaferraro/camel,satishgummadelli/camel,anton-k11/camel,alvinkwekel/camel,yuruki/camel,trohovsky/camel,yury-vashchyla/camel,snurmine/camel,objectiser/camel,cunningt/camel,engagepoint/camel,christophd/camel,royopa/camel,coderczp/camel,jmandawg/camel,jkorab/camel,engagepoint/camel,nikhilvibhav/camel,yuruki/camel,cunningt/camel,dsimansk/camel,haku/camel,jpav/camel,sabre1041/camel,drsquidop/camel,gyc567/camel
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.model; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import org.apache.camel.Processor; import org.apache.camel.component.bean.BeanProcessor; import org.apache.camel.component.bean.RegistryBean; import org.apache.camel.impl.RouteContext; import org.apache.camel.util.CamelContextHelper; import org.apache.camel.util.ObjectHelper; /** * @version $Revision$ */ @XmlRootElement(name = "bean") @XmlAccessorType(XmlAccessType.FIELD) public class BeanRef extends OutputType<ProcessorType> { @XmlAttribute(required = false) private String ref; @XmlAttribute(required = false) private String method; @XmlAttribute(required = false) private Class beanType; @XmlTransient private Object bean; public BeanRef() { } public BeanRef(String ref) { this.ref = ref; } public BeanRef(String ref, String method) { this.ref = ref; this.method = method; } @Override public String toString() { return "Bean[" + getLabel() + "]"; } public String getRef() { return ref; } public void setRef(String ref) { this.ref = ref; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public void setBean(Object bean) { this.bean = bean; } public Class getBeanType() { return beanType; } public void setBeanType(Class beanType) { this.beanType = beanType; } @Override public Processor createProcessor(RouteContext routeContext) { BeanProcessor answer; if (ref != null) { answer = new BeanProcessor(new RegistryBean(routeContext.getCamelContext(), ref)); } else { if (bean == null) { ObjectHelper.notNull(beanType, "bean, ref or beanType"); bean = CamelContextHelper.newInstance(routeContext.getCamelContext(), beanType); } answer = new BeanProcessor(bean, routeContext.getCamelContext()); } if (method != null) { answer.setMethod(method); } return answer; } @Override public String getLabel() { if (ref != null) { String methodText = ""; if (method != null) { methodText = " method: " + method; } return "ref: " + ref + methodText; } else if (bean != null) { return bean.toString(); } else if (beanType != null) { return beanType.getName(); } else { return ""; } } }
camel-core/src/main/java/org/apache/camel/model/BeanRef.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.model; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import org.apache.camel.Processor; import org.apache.camel.component.bean.BeanProcessor; import org.apache.camel.component.bean.RegistryBean; import org.apache.camel.impl.RouteContext; import org.apache.camel.util.CamelContextHelper; import org.apache.camel.util.ObjectHelper; /** * @version $Revision$ */ @XmlRootElement(name = "bean") @XmlAccessorType(XmlAccessType.FIELD) public class BeanRef extends OutputType<ProcessorType> { @XmlAttribute(required = true) private String ref; @XmlAttribute(required = false) private String method; @XmlAttribute(required = false) private Class beanType; @XmlTransient private Object bean; public BeanRef() { } public BeanRef(String ref) { this.ref = ref; } public BeanRef(String ref, String method) { this.ref = ref; this.method = method; } @Override public String toString() { return "Bean[" + getLabel() + "]"; } public String getRef() { return ref; } public void setRef(String ref) { this.ref = ref; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public void setBean(Object bean) { this.bean = bean; } public Class getBeanType() { return beanType; } public void setBeanType(Class beanType) { this.beanType = beanType; } @Override public Processor createProcessor(RouteContext routeContext) { BeanProcessor answer; if (ref != null) { answer = new BeanProcessor(new RegistryBean(routeContext.getCamelContext(), ref)); } else { if (bean == null) { ObjectHelper.notNull(beanType, "bean, ref or beanType"); bean = CamelContextHelper.newInstance(routeContext.getCamelContext(), beanType); } answer = new BeanProcessor(bean, routeContext.getCamelContext()); } if (method != null) { answer.setMethod(method); } return answer; } @Override public String getLabel() { if (ref != null) { String methodText = ""; if (method != null) { methodText = " method: " + method; } return "ref: " + ref + methodText; } else if (bean != null) { return bean.toString(); } else if (beanType != null) { return beanType.getName(); } else { return ""; } } }
the bean ref is not manadatory, you could specify the beanType git-svn-id: e3ccc80b644512be24afa6caf639b2d1f1969354@632281 13f79535-47bb-0310-9956-ffa450edef68
camel-core/src/main/java/org/apache/camel/model/BeanRef.java
the bean ref is not manadatory, you could specify the beanType
<ide><path>amel-core/src/main/java/org/apache/camel/model/BeanRef.java <ide> @XmlRootElement(name = "bean") <ide> @XmlAccessorType(XmlAccessType.FIELD) <ide> public class BeanRef extends OutputType<ProcessorType> { <del> @XmlAttribute(required = true) <add> @XmlAttribute(required = false) <ide> private String ref; <ide> @XmlAttribute(required = false) <ide> private String method;
Java
bsd-2-clause
fd4f97b87ae2d45dec7a05e8284afd518f604976
0
scifio/scifio
// // LeicaReader.java // /* OME Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc. 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 */ package loci.formats.in; import java.io.File; import java.io.IOException; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.Hashtable; import java.util.StringTokenizer; import java.util.Vector; import loci.common.DataTools; import loci.common.Location; import loci.common.RandomAccessInputStream; import loci.formats.AxisGuesser; import loci.formats.CoreMetadata; import loci.formats.FilePattern; import loci.formats.FormatException; import loci.formats.FormatReader; import loci.formats.FormatTools; import loci.formats.MetadataTools; import loci.formats.TiffTools; import loci.formats.meta.FilterMetadata; import loci.formats.meta.MetadataStore; /** * LeicaReader is the file format reader for Leica files. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/in/LeicaReader.java">Trac</a>, * <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/in/LeicaReader.java">SVN</a></dd></dl> * * @author Melissa Linkert linkert at wisc.edu */ public class LeicaReader extends FormatReader { // -- Constants - public static final String[] LEI_SUFFIX = {"lei"}; /** All Leica TIFFs have this tag. */ private static final int LEICA_MAGIC_TAG = 33923; /** IFD tags. */ private static final Integer SERIES = new Integer(10); private static final Integer IMAGES = new Integer(15); private static final Integer DIMDESCR = new Integer(20); private static final Integer FILTERSET = new Integer(30); private static final Integer TIMEINFO = new Integer(40); private static final Integer SCANNERSET = new Integer(50); private static final Integer EXPERIMENT = new Integer(60); private static final Integer LUTDESC = new Integer(70); private static final Hashtable CHANNEL_PRIORITIES = createChannelPriorities(); private static Hashtable createChannelPriorities() { Hashtable h = new Hashtable(); h.put("red", new Integer(0)); h.put("green", new Integer(1)); h.put("blue", new Integer(2)); h.put("cyan", new Integer(3)); h.put("magenta", new Integer(4)); h.put("yellow", new Integer(5)); h.put("black", new Integer(6)); h.put("gray", new Integer(7)); h.put("", new Integer(8)); return h; } // -- Static fields -- private static Hashtable dimensionNames = makeDimensionTable(); // -- Fields -- protected Hashtable[] ifds; /** Array of IFD-like structures containing metadata. */ protected Hashtable[] headerIFDs; /** Helper readers. */ protected MinimalTiffReader tiff; /** Array of image file names. */ protected Vector[] files; /** Number of series in the file. */ private int numSeries; /** Name of current LEI file */ private String leiFilename; private Vector seriesNames; private Vector seriesDescriptions; private int lastPlane = 0; private float[][] physicalSizes; private float[] pinhole, exposureTime; private int[][] channelMap; // -- Constructor -- /** Constructs a new Leica reader. */ public LeicaReader() { super("Leica", new String[] {"lei", "tif", "tiff"}); } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isThisType(String, boolean) */ public boolean isThisType(String name, boolean open) { if (checkSuffix(name, LEI_SUFFIX)) return true; if (!checkSuffix(name, TiffReader.TIFF_SUFFIXES)) return false; if (!open) return false; // not allowed to touch the file system // check for that there is an .lei file in the same directory String prefix = name; if (prefix.indexOf(".") != -1) { prefix = prefix.substring(0, prefix.lastIndexOf(".")); } Location lei = new Location(prefix + ".lei"); if (!lei.exists()) { lei = new Location(prefix + ".LEI"); while (!lei.exists() && prefix.indexOf("_") != -1) { prefix = prefix.substring(0, prefix.lastIndexOf("_")); lei = new Location(prefix + ".lei"); if (!lei.exists()) lei = new Location(prefix + ".LEI"); } } return lei.exists(); } /* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */ public boolean isThisType(RandomAccessInputStream stream) throws IOException { if (!FormatTools.validStream(stream, blockCheckLen, false)) return false; Hashtable ifd = TiffTools.getFirstIFD(stream); return ifd.containsKey(new Integer(LEICA_MAGIC_TAG)); } /* @see loci.formats.IFormatReader#get8BitLookupTable() */ public byte[][] get8BitLookupTable() throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); try { tiff.setId((String) files[series].get(lastPlane)); return tiff.get8BitLookupTable(); } catch (IOException e) { if (debug) trace(e); } return null; } /* @see loci.formats.IFormatReader#get16BitLookupTable() */ public short[][] get16BitLookupTable() throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); try { tiff.setId((String) files[series].get(lastPlane)); return tiff.get16BitLookupTable(); } catch (IOException e) { if (debug) trace(e); } return null; } /* @see loci.formats.IFormatReader#fileGroupOption(String) */ public int fileGroupOption(String id) throws FormatException, IOException { return FormatTools.MUST_GROUP; } /** * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); FormatTools.checkPlaneNumber(this, no); if (!isRGB()) { int[] pos = getZCTCoords(no); pos[1] = DataTools.indexOf(channelMap[series], pos[1]); if (pos[1] >= 0 && pos[1] < getSizeC()) { no = getIndex(pos[0], pos[1], pos[2]); } } lastPlane = no; tiff.setId((String) files[series].get(no)); return tiff.openBytes(0, buf, x, y, w, h); } /* @see loci.formats.IFormatReader#getUsedFiles(boolean) */ public String[] getUsedFiles(boolean noPixels) { FormatTools.assertId(currentId, true, 1); if (noPixels) return new String[] {currentId}; Vector<String> v = new Vector<String>(); v.add(leiFilename); for (int i=0; i<files.length; i++) { for (int j=0; j<files[i].size(); j++) { v.add((String) files[i].get(j)); } } return v.toArray(new String[0]); } /* @see loci.formats.IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { if (in != null) in.close(); if (tiff != null) tiff.close(); tiff = null; if (!fileOnly) { super.close(); leiFilename = null; files = null; ifds = headerIFDs = null; tiff = null; seriesNames = null; numSeries = 0; lastPlane = 0; channelMap = null; physicalSizes = null; seriesDescriptions = null; pinhole = exposureTime = null; } } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { debug("LeicaReader.initFile(" + id + ")"); close(); if (checkSuffix(id, TiffReader.TIFF_SUFFIXES)) { // need to find the associated .lei file if (ifds == null) super.initFile(id); in = new RandomAccessInputStream(id); in.order(TiffTools.checkHeader(in).booleanValue()); in.seek(0); status("Finding companion file name"); // open the TIFF file and look for the "Image Description" field ifds = TiffTools.getIFDs(in); if (ifds == null) throw new FormatException("No IFDs found"); String descr = TiffTools.getComment(ifds[0]); // remove anything of the form "[blah]" descr = descr.replaceAll("\\[.*.\\]\n", ""); // each remaining line in descr is a (key, value) pair, // where '=' separates the key from the value String lei = id.substring(0, id.lastIndexOf(File.separator) + 1); StringTokenizer lines = new StringTokenizer(descr, "\n"); String line = null, key = null, value = null; while (lines.hasMoreTokens()) { line = lines.nextToken(); if (line.indexOf("=") == -1) continue; key = line.substring(0, line.indexOf("=")).trim(); value = line.substring(line.indexOf("=") + 1).trim(); addMeta(key, value); if (key.startsWith("Series Name")) lei += value; } // now open the LEI file Location l = new Location(lei).getAbsoluteFile(); if (l.exists()) { initFile(lei); return; } else { l = l.getParentFile(); String[] list = l.list(); for (int i=0; i<list.length; i++) { if (checkSuffix(list[i], LEI_SUFFIX)) { initFile( new Location(l.getAbsolutePath(), list[i]).getAbsolutePath()); return; } } } throw new FormatException("LEI file not found."); } // parse the LEI file super.initFile(id); leiFilename = new File(id).exists() ? new Location(id).getAbsolutePath() : id; in = new RandomAccessInputStream(id); seriesNames = new Vector(); byte[] fourBytes = new byte[4]; in.read(fourBytes); core[0].littleEndian = (fourBytes[0] == TiffTools.LITTLE && fourBytes[1] == TiffTools.LITTLE && fourBytes[2] == TiffTools.LITTLE && fourBytes[3] == TiffTools.LITTLE); in.order(isLittleEndian()); status("Reading metadata blocks"); in.skipBytes(8); int addr = in.readInt(); Vector v = new Vector(); Hashtable ifd; while (addr != 0) { ifd = new Hashtable(); v.add(ifd); in.seek(addr + 4); int tag = in.readInt(); while (tag != 0) { // create the IFD structure int offset = in.readInt(); long pos = in.getFilePointer(); in.seek(offset + 12); int size = in.readInt(); byte[] data = new byte[size]; in.read(data); ifd.put(new Integer(tag), data); in.seek(pos); tag = in.readInt(); } addr = in.readInt(); } numSeries = v.size(); core = new CoreMetadata[numSeries]; for (int i=0; i<numSeries; i++) { core[i] = new CoreMetadata(); } channelMap = new int[numSeries][]; files = new Vector[numSeries]; headerIFDs = (Hashtable[]) v.toArray(new Hashtable[0]); // determine the length of a filename int nameLength = 0; int maxPlanes = 0; status("Parsing metadata blocks"); core[0].littleEndian = !isLittleEndian(); int seriesIndex = 0; boolean[] valid = new boolean[numSeries]; for (int i=0; i<headerIFDs.length; i++) { valid[i] = true; if (headerIFDs[i].get(SERIES) != null) { byte[] temp = (byte[]) headerIFDs[i].get(SERIES); nameLength = DataTools.bytesToInt(temp, 8, isLittleEndian()) * 2; } Vector f = new Vector(); byte[] tempData = (byte[]) headerIFDs[i].get(IMAGES); RandomAccessInputStream data = new RandomAccessInputStream(tempData); data.order(isLittleEndian()); int tempImages = data.readInt(); if (((long) tempImages * nameLength) > data.length()) { data.order(!isLittleEndian()); tempImages = data.readInt(); data.order(isLittleEndian()); } core[i].sizeX = data.readInt(); core[i].sizeY = data.readInt(); data.skipBytes(4); int samplesPerPixel = data.readInt(); core[i].rgb = samplesPerPixel > 1; core[i].sizeC = samplesPerPixel; File dirFile = new File(id).getAbsoluteFile(); String[] listing = null; String dirPrefix = ""; if (dirFile.exists()) { listing = dirFile.getParentFile().list(); dirPrefix = dirFile.getParent(); if (!dirPrefix.endsWith(File.separator)) dirPrefix += File.separator; } else { listing = (String[]) Location.getIdMap().keySet().toArray(new String[0]); } Vector list = new Vector(); for (int k=0; k<listing.length; k++) { if (checkSuffix(listing[k], TiffReader.TIFF_SUFFIXES)) { list.add(listing[k]); } } boolean tiffsExist = true; String prefix = ""; for (int j=0; j<tempImages; j++) { // read in each filename prefix = getString(data, nameLength); f.add(dirPrefix + prefix); // test to make sure the path is valid Location test = new Location((String) f.get(f.size() - 1)); if (test.exists()) list.remove(prefix); if (tiffsExist) tiffsExist = test.exists(); } data.close(); tempData = null; // at least one of the TIFF files was renamed if (!tiffsExist) { // Strategy for handling renamed files: // 1) Assume that files for each series follow a pattern. // 2) Assign each file group to the first series with the correct count. status("Handling renamed TIFF files"); listing = (String[]) list.toArray(new String[0]); // grab the file patterns Vector filePatterns = new Vector(); for (int q=0; q<listing.length; q++) { Location l = new Location(dirPrefix, listing[q]); l = l.getAbsoluteFile(); FilePattern pattern = new FilePattern(l); AxisGuesser guess = new AxisGuesser(pattern, "XYZCT", 1, 1, 1, false); String fp = pattern.getPattern(); if (guess.getAxisCountS() >= 1) { String pre = pattern.getPrefix(guess.getAxisCountS()); Vector fileList = new Vector(); for (int n=0; n<listing.length; n++) { Location p = new Location(dirPrefix, listing[n]); if (p.getAbsolutePath().startsWith(pre)) { fileList.add(listing[n]); } } fp = FilePattern.findPattern(l.getAbsolutePath(), dirPrefix, (String[]) fileList.toArray(new String[0])); } if (fp != null && !filePatterns.contains(fp)) { filePatterns.add(fp); } } for (int q=0; q<filePatterns.size(); q++) { String[] pattern = new FilePattern((String) filePatterns.get(q)).getFiles(); if (pattern.length == tempImages) { // make sure that this pattern hasn't already been used boolean validPattern = true; for (int n=0; n<i; n++) { if (files[n] == null) continue; if (files[n].contains(pattern[0])) { validPattern = false; break; } } if (validPattern) { files[i] = new Vector(); for (int n=0; n<pattern.length; n++) { files[i].add(pattern[n]); } } } } } else files[i] = f; if (files[i] == null) valid[i] = false; else { core[i].imageCount = files[i].size(); if (core[i].imageCount > maxPlanes) maxPlanes = core[i].imageCount; } } int invalidCount = 0; for (int i=0; i<valid.length; i++) { if (!valid[i]) invalidCount++; } numSeries -= invalidCount; int[] count = new int[getSeriesCount()]; for (int i=0; i<getSeriesCount(); i++) { count[i] = core[i].imageCount; } Vector[] tempFiles = files; Hashtable[] tempIFDs = headerIFDs; core = new CoreMetadata[numSeries]; files = new Vector[numSeries]; headerIFDs = new Hashtable[numSeries]; int index = 0; for (int i=0; i<numSeries; i++) { core[i] = new CoreMetadata(); while (!valid[index]) index++; core[i].imageCount = count[index]; files[i] = tempFiles[index]; Object[] sorted = files[i].toArray(); Arrays.sort(sorted); files[i].clear(); for (int q=0; q<sorted.length; q++) { files[i].add(sorted[q]); } headerIFDs[i] = tempIFDs[index]; index++; } tiff = new MinimalTiffReader(); status("Populating metadata"); if (headerIFDs == null) headerIFDs = ifds; int fileLength = 0; int resolution = -1; String[][] timestamps = new String[headerIFDs.length][]; seriesDescriptions = new Vector(); physicalSizes = new float[headerIFDs.length][5]; pinhole = new float[headerIFDs.length]; exposureTime = new float[headerIFDs.length]; for (int i=0; i<headerIFDs.length; i++) { Object[] keys = headerIFDs[i].keySet().toArray(); Arrays.sort(keys); String prefix = "Series " + i + " "; for (int q=0; q<keys.length; q++) { byte[] tmp = (byte[]) headerIFDs[i].get(keys[q]); if (tmp == null) continue; RandomAccessInputStream stream = new RandomAccessInputStream(tmp); stream.order(isLittleEndian()); if (keys[q].equals(SERIES)) { addMeta(prefix + "Version", stream.readInt()); addMeta(prefix + "Number of Series", stream.readInt()); fileLength = stream.readInt(); addMeta(prefix + "Length of filename", fileLength); int extLen = stream.readInt(); if (extLen > fileLength) { stream.seek(8); core[0].littleEndian = !isLittleEndian(); stream.order(isLittleEndian()); fileLength = stream.readInt(); extLen = stream.readInt(); } addMeta(prefix + "Length of file extension", extLen); addMeta(prefix + "Image file extension", getString(stream, extLen)); } else if (keys[q].equals(IMAGES)) { core[i].imageCount = stream.readInt(); core[i].sizeX = stream.readInt(); core[i].sizeY = stream.readInt(); addMeta(prefix + "Number of images", core[i].imageCount); addMeta(prefix + "Image width", core[i].sizeX); addMeta(prefix + "Image height", core[i].sizeY); addMeta(prefix + "Bits per Sample", stream.readInt()); addMeta(prefix + "Samples per pixel", stream.readInt()); String name = getString(stream, fileLength * 2); if (name.indexOf(".") != -1) { name = name.substring(0, name.lastIndexOf(".")); } String[] tokens = name.split("_"); StringBuffer buf = new StringBuffer(); for (int p=1; p<tokens.length; p++) { String lcase = tokens[p].toLowerCase(); if (!lcase.startsWith("ch0") && !lcase.startsWith("c0") && !lcase.startsWith("z0") && !lcase.startsWith("t0")) { if (buf.length() > 0) buf.append("_"); buf.append(tokens[p]); } } seriesNames.add(buf.toString()); } else if (keys[q].equals(DIMDESCR)) { addMeta(prefix + "Voxel Version", stream.readInt()); core[i].rgb = stream.readInt() == 20; addMeta(prefix + "VoxelType", core[i].rgb ? "RGB" : "gray"); int bpp = stream.readInt(); addMeta(prefix + "Bytes per pixel", bpp); switch (bpp) { case 1: core[i].pixelType = FormatTools.UINT8; break; case 3: core[i].pixelType = FormatTools.UINT8; core[i].sizeC = 3; core[i].rgb = true; break; case 2: core[i].pixelType = FormatTools.UINT16; break; case 6: core[i].pixelType = FormatTools.UINT16; core[i].sizeC = 3; core[i].rgb = true; break; case 4: core[i].pixelType = FormatTools.UINT32; break; default: throw new FormatException("Unsupported bytes per pixel (" + bpp + ")"); } core[i].dimensionOrder = "XY"; resolution = stream.readInt(); addMeta(prefix + "Real world resolution", resolution); addMeta(prefix + "Maximum voxel intensity", getString(stream, true)); addMeta(prefix + "Minimum voxel intensity", getString(stream, true)); int len = stream.readInt(); stream.skipBytes(len * 2 + 4); len = stream.readInt(); for (int j=0; j<len; j++) { int dimId = stream.readInt(); String dimType = (String) dimensionNames.get(new Integer(dimId)); if (dimType == null) dimType = ""; int size = stream.readInt(); int distance = stream.readInt(); int strlen = stream.readInt() * 2; String[] sizeData = getString(stream, strlen).split(" "); String physicalSize = sizeData[0]; String unit = ""; if (sizeData.length > 1) unit = sizeData[1]; float physical = Float.parseFloat(physicalSize) / size; if (unit.equals("m")) { physical *= 1000000; } if (dimType.equals("x")) { core[i].sizeX = size; physicalSizes[i][0] = physical; } else if (dimType.equals("y")) { core[i].sizeY = size; physicalSizes[i][1] = physical; } else if (dimType.indexOf("z") != -1) { core[i].sizeZ = size; if (core[i].dimensionOrder.indexOf("Z") == -1) { core[i].dimensionOrder += "Z"; } physicalSizes[i][2] = physical; } else if (dimType.equals("channel")) { if (core[i].sizeC == 0) core[i].sizeC = 1; core[i].sizeC *= size; if (core[i].dimensionOrder.indexOf("C") == -1) { core[i].dimensionOrder += "C"; } physicalSizes[i][3] = physical; } else { core[i].sizeT = size; if (core[i].dimensionOrder.indexOf("T") == -1) { core[i].dimensionOrder += "T"; } physicalSizes[i][4] = physical; } String dimPrefix = prefix + "Dim" + j; addMeta(dimPrefix + " type", dimType); addMeta(dimPrefix + " size", size); addMeta(dimPrefix + " distance between sub-dimensions", distance); addMeta(dimPrefix + " physical length", physicalSize + " " + unit); addMeta(dimPrefix + " physical origin", getString(stream, true)); } addMeta(prefix + "Series name", getString(stream, false)); String description = getString(stream, false); seriesDescriptions.add(description); addMeta(prefix + "Series description", description); } else if (keys[q].equals(TIMEINFO)) { int nDims = stream.readInt(); addMeta(prefix + "Number of time-stamped dimensions", nDims); addMeta(prefix + "Time-stamped dimension", stream.readInt()); for (int j=0; j<nDims; j++) { String dimPrefix = prefix + "Dimension " + j; addMeta(dimPrefix + " ID", stream.readInt()); addMeta(dimPrefix + " size", stream.readInt()); addMeta(dimPrefix + " distance", stream.readInt()); } int numStamps = stream.readInt(); addMeta(prefix + "Number of time-stamps", numStamps); timestamps[i] = new String[numStamps]; for (int j=0; j<numStamps; j++) { timestamps[i][j] = getString(stream, 64); addMeta(prefix + "Timestamp " + j, timestamps[i][j]); } if (stream.getFilePointer() < stream.length()) { int numTMs = stream.readInt(); addMeta(prefix + "Number of time-markers", numTMs); for (int j=0; j<numTMs; j++) { int numDims = stream.readInt(); String time = "Time-marker " + j + " Dimension "; for (int k=0; k<numDims; k++) { addMeta(prefix + time + k + " coordinate", stream.readInt()); } addMeta(prefix + "Time-marker " + j, getString(stream, 64)); } } } else if (keys[q].equals(EXPERIMENT)) { stream.skipBytes(8); String description = getString(stream, true); addMeta(prefix + "Image Description", description); addMeta(prefix + "Main file extension", getString(stream, true)); addMeta(prefix + "Image format identifier", getString(stream, true)); addMeta(prefix + "Single image extension", getString(stream, true)); } else if (keys[q].equals(LUTDESC)) { int nChannels = stream.readInt(); if (nChannels > 0) core[i].indexed = true; addMeta(prefix + "Number of LUT channels", nChannels); addMeta(prefix + "ID of colored dimension", stream.readInt()); channelMap[i] = new int[nChannels]; String[] luts = new String[nChannels]; for (int j=0; j<nChannels; j++) { String p = prefix + "LUT Channel " + j; addMeta(p + " version", stream.readInt()); addMeta(p + " inverted?", stream.read() == 1); addMeta(p + " description", getString(stream, false)); addMeta(p + " filename", getString(stream, false)); luts[j] = getString(stream, false); addMeta(p + " name", luts[j]); luts[j] = luts[j].toLowerCase(); stream.skipBytes(8); } // finish setting up channel mapping for (int p=0; p<channelMap[i].length; p++) { if (!CHANNEL_PRIORITIES.containsKey(luts[p])) luts[p] = ""; channelMap[i][p] = ((Integer) CHANNEL_PRIORITIES.get(luts[p])).intValue(); } int[] sorted = new int[channelMap[i].length]; Arrays.fill(sorted, -1); for (int p=0; p<sorted.length; p++) { int min = Integer.MAX_VALUE; int minIndex = -1; for (int n=0; n<channelMap[i].length; n++) { if (channelMap[i][n] < min && !DataTools.containsValue(sorted, n)) { min = channelMap[i][n]; minIndex = n; } } sorted[p] = minIndex; } for (int p=0; p<channelMap[i].length; p++) { channelMap[i][sorted[p]] = p; } } stream.close(); } core[i].orderCertain = true; core[i].littleEndian = isLittleEndian(); core[i].falseColor = true; core[i].metadataComplete = true; core[i].interleaved = false; } for (int i=0; i<numSeries; i++) { setSeries(i); if (getSizeZ() == 0) core[i].sizeZ = 1; if (getSizeT() == 0) core[i].sizeT = 1; if (getSizeC() == 0) core[i].sizeC = 1; if (getImageCount() == 0) core[i].imageCount = 1; if (getImageCount() == 1 && getSizeZ() * getSizeT() > 1) { core[i].sizeZ = 1; core[i].sizeT = 1; } if (getSizeY() == 1) { // XZ or XT scan if (getSizeZ() > 1 && getImageCount() == getSizeC() * getSizeT()) { core[i].sizeY = getSizeZ(); core[i].sizeZ = 1; } else if (getSizeT() > 1 && getImageCount() == getSizeC() * getSizeZ()) { core[i].sizeY = getSizeT(); core[i].sizeT = 1; } } if (isRGB()) core[i].indexed = false; if (getDimensionOrder().indexOf("C") == -1) { core[i].dimensionOrder += "C"; } if (getDimensionOrder().indexOf("Z") == -1) { core[i].dimensionOrder += "Z"; } if (getDimensionOrder().indexOf("T") == -1) { core[i].dimensionOrder += "T"; } } MetadataStore store = new FilterMetadata(getMetadataStore(), isMetadataFiltered()); MetadataTools.populatePixels(store, this, true); store.setInstrumentID("Instrument:0", 0); for (int i=0; i<numSeries; i++) { long firstPlane = 0; if (i < timestamps.length && timestamps[i] != null && timestamps[i].length > 0) { SimpleDateFormat parse = new SimpleDateFormat("yyyy:MM:dd,HH:mm:ss:SSS"); Date date = parse.parse(timestamps[i][0], new ParsePosition(0)); firstPlane = date.getTime(); SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); store.setImageCreationDate(fmt.format(date), i); } else { MetadataTools.setDefaultCreationDate(store, id, i); } store.setImageName((String) seriesNames.get(i), i); store.setImageDescription((String) seriesDescriptions.get(i), i); // link Instrument and Image store.setImageInstrumentRef("Instrument:0", i); store.setDimensionsPhysicalSizeX(new Float(physicalSizes[i][0]), i, 0); store.setDimensionsPhysicalSizeY(new Float(physicalSizes[i][1]), i, 0); store.setDimensionsPhysicalSizeZ(new Float(physicalSizes[i][2]), i, 0); if ((int) physicalSizes[i][3] > 0) { store.setDimensionsWaveIncrement( new Integer((int) physicalSizes[i][3]), i, 0); } store.setDimensionsTimeIncrement(new Float(physicalSizes[i][4]), i, 0); // parse instrument data Object[] keys = headerIFDs[i].keySet().toArray(); for (int q=0; q<keys.length; q++) { if (keys[q].equals(FILTERSET) || keys[q].equals(SCANNERSET)) { byte[] tmp = (byte[]) headerIFDs[i].get(keys[q]); if (tmp == null) continue; RandomAccessInputStream stream = new RandomAccessInputStream(tmp); stream.order(isLittleEndian()); parseInstrumentData(stream, store, i); stream.close(); } } for (int j=0; j<core[i].imageCount; j++) { if (timestamps[i] != null && j < timestamps[i].length) { SimpleDateFormat parse = new SimpleDateFormat("yyyy:MM:dd,HH:mm:ss:SSS"); Date date = parse.parse(timestamps[i][j], new ParsePosition(0)); float elapsedTime = (float) (date.getTime() - firstPlane) / 1000; store.setPlaneTimingDeltaT(new Float(elapsedTime), i, 0, j); store.setPlaneTimingExposureTime(new Float(exposureTime[i]), i, 0, j); } } } setSeries(0); } // -- Helper methods -- private void parseInstrumentData(RandomAccessInputStream stream, MetadataStore store, int series) throws IOException { // read 24 byte SAFEARRAY stream.skipBytes(4); int cbElements = stream.readInt(); stream.skipBytes(8); int nElements = stream.readInt(); stream.skipBytes(4); Vector[] channelNames = new Vector[getSeriesCount()]; Vector[] emWaves = new Vector[getSeriesCount()]; Vector[] exWaves = new Vector[getSeriesCount()]; for (int i=0; i<getSeriesCount(); i++) { channelNames[i] = new Vector(); emWaves[i] = new Vector(); exWaves[i] = new Vector(); } for (int j=0; j<nElements; j++) { stream.seek(24 + j * cbElements); String contentID = getString(stream, 128); String description = getString(stream, 64); String data = getString(stream, 64); int dataType = stream.readShort(); stream.skipBytes(6); // read data switch (dataType) { case 2: data = String.valueOf(stream.readShort()); break; case 3: data = String.valueOf(stream.readInt()); break; case 4: data = String.valueOf(stream.readFloat()); break; case 5: data = String.valueOf(stream.readDouble()); break; case 7: case 11: data = stream.read() == 0 ? "false" : "true"; break; case 17: data = stream.readString(1); break; } String[] tokens = contentID.split("\\|"); if (tokens[0].startsWith("CDetectionUnit")) { // detector information if (tokens[1].startsWith("PMT")) { try { int ndx = tokens[1].lastIndexOf(" ") + 1; int detector = Integer.parseInt(tokens[1].substring(ndx)) - 1; store.setDetectorType("Unknown", 0, detector); if (tokens[2].equals("VideoOffset")) { store.setDetectorOffset(new Float(data), 0, detector); } else if (tokens[2].equals("HighVoltage")) { store.setDetectorVoltage(new Float(data), 0, detector); } else if (tokens[2].equals("State")) { // link Detector to Image, if the detector was actually used store.setDetectorID("Detector:" + detector, 0, detector); for (int i=0; i<getSeriesCount(); i++) { if (detector < core[i].sizeC) { store.setDetectorSettingsDetector("Detector:" + detector, i, detector); } } } } catch (NumberFormatException e) { if (debug) trace(e); } } } else if (tokens[0].startsWith("CTurret")) { // objective information int objective = Integer.parseInt(tokens[3]); if (tokens[2].equals("NumericalAperture")) { store.setObjectiveLensNA(new Float(data), 0, objective); } else if (tokens[2].equals("Objective")) { String[] objectiveData = data.split(" "); StringBuffer model = new StringBuffer(); String mag = null, na = null; StringBuffer correction = new StringBuffer(); String immersion = null; for (int i=0; i<objectiveData.length; i++) { if (objectiveData[i].indexOf("x") != -1 && mag == null && na == null) { int xIndex = objectiveData[i].indexOf("x"); mag = objectiveData[i].substring(0, xIndex).trim(); na = objectiveData[i].substring(xIndex + 1).trim(); } else if (mag == null && na == null) { model.append(objectiveData[i]); model.append(" "); } else if (immersion == null) { immersion = objectiveData[i]; } else { correction.append(objectiveData[i]); correction.append(" "); } } if (immersion == null || immersion.trim().equals("")) { immersion = "Unknown"; } store.setObjectiveImmersion(immersion, 0, objective); store.setObjectiveCorrection(correction.toString().trim(), 0, objective); store.setObjectiveModel(model.toString().trim(), 0, objective); store.setObjectiveLensNA(new Float(na), 0, objective); store.setObjectiveNominalMagnification( new Integer((int) Float.parseFloat(mag)), 0, objective); } else if (tokens[2].equals("OrderNumber")) { store.setObjectiveSerialNumber(data, 0, objective); } else if (tokens[2].equals("RefractionIndex")) { store.setObjectiveSettingsRefractiveIndex(new Float(data), series); } // link Objective to Image store.setObjectiveID("Objective:" + objective, 0, objective); if (objective == 0) { store.setObjectiveSettingsObjective("Objective:" + objective, series); store.setImageObjective("Objective:" + objective, series); } } else if (tokens[0].startsWith("CSpectrophotometerUnit")) { int ndx = tokens[1].lastIndexOf(" ") + 1; int channel = Integer.parseInt(tokens[1].substring(ndx)) - 1; if (tokens[2].equals("Wavelength")) { Integer wavelength = new Integer((int) Float.parseFloat(data)); if (tokens[3].equals("0")) { emWaves[series].add(wavelength); } else if (tokens[3].equals("1")) { exWaves[series].add(wavelength); } } else if (tokens[2].equals("Stain")) { channelNames[series].add(data); } } else if (tokens[0].startsWith("CXYZStage")) { // NB: there is only one stage position specified for each series if (tokens[2].equals("XPos")) { for (int q=0; q<core[series].imageCount; q++) { store.setStagePositionPositionX(new Float(data), series, 0, q); } } else if (tokens[2].equals("YPos")) { for (int q=0; q<core[series].imageCount; q++) { store.setStagePositionPositionY(new Float(data), series, 0, q); } } else if (tokens[2].equals("ZPos")) { for (int q=0; q<core[series].imageCount; q++) { store.setStagePositionPositionZ(new Float(data), series, 0, q); } } } if (contentID.equals("dblVoxelX")) { physicalSizes[series][0] = Float.parseFloat(data); } else if (contentID.equals("dblVoxelY")) { physicalSizes[series][1] = Float.parseFloat(data); } else if (contentID.equals("dblVoxelZ")) { physicalSizes[series][2] = Float.parseFloat(data); } else if (contentID.equals("dblPinhole")) { pinhole[series] = Float.parseFloat(data); } else if (contentID.equals("dblZoom")) { store.setDisplayOptionsZoom(new Float(data), series); } else if (contentID.startsWith("nDelayTime")) { exposureTime[series] = Float.parseFloat(data); if (contentID.endsWith("_ms")) { exposureTime[series] /= 1000f; } } addMeta("Series " + series + " " + contentID, data); } stream.close(); // populate saved LogicalChannel data for (int i=0; i<getSeriesCount(); i++) { int nextChannel = 0; for (int channel=0; channel<getEffectiveSizeC(); channel++) { if (channel >= channelNames[i].size()) break; String name = (String) channelNames[i].get(channel); if (name == null || name.trim().equals("")) continue; store.setLogicalChannelName(name, i, nextChannel); store.setLogicalChannelEmWave((Integer) emWaves[i].get(channel), i, nextChannel); store.setLogicalChannelExWave((Integer) exWaves[i].get(channel), i, nextChannel); store.setLogicalChannelPinholeSize(new Float(pinhole[i]), i, nextChannel); nextChannel++; } } } private boolean usedFile(String s) { if (files == null) return false; for (int i=0; i<files.length; i++) { if (files[i] == null) continue; for (int j=0; j<files[i].size(); j++) { if (((String) files[i].get(j)).endsWith(s)) return true; } } return false; } private String getString(RandomAccessInputStream stream, int len) throws IOException { return DataTools.stripString(stream.readString(len)); } private String getString(RandomAccessInputStream stream, boolean doubleLength) throws IOException { int len = stream.readInt(); if (doubleLength) len *= 2; return getString(stream, len); } private static Hashtable makeDimensionTable() { Hashtable table = new Hashtable(); table.put(new Integer(0), "undefined"); table.put(new Integer(120), "x"); table.put(new Integer(121), "y"); table.put(new Integer(122), "z"); table.put(new Integer(116), "t"); table.put(new Integer(6815843), "channel"); table.put(new Integer(6357100), "wave length"); table.put(new Integer(7602290), "rotation"); table.put(new Integer(7798904), "x-wide for the motorized xy-stage"); table.put(new Integer(7798905), "y-wide for the motorized xy-stage"); table.put(new Integer(7798906), "z-wide for the z-stage-drive"); table.put(new Integer(4259957), "user1 - unspecified"); table.put(new Integer(4325493), "user2 - unspecified"); table.put(new Integer(4391029), "user3 - unspecified"); table.put(new Integer(6357095), "graylevel"); table.put(new Integer(6422631), "graylevel1"); table.put(new Integer(6488167), "graylevel2"); table.put(new Integer(6553703), "graylevel3"); table.put(new Integer(7864398), "logical x"); table.put(new Integer(7929934), "logical y"); table.put(new Integer(7995470), "logical z"); table.put(new Integer(7602254), "logical t"); table.put(new Integer(7077966), "logical lambda"); table.put(new Integer(7471182), "logical rotation"); table.put(new Integer(5767246), "logical x-wide"); table.put(new Integer(5832782), "logical y-wide"); table.put(new Integer(5898318), "logical z-wide"); return table; } }
components/bio-formats/src/loci/formats/in/LeicaReader.java
// // LeicaReader.java // /* OME Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc. 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 */ package loci.formats.in; import java.io.File; import java.io.IOException; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.Hashtable; import java.util.StringTokenizer; import java.util.Vector; import loci.common.DataTools; import loci.common.Location; import loci.common.RandomAccessInputStream; import loci.formats.AxisGuesser; import loci.formats.CoreMetadata; import loci.formats.FilePattern; import loci.formats.FormatException; import loci.formats.FormatReader; import loci.formats.FormatTools; import loci.formats.MetadataTools; import loci.formats.TiffTools; import loci.formats.meta.FilterMetadata; import loci.formats.meta.MetadataStore; /** * LeicaReader is the file format reader for Leica files. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/in/LeicaReader.java">Trac</a>, * <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/in/LeicaReader.java">SVN</a></dd></dl> * * @author Melissa Linkert linkert at wisc.edu */ public class LeicaReader extends FormatReader { // -- Constants - public static final String[] LEI_SUFFIX = {"lei"}; /** All Leica TIFFs have this tag. */ private static final int LEICA_MAGIC_TAG = 33923; /** IFD tags. */ private static final Integer SERIES = new Integer(10); private static final Integer IMAGES = new Integer(15); private static final Integer DIMDESCR = new Integer(20); private static final Integer FILTERSET = new Integer(30); private static final Integer TIMEINFO = new Integer(40); private static final Integer SCANNERSET = new Integer(50); private static final Integer EXPERIMENT = new Integer(60); private static final Integer LUTDESC = new Integer(70); private static final Hashtable CHANNEL_PRIORITIES = createChannelPriorities(); private static Hashtable createChannelPriorities() { Hashtable h = new Hashtable(); h.put("red", new Integer(0)); h.put("green", new Integer(1)); h.put("blue", new Integer(2)); h.put("cyan", new Integer(3)); h.put("magenta", new Integer(4)); h.put("yellow", new Integer(5)); h.put("black", new Integer(6)); h.put("gray", new Integer(7)); h.put("", new Integer(8)); return h; } // -- Static fields -- private static Hashtable dimensionNames = makeDimensionTable(); // -- Fields -- protected Hashtable[] ifds; /** Array of IFD-like structures containing metadata. */ protected Hashtable[] headerIFDs; /** Helper readers. */ protected MinimalTiffReader tiff; /** Array of image file names. */ protected Vector[] files; /** Number of series in the file. */ private int numSeries; /** Name of current LEI file */ private String leiFilename; private Vector seriesNames; private Vector seriesDescriptions; private int lastPlane = 0; private float[][] physicalSizes; private float[] pinhole, exposureTime; private int[][] channelMap; // -- Constructor -- /** Constructs a new Leica reader. */ public LeicaReader() { super("Leica", new String[] {"lei", "tif", "tiff"}); } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isThisType(String, boolean) */ public boolean isThisType(String name, boolean open) { if (checkSuffix(name, LEI_SUFFIX)) return true; if (!checkSuffix(name, TiffReader.TIFF_SUFFIXES)) return false; if (!open) return false; // not allowed to touch the file system // check for that there is an .lei file in the same directory String prefix = name; if (prefix.indexOf(".") != -1) { prefix = prefix.substring(0, prefix.lastIndexOf(".")); } Location lei = new Location(prefix + ".lei"); if (!lei.exists()) { lei = new Location(prefix + ".LEI"); while (!lei.exists() && prefix.indexOf("_") != -1) { prefix = prefix.substring(0, prefix.lastIndexOf("_")); lei = new Location(prefix + ".lei"); if (!lei.exists()) lei = new Location(prefix + ".LEI"); } } return lei.exists(); } /* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */ public boolean isThisType(RandomAccessInputStream stream) throws IOException { if (!FormatTools.validStream(stream, blockCheckLen, false)) return false; Hashtable ifd = TiffTools.getFirstIFD(stream); return ifd.containsKey(new Integer(LEICA_MAGIC_TAG)); } /* @see loci.formats.IFormatReader#get8BitLookupTable() */ public byte[][] get8BitLookupTable() throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); try { tiff.setId((String) files[series].get(lastPlane)); return tiff.get8BitLookupTable(); } catch (IOException e) { if (debug) trace(e); } return null; } /* @see loci.formats.IFormatReader#get16BitLookupTable() */ public short[][] get16BitLookupTable() throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); try { tiff.setId((String) files[series].get(lastPlane)); return tiff.get16BitLookupTable(); } catch (IOException e) { if (debug) trace(e); } return null; } /* @see loci.formats.IFormatReader#fileGroupOption(String) */ public int fileGroupOption(String id) throws FormatException, IOException { return FormatTools.MUST_GROUP; } /** * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); FormatTools.checkPlaneNumber(this, no); if (!isRGB()) { int[] pos = getZCTCoords(no); pos[1] = DataTools.indexOf(channelMap[series], pos[1]); if (pos[1] >= 0 && pos[1] < getSizeC()) { no = getIndex(pos[0], pos[1], pos[2]); } } lastPlane = no; tiff.setId((String) files[series].get(no)); return tiff.openBytes(0, buf, x, y, w, h); } /* @see loci.formats.IFormatReader#getUsedFiles(boolean) */ public String[] getUsedFiles(boolean noPixels) { FormatTools.assertId(currentId, true, 1); if (noPixels) return new String[] {currentId}; Vector<String> v = new Vector<String>(); v.add(leiFilename); for (int i=0; i<files.length; i++) { for (int j=0; j<files[i].size(); j++) { v.add((String) files[i].get(j)); } } return v.toArray(new String[0]); } /* @see loci.formats.IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { if (in != null) in.close(); if (tiff != null) tiff.close(); tiff = null; if (!fileOnly) { super.close(); leiFilename = null; files = null; ifds = headerIFDs = null; tiff = null; seriesNames = null; numSeries = 0; lastPlane = 0; channelMap = null; physicalSizes = null; seriesDescriptions = null; pinhole = exposureTime = null; } } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { debug("LeicaReader.initFile(" + id + ")"); close(); if (checkSuffix(id, TiffReader.TIFF_SUFFIXES)) { // need to find the associated .lei file if (ifds == null) super.initFile(id); in = new RandomAccessInputStream(id); in.order(TiffTools.checkHeader(in).booleanValue()); in.seek(0); status("Finding companion file name"); // open the TIFF file and look for the "Image Description" field ifds = TiffTools.getIFDs(in); if (ifds == null) throw new FormatException("No IFDs found"); String descr = TiffTools.getComment(ifds[0]); // remove anything of the form "[blah]" descr = descr.replaceAll("\\[.*.\\]\n", ""); // each remaining line in descr is a (key, value) pair, // where '=' separates the key from the value String lei = id.substring(0, id.lastIndexOf(File.separator) + 1); StringTokenizer lines = new StringTokenizer(descr, "\n"); String line = null, key = null, value = null; while (lines.hasMoreTokens()) { line = lines.nextToken(); if (line.indexOf("=") == -1) continue; key = line.substring(0, line.indexOf("=")).trim(); value = line.substring(line.indexOf("=") + 1).trim(); addMeta(key, value); if (key.startsWith("Series Name")) lei += value; } // now open the LEI file Location l = new Location(lei).getAbsoluteFile(); if (l.exists()) { initFile(lei); return; } else { l = l.getParentFile(); String[] list = l.list(); for (int i=0; i<list.length; i++) { if (checkSuffix(list[i], LEI_SUFFIX)) { initFile( new Location(l.getAbsolutePath(), list[i]).getAbsolutePath()); return; } } } throw new FormatException("LEI file not found."); } // parse the LEI file super.initFile(id); leiFilename = new File(id).exists() ? new Location(id).getAbsolutePath() : id; in = new RandomAccessInputStream(id); seriesNames = new Vector(); byte[] fourBytes = new byte[4]; in.read(fourBytes); core[0].littleEndian = (fourBytes[0] == TiffTools.LITTLE && fourBytes[1] == TiffTools.LITTLE && fourBytes[2] == TiffTools.LITTLE && fourBytes[3] == TiffTools.LITTLE); in.order(isLittleEndian()); status("Reading metadata blocks"); in.skipBytes(8); int addr = in.readInt(); Vector v = new Vector(); Hashtable ifd; while (addr != 0) { ifd = new Hashtable(); v.add(ifd); in.seek(addr + 4); int tag = in.readInt(); while (tag != 0) { // create the IFD structure int offset = in.readInt(); long pos = in.getFilePointer(); in.seek(offset + 12); int size = in.readInt(); byte[] data = new byte[size]; in.read(data); ifd.put(new Integer(tag), data); in.seek(pos); tag = in.readInt(); } addr = in.readInt(); } numSeries = v.size(); core = new CoreMetadata[numSeries]; for (int i=0; i<numSeries; i++) { core[i] = new CoreMetadata(); } channelMap = new int[numSeries][]; files = new Vector[numSeries]; headerIFDs = (Hashtable[]) v.toArray(new Hashtable[0]); // determine the length of a filename int nameLength = 0; int maxPlanes = 0; status("Parsing metadata blocks"); core[0].littleEndian = !isLittleEndian(); int seriesIndex = 0; boolean[] valid = new boolean[numSeries]; for (int i=0; i<headerIFDs.length; i++) { valid[i] = true; if (headerIFDs[i].get(SERIES) != null) { byte[] temp = (byte[]) headerIFDs[i].get(SERIES); nameLength = DataTools.bytesToInt(temp, 8, isLittleEndian()) * 2; } Vector f = new Vector(); byte[] tempData = (byte[]) headerIFDs[i].get(IMAGES); RandomAccessInputStream data = new RandomAccessInputStream(tempData); data.order(isLittleEndian()); int tempImages = data.readInt(); if (((long) tempImages * nameLength) > data.length()) { data.order(!isLittleEndian()); tempImages = data.readInt(); data.order(isLittleEndian()); } core[i].sizeX = data.readInt(); core[i].sizeY = data.readInt(); data.skipBytes(4); int samplesPerPixel = data.readInt(); core[i].rgb = samplesPerPixel > 1; core[i].sizeC = samplesPerPixel; File dirFile = new File(id).getAbsoluteFile(); String[] listing = null; String dirPrefix = ""; if (dirFile.exists()) { listing = dirFile.getParentFile().list(); dirPrefix = dirFile.getParent(); if (!dirPrefix.endsWith(File.separator)) dirPrefix += File.separator; } else { listing = (String[]) Location.getIdMap().keySet().toArray(new String[0]); } Vector list = new Vector(); for (int k=0; k<listing.length; k++) { if (checkSuffix(listing[k], TiffReader.TIFF_SUFFIXES)) { list.add(listing[k]); } } boolean tiffsExist = true; String prefix = ""; for (int j=0; j<tempImages; j++) { // read in each filename prefix = getString(data, nameLength); f.add(dirPrefix + prefix); // test to make sure the path is valid Location test = new Location((String) f.get(f.size() - 1)); if (test.exists()) list.remove(prefix); if (tiffsExist) tiffsExist = test.exists(); } data.close(); tempData = null; // at least one of the TIFF files was renamed if (!tiffsExist) { // Strategy for handling renamed files: // 1) Assume that files for each series follow a pattern. // 2) Assign each file group to the first series with the correct count. status("Handling renamed TIFF files"); listing = (String[]) list.toArray(new String[0]); // grab the file patterns Vector filePatterns = new Vector(); for (int q=0; q<listing.length; q++) { Location l = new Location(dirPrefix, listing[q]); l = l.getAbsoluteFile(); FilePattern pattern = new FilePattern(l); AxisGuesser guess = new AxisGuesser(pattern, "XYZCT", 1, 1, 1, false); String fp = pattern.getPattern(); if (guess.getAxisCountS() >= 1) { String pre = pattern.getPrefix(guess.getAxisCountS()); Vector fileList = new Vector(); for (int n=0; n<listing.length; n++) { Location p = new Location(dirPrefix, listing[n]); if (p.getAbsolutePath().startsWith(pre)) { fileList.add(listing[n]); } } fp = FilePattern.findPattern(l.getAbsolutePath(), dirPrefix, (String[]) fileList.toArray(new String[0])); } if (fp != null && !filePatterns.contains(fp)) { filePatterns.add(fp); } } for (int q=0; q<filePatterns.size(); q++) { String[] pattern = new FilePattern((String) filePatterns.get(q)).getFiles(); if (pattern.length == tempImages) { // make sure that this pattern hasn't already been used boolean validPattern = true; for (int n=0; n<i; n++) { if (files[n] == null) continue; if (files[n].contains(pattern[0])) { validPattern = false; break; } } if (validPattern) { files[i] = new Vector(); for (int n=0; n<pattern.length; n++) { files[i].add(pattern[n]); } } } } } else files[i] = f; if (files[i] == null) valid[i] = false; else { core[i].imageCount = files[i].size(); if (core[i].imageCount > maxPlanes) maxPlanes = core[i].imageCount; } } int invalidCount = 0; for (int i=0; i<valid.length; i++) { if (!valid[i]) invalidCount++; } numSeries -= invalidCount; int[] count = new int[getSeriesCount()]; for (int i=0; i<getSeriesCount(); i++) { count[i] = core[i].imageCount; } Vector[] tempFiles = files; Hashtable[] tempIFDs = headerIFDs; core = new CoreMetadata[numSeries]; files = new Vector[numSeries]; headerIFDs = new Hashtable[numSeries]; int index = 0; for (int i=0; i<numSeries; i++) { core[i] = new CoreMetadata(); while (!valid[index]) index++; core[i].imageCount = count[index]; files[i] = tempFiles[index]; Object[] sorted = files[i].toArray(); Arrays.sort(sorted); files[i].clear(); for (int q=0; q<sorted.length; q++) { files[i].add(sorted[q]); } headerIFDs[i] = tempIFDs[index]; index++; } tiff = new MinimalTiffReader(); status("Populating metadata"); if (headerIFDs == null) headerIFDs = ifds; int fileLength = 0; int resolution = -1; String[][] timestamps = new String[headerIFDs.length][]; seriesDescriptions = new Vector(); physicalSizes = new float[headerIFDs.length][5]; pinhole = new float[headerIFDs.length]; exposureTime = new float[headerIFDs.length]; for (int i=0; i<headerIFDs.length; i++) { Object[] keys = headerIFDs[i].keySet().toArray(); Arrays.sort(keys); String prefix = "Series " + i + " "; for (int q=0; q<keys.length; q++) { byte[] tmp = (byte[]) headerIFDs[i].get(keys[q]); if (tmp == null) continue; RandomAccessInputStream stream = new RandomAccessInputStream(tmp); stream.order(isLittleEndian()); if (keys[q].equals(SERIES)) { addMeta(prefix + "Version", stream.readInt()); addMeta(prefix + "Number of Series", stream.readInt()); fileLength = stream.readInt(); addMeta(prefix + "Length of filename", fileLength); int extLen = stream.readInt(); if (extLen > fileLength) { stream.seek(8); core[0].littleEndian = !isLittleEndian(); stream.order(isLittleEndian()); fileLength = stream.readInt(); extLen = stream.readInt(); } addMeta(prefix + "Length of file extension", extLen); addMeta(prefix + "Image file extension", getString(stream, extLen)); } else if (keys[q].equals(IMAGES)) { core[i].imageCount = stream.readInt(); core[i].sizeX = stream.readInt(); core[i].sizeY = stream.readInt(); addMeta(prefix + "Number of images", core[i].imageCount); addMeta(prefix + "Image width", core[i].sizeX); addMeta(prefix + "Image height", core[i].sizeY); addMeta(prefix + "Bits per Sample", stream.readInt()); addMeta(prefix + "Samples per pixel", stream.readInt()); String name = getString(stream, fileLength * 2); if (name.indexOf(".") != -1) { name = name.substring(0, name.lastIndexOf(".")); } String[] tokens = name.split("_"); StringBuffer buf = new StringBuffer(); for (int p=1; p<tokens.length; p++) { String lcase = tokens[p].toLowerCase(); if (!lcase.startsWith("ch0") && !lcase.startsWith("c0") && !lcase.startsWith("z0") && !lcase.startsWith("t0")) { if (buf.length() > 0) buf.append("_"); buf.append(tokens[p]); } } seriesNames.add(buf.toString()); } else if (keys[q].equals(DIMDESCR)) { addMeta(prefix + "Voxel Version", stream.readInt()); core[i].rgb = stream.readInt() == 20; addMeta(prefix + "VoxelType", core[i].rgb ? "RGB" : "gray"); int bpp = stream.readInt(); addMeta(prefix + "Bytes per pixel", bpp); switch (bpp) { case 1: core[i].pixelType = FormatTools.UINT8; break; case 3: core[i].pixelType = FormatTools.UINT8; core[i].sizeC = 3; core[i].rgb = true; break; case 2: core[i].pixelType = FormatTools.UINT16; break; case 6: core[i].pixelType = FormatTools.UINT16; core[i].sizeC = 3; core[i].rgb = true; break; case 4: core[i].pixelType = FormatTools.UINT32; break; default: throw new FormatException("Unsupported bytes per pixel (" + bpp + ")"); } core[i].dimensionOrder = "XY"; resolution = stream.readInt(); addMeta(prefix + "Real world resolution", resolution); addMeta(prefix + "Maximum voxel intensity", getString(stream, true)); addMeta(prefix + "Minimum voxel intensity", getString(stream, true)); int len = stream.readInt(); stream.skipBytes(len * 2 + 4); len = stream.readInt(); for (int j=0; j<len; j++) { int dimId = stream.readInt(); String dimType = (String) dimensionNames.get(new Integer(dimId)); if (dimType == null) dimType = ""; int size = stream.readInt(); int distance = stream.readInt(); int strlen = stream.readInt() * 2; String[] sizeData = getString(stream, strlen).split(" "); String physicalSize = sizeData[0]; String unit = ""; if (sizeData.length > 1) unit = sizeData[1]; float physical = Float.parseFloat(physicalSize) / size; if (unit.equals("m")) { physical *= 1000000; } if (dimType.equals("x")) { core[i].sizeX = size; physicalSizes[i][0] = physical; } else if (dimType.equals("y")) { core[i].sizeY = size; physicalSizes[i][1] = physical; } else if (dimType.indexOf("z") != -1) { core[i].sizeZ = size; if (core[i].dimensionOrder.indexOf("Z") == -1) { core[i].dimensionOrder += "Z"; } physicalSizes[i][2] = physical; } else if (dimType.equals("channel")) { if (core[i].sizeC == 0) core[i].sizeC = 1; core[i].sizeC *= size; if (core[i].dimensionOrder.indexOf("C") == -1) { core[i].dimensionOrder += "C"; } physicalSizes[i][3] = physical; } else { core[i].sizeT = size; if (core[i].dimensionOrder.indexOf("T") == -1) { core[i].dimensionOrder += "T"; } physicalSizes[i][4] = physical; } String dimPrefix = prefix + "Dim" + j; addMeta(dimPrefix + " type", dimType); addMeta(dimPrefix + " size", size); addMeta(dimPrefix + " distance between sub-dimensions", distance); addMeta(dimPrefix + " physical length", physicalSize + " " + unit); addMeta(dimPrefix + " physical origin", getString(stream, true)); } addMeta(prefix + "Series name", getString(stream, false)); String description = getString(stream, false); seriesDescriptions.add(description); addMeta(prefix + "Series description", description); } else if (keys[q].equals(TIMEINFO)) { int nDims = stream.readInt(); addMeta(prefix + "Number of time-stamped dimensions", nDims); addMeta(prefix + "Time-stamped dimension", stream.readInt()); for (int j=0; j<nDims; j++) { String dimPrefix = prefix + "Dimension " + j; addMeta(dimPrefix + " ID", stream.readInt()); addMeta(dimPrefix + " size", stream.readInt()); addMeta(dimPrefix + " distance", stream.readInt()); } int numStamps = stream.readInt(); addMeta(prefix + "Number of time-stamps", numStamps); timestamps[i] = new String[numStamps]; for (int j=0; j<numStamps; j++) { timestamps[i][j] = getString(stream, 64); addMeta(prefix + "Timestamp " + j, timestamps[i][j]); } if (stream.getFilePointer() < stream.length()) { int numTMs = stream.readInt(); addMeta(prefix + "Number of time-markers", numTMs); for (int j=0; j<numTMs; j++) { int numDims = stream.readInt(); String time = "Time-marker " + j + " Dimension "; for (int k=0; k<numDims; k++) { addMeta(prefix + time + k + " coordinate", stream.readInt()); } addMeta(prefix + "Time-marker " + j, getString(stream, 64)); } } } else if (keys[q].equals(EXPERIMENT)) { stream.skipBytes(8); String description = getString(stream, true); addMeta(prefix + "Image Description", description); addMeta(prefix + "Main file extension", getString(stream, true)); addMeta(prefix + "Image format identifier", getString(stream, true)); addMeta(prefix + "Single image extension", getString(stream, true)); } else if (keys[q].equals(LUTDESC)) { int nChannels = stream.readInt(); if (nChannels > 0) core[i].indexed = true; addMeta(prefix + "Number of LUT channels", nChannels); addMeta(prefix + "ID of colored dimension", stream.readInt()); channelMap[i] = new int[nChannels]; String[] luts = new String[nChannels]; for (int j=0; j<nChannels; j++) { String p = prefix + "LUT Channel " + j; addMeta(p + " version", stream.readInt()); addMeta(p + " inverted?", stream.read() == 1); addMeta(p + " description", getString(stream, false)); addMeta(p + " filename", getString(stream, false)); luts[j] = getString(stream, false); addMeta(p + " name", luts[j]); luts[j] = luts[j].toLowerCase(); stream.skipBytes(8); } // finish setting up channel mapping for (int p=0; p<channelMap[i].length; p++) { if (!CHANNEL_PRIORITIES.containsKey(luts[p])) luts[p] = ""; channelMap[i][p] = ((Integer) CHANNEL_PRIORITIES.get(luts[p])).intValue(); } int[] sorted = new int[channelMap[i].length]; Arrays.fill(sorted, -1); for (int p=0; p<sorted.length; p++) { int min = Integer.MAX_VALUE; int minIndex = -1; for (int n=0; n<channelMap[i].length; n++) { if (channelMap[i][n] < min && !DataTools.containsValue(sorted, n)) { min = channelMap[i][n]; minIndex = n; } } sorted[p] = minIndex; } for (int p=0; p<channelMap[i].length; p++) { channelMap[i][sorted[p]] = p; } } stream.close(); } core[i].orderCertain = true; core[i].littleEndian = isLittleEndian(); core[i].falseColor = true; core[i].metadataComplete = true; core[i].interleaved = false; } for (int i=0; i<numSeries; i++) { setSeries(i); if (getSizeZ() == 0) core[i].sizeZ = 1; if (getSizeT() == 0) core[i].sizeT = 1; if (getSizeC() == 0) core[i].sizeC = 1; if (getImageCount() == 0) core[i].imageCount = 1; if (getImageCount() == 1 && getSizeZ() * getSizeT() > 1) { core[i].sizeZ = 1; core[i].sizeT = 1; } if (isRGB()) core[i].indexed = false; if (getDimensionOrder().indexOf("C") == -1) { core[i].dimensionOrder += "C"; } if (getDimensionOrder().indexOf("Z") == -1) { core[i].dimensionOrder += "Z"; } if (getDimensionOrder().indexOf("T") == -1) { core[i].dimensionOrder += "T"; } } MetadataStore store = new FilterMetadata(getMetadataStore(), isMetadataFiltered()); MetadataTools.populatePixels(store, this, true); store.setInstrumentID("Instrument:0", 0); for (int i=0; i<numSeries; i++) { long firstPlane = 0; if (i < timestamps.length && timestamps[i] != null && timestamps[i].length > 0) { SimpleDateFormat parse = new SimpleDateFormat("yyyy:MM:dd,HH:mm:ss:SSS"); Date date = parse.parse(timestamps[i][0], new ParsePosition(0)); firstPlane = date.getTime(); SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); store.setImageCreationDate(fmt.format(date), i); } else { MetadataTools.setDefaultCreationDate(store, id, i); } store.setImageName((String) seriesNames.get(i), i); store.setImageDescription((String) seriesDescriptions.get(i), i); // link Instrument and Image store.setImageInstrumentRef("Instrument:0", i); store.setDimensionsPhysicalSizeX(new Float(physicalSizes[i][0]), i, 0); store.setDimensionsPhysicalSizeY(new Float(physicalSizes[i][1]), i, 0); store.setDimensionsPhysicalSizeZ(new Float(physicalSizes[i][2]), i, 0); if ((int) physicalSizes[i][3] > 0) { store.setDimensionsWaveIncrement( new Integer((int) physicalSizes[i][3]), i, 0); } store.setDimensionsTimeIncrement(new Float(physicalSizes[i][4]), i, 0); // parse instrument data Object[] keys = headerIFDs[i].keySet().toArray(); for (int q=0; q<keys.length; q++) { if (keys[q].equals(FILTERSET) || keys[q].equals(SCANNERSET)) { byte[] tmp = (byte[]) headerIFDs[i].get(keys[q]); if (tmp == null) continue; RandomAccessInputStream stream = new RandomAccessInputStream(tmp); stream.order(isLittleEndian()); parseInstrumentData(stream, store, i); stream.close(); } } for (int j=0; j<core[i].imageCount; j++) { if (timestamps[i] != null && j < timestamps[i].length) { SimpleDateFormat parse = new SimpleDateFormat("yyyy:MM:dd,HH:mm:ss:SSS"); Date date = parse.parse(timestamps[i][j], new ParsePosition(0)); float elapsedTime = (float) (date.getTime() - firstPlane) / 1000; store.setPlaneTimingDeltaT(new Float(elapsedTime), i, 0, j); store.setPlaneTimingExposureTime(new Float(exposureTime[i]), i, 0, j); } } } setSeries(0); } // -- Helper methods -- private void parseInstrumentData(RandomAccessInputStream stream, MetadataStore store, int series) throws IOException { // read 24 byte SAFEARRAY stream.skipBytes(4); int cbElements = stream.readInt(); stream.skipBytes(8); int nElements = stream.readInt(); stream.skipBytes(4); Vector[] channelNames = new Vector[getSeriesCount()]; Vector[] emWaves = new Vector[getSeriesCount()]; Vector[] exWaves = new Vector[getSeriesCount()]; for (int i=0; i<getSeriesCount(); i++) { channelNames[i] = new Vector(); emWaves[i] = new Vector(); exWaves[i] = new Vector(); } for (int j=0; j<nElements; j++) { stream.seek(24 + j * cbElements); String contentID = getString(stream, 128); String description = getString(stream, 64); String data = getString(stream, 64); int dataType = stream.readShort(); stream.skipBytes(6); // read data switch (dataType) { case 2: data = String.valueOf(stream.readShort()); break; case 3: data = String.valueOf(stream.readInt()); break; case 4: data = String.valueOf(stream.readFloat()); break; case 5: data = String.valueOf(stream.readDouble()); break; case 7: case 11: data = stream.read() == 0 ? "false" : "true"; break; case 17: data = stream.readString(1); break; } String[] tokens = contentID.split("\\|"); if (tokens[0].startsWith("CDetectionUnit")) { // detector information if (tokens[1].startsWith("PMT")) { try { int ndx = tokens[1].lastIndexOf(" ") + 1; int detector = Integer.parseInt(tokens[1].substring(ndx)) - 1; store.setDetectorType("Unknown", 0, detector); if (tokens[2].equals("VideoOffset")) { store.setDetectorOffset(new Float(data), 0, detector); } else if (tokens[2].equals("HighVoltage")) { store.setDetectorVoltage(new Float(data), 0, detector); } else if (tokens[2].equals("State")) { // link Detector to Image, if the detector was actually used store.setDetectorID("Detector:" + detector, 0, detector); for (int i=0; i<getSeriesCount(); i++) { if (detector < core[i].sizeC) { store.setDetectorSettingsDetector("Detector:" + detector, i, detector); } } } } catch (NumberFormatException e) { if (debug) trace(e); } } } else if (tokens[0].startsWith("CTurret")) { // objective information int objective = Integer.parseInt(tokens[3]); if (tokens[2].equals("NumericalAperture")) { store.setObjectiveLensNA(new Float(data), 0, objective); } else if (tokens[2].equals("Objective")) { String[] objectiveData = data.split(" "); StringBuffer model = new StringBuffer(); String mag = null, na = null; StringBuffer correction = new StringBuffer(); String immersion = null; for (int i=0; i<objectiveData.length; i++) { if (objectiveData[i].indexOf("x") != -1 && mag == null && na == null) { int xIndex = objectiveData[i].indexOf("x"); mag = objectiveData[i].substring(0, xIndex).trim(); na = objectiveData[i].substring(xIndex + 1).trim(); } else if (mag == null && na == null) { model.append(objectiveData[i]); model.append(" "); } else if (immersion == null) { immersion = objectiveData[i]; } else { correction.append(objectiveData[i]); correction.append(" "); } } if (immersion == null || immersion.trim().equals("")) { immersion = "Unknown"; } store.setObjectiveImmersion(immersion, 0, objective); store.setObjectiveCorrection(correction.toString().trim(), 0, objective); store.setObjectiveModel(model.toString().trim(), 0, objective); store.setObjectiveLensNA(new Float(na), 0, objective); store.setObjectiveNominalMagnification( new Integer((int) Float.parseFloat(mag)), 0, objective); } else if (tokens[2].equals("OrderNumber")) { store.setObjectiveSerialNumber(data, 0, objective); } else if (tokens[2].equals("RefractionIndex")) { store.setObjectiveSettingsRefractiveIndex(new Float(data), series); } // link Objective to Image store.setObjectiveID("Objective:" + objective, 0, objective); if (objective == 0) { store.setObjectiveSettingsObjective("Objective:" + objective, series); store.setImageObjective("Objective:" + objective, series); } } else if (tokens[0].startsWith("CSpectrophotometerUnit")) { int ndx = tokens[1].lastIndexOf(" ") + 1; int channel = Integer.parseInt(tokens[1].substring(ndx)) - 1; if (tokens[2].equals("Wavelength")) { Integer wavelength = new Integer((int) Float.parseFloat(data)); if (tokens[3].equals("0")) { emWaves[series].add(wavelength); } else if (tokens[3].equals("1")) { exWaves[series].add(wavelength); } } else if (tokens[2].equals("Stain")) { channelNames[series].add(data); } } else if (tokens[0].startsWith("CXYZStage")) { // NB: there is only one stage position specified for each series if (tokens[2].equals("XPos")) { for (int q=0; q<core[series].imageCount; q++) { store.setStagePositionPositionX(new Float(data), series, 0, q); } } else if (tokens[2].equals("YPos")) { for (int q=0; q<core[series].imageCount; q++) { store.setStagePositionPositionY(new Float(data), series, 0, q); } } else if (tokens[2].equals("ZPos")) { for (int q=0; q<core[series].imageCount; q++) { store.setStagePositionPositionZ(new Float(data), series, 0, q); } } } if (contentID.equals("dblVoxelX")) { physicalSizes[series][0] = Float.parseFloat(data); } else if (contentID.equals("dblVoxelY")) { physicalSizes[series][1] = Float.parseFloat(data); } else if (contentID.equals("dblVoxelZ")) { physicalSizes[series][2] = Float.parseFloat(data); } else if (contentID.equals("dblPinhole")) { pinhole[series] = Float.parseFloat(data); } else if (contentID.equals("dblZoom")) { store.setDisplayOptionsZoom(new Float(data), series); } else if (contentID.startsWith("nDelayTime")) { exposureTime[series] = Float.parseFloat(data); if (contentID.endsWith("_ms")) { exposureTime[series] /= 1000f; } } addMeta("Series " + series + " " + contentID, data); } stream.close(); // populate saved LogicalChannel data for (int i=0; i<getSeriesCount(); i++) { int nextChannel = 0; for (int channel=0; channel<getEffectiveSizeC(); channel++) { if (channel >= channelNames[i].size()) break; String name = (String) channelNames[i].get(channel); if (name == null || name.trim().equals("")) continue; store.setLogicalChannelName(name, i, nextChannel); store.setLogicalChannelEmWave((Integer) emWaves[i].get(channel), i, nextChannel); store.setLogicalChannelExWave((Integer) exWaves[i].get(channel), i, nextChannel); store.setLogicalChannelPinholeSize(new Float(pinhole[i]), i, nextChannel); nextChannel++; } } } private boolean usedFile(String s) { if (files == null) return false; for (int i=0; i<files.length; i++) { if (files[i] == null) continue; for (int j=0; j<files[i].size(); j++) { if (((String) files[i].get(j)).endsWith(s)) return true; } } return false; } private String getString(RandomAccessInputStream stream, int len) throws IOException { return DataTools.stripString(stream.readString(len)); } private String getString(RandomAccessInputStream stream, boolean doubleLength) throws IOException { int len = stream.readInt(); if (doubleLength) len *= 2; return getString(stream, len); } private static Hashtable makeDimensionTable() { Hashtable table = new Hashtable(); table.put(new Integer(0), "undefined"); table.put(new Integer(120), "x"); table.put(new Integer(121), "y"); table.put(new Integer(122), "z"); table.put(new Integer(116), "t"); table.put(new Integer(6815843), "channel"); table.put(new Integer(6357100), "wave length"); table.put(new Integer(7602290), "rotation"); table.put(new Integer(7798904), "x-wide for the motorized xy-stage"); table.put(new Integer(7798905), "y-wide for the motorized xy-stage"); table.put(new Integer(7798906), "z-wide for the z-stage-drive"); table.put(new Integer(4259957), "user1 - unspecified"); table.put(new Integer(4325493), "user2 - unspecified"); table.put(new Integer(4391029), "user3 - unspecified"); table.put(new Integer(6357095), "graylevel"); table.put(new Integer(6422631), "graylevel1"); table.put(new Integer(6488167), "graylevel2"); table.put(new Integer(6553703), "graylevel3"); table.put(new Integer(7864398), "logical x"); table.put(new Integer(7929934), "logical y"); table.put(new Integer(7995470), "logical z"); table.put(new Integer(7602254), "logical t"); table.put(new Integer(7077966), "logical lambda"); table.put(new Integer(7471182), "logical rotation"); table.put(new Integer(5767246), "logical x-wide"); table.put(new Integer(5832782), "logical y-wide"); table.put(new Integer(5898318), "logical z-wide"); return table; } }
Adjust image count if an XZ or XT scan is found.
components/bio-formats/src/loci/formats/in/LeicaReader.java
Adjust image count if an XZ or XT scan is found.
<ide><path>omponents/bio-formats/src/loci/formats/in/LeicaReader.java <ide> if (getImageCount() == 1 && getSizeZ() * getSizeT() > 1) { <ide> core[i].sizeZ = 1; <ide> core[i].sizeT = 1; <add> } <add> if (getSizeY() == 1) { <add> // XZ or XT scan <add> if (getSizeZ() > 1 && getImageCount() == getSizeC() * getSizeT()) { <add> core[i].sizeY = getSizeZ(); <add> core[i].sizeZ = 1; <add> } <add> else if (getSizeT() > 1 && getImageCount() == getSizeC() * getSizeZ()) { <add> core[i].sizeY = getSizeT(); <add> core[i].sizeT = 1; <add> } <ide> } <ide> if (isRGB()) core[i].indexed = false; <ide>
Java
apache-2.0
e61242e8a41a2aeceb7ddb0e571cd7309fa42cfa
0
interpss/DeepMachineLearning,interpss/DeepMachineLearning
/* * @(#)AclfFuncTest.java * * Copyright (C) 2006-2014 www.interpss.org * 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. * * @Author Mike Zhou * @Version 1.0 * @Date 04/05/2017 * * Revision History * ================ * */ package test; import static org.junit.Assert.assertTrue; import org.interpss.IpssCorePlugin; import org.interpss.service.UtilFunction; import org.interpss.service.train_data.ITrainCaseBuilder; import org.junit.Test; import com.interpss.common.exp.InterpssException; import com.interpss.core.datatype.Mismatch; public class AclfFuncSingleNetTest { @Test public void testSingleNet() throws InterpssException { IpssCorePlugin.init(); ITrainCaseBuilder caseBuilder = UtilFunction.createSingleNetBuilder( "testdata/ieee14.ieee", "BusVoltageTrainCaseBuilder"); // at this point, the caseBuilder.loadConfigureAclfNet() has been called and the // base case bus data has been cached /* System.out.println(caseBuilder.getBaseCaseData()[0]); System.out.println(caseBuilder.getBaseCaseData()[2]); System.out.println(caseBuilder.getBaseCaseData()[10]); BusData: Bus1, 0, 0.0, 0.0 BusData: Bus3, 1, 0.0, 0.0 BusData: Bus11, 2, 0.035, 0.018 */ ITrainCaseBuilder.BusData busdata = caseBuilder.getBaseCaseData()[0]; assertTrue("", busdata.id.equals("Bus1")); assertTrue("", busdata.type == ITrainCaseBuilder.BusData.Swing); busdata = caseBuilder.getBaseCaseData()[2]; assertTrue("", busdata.id.equals("Bus3")); assertTrue("", busdata.type == ITrainCaseBuilder.BusData.PV); busdata = caseBuilder.getBaseCaseData()[10]; assertTrue("", busdata.id.equals("Bus11")); assertTrue("", busdata.type == ITrainCaseBuilder.BusData.PQ); assertTrue("", busdata.loadP == 0.035); assertTrue("", busdata.loadQ == 0.018); caseBuilder.createTestCase(); double[] netVolt = caseBuilder.getNetOutput(); Mismatch mis = caseBuilder.calMismatch(netVolt); assertTrue("netVolt is a Loadflow solution, therefore the mismatch should be very small! ", mis.maxMis.abs() < 0.0001); //System.out.println(caseBuilder.calMismatch(netVolt)); } @Test public void testSingleNet1() throws InterpssException { IpssCorePlugin.init(); ITrainCaseBuilder caseBuilder = UtilFunction.createSingleNetBuilder("testdata/ieee14.ieee", "BusVoltageTrainCaseBuilder", "c:/temp/temp/ieee14_busid2no.mapping", "c:/temp/temp/ieee14_branchid2no.mapping"); caseBuilder.createTestCase(); double[] netVolt = caseBuilder.getNetOutput(); assertTrue("The length is decided by the info in the mapping file", netVolt.length == 15*2); Mismatch mis = caseBuilder.calMismatch(netVolt); assertTrue("netVolt is a Loadflow solution, therefore the mismatch should be very small! ", mis.maxMis.abs() < 0.0001); //System.out.println(caseBuilder.calMismatch(netVolt)); } @Test public void testSingleNet_NNLF() throws InterpssException { IpssCorePlugin.init(); ITrainCaseBuilder caseBuilder = UtilFunction.createSingleNetBuilder( "testdata/ieee14.ieee", "NNLFLoadChangeTrainCaseBuilder"); caseBuilder.createTestCase(); double[] netVolt = caseBuilder.getNetOutput(); Mismatch mis = caseBuilder.calMismatch(netVolt); System.out.println("--->" + caseBuilder.calMismatch(netVolt)); assertTrue("netVolt is a Loadflow solution, therefore the mismatch should be very small! ", mis.maxMis.abs() < 0.0001); } }
ipss.dml/src/test/AclfFuncSingleNetTest.java
/* * @(#)AclfFuncTest.java * * Copyright (C) 2006-2014 www.interpss.org * 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. * * @Author Mike Zhou * @Version 1.0 * @Date 04/05/2017 * * Revision History * ================ * */ package test; import static org.junit.Assert.assertTrue; import org.interpss.IpssCorePlugin; import org.interpss.service.UtilFunction; import org.interpss.service.train_data.ITrainCaseBuilder; import org.junit.Test; import com.interpss.common.exp.InterpssException; import com.interpss.core.datatype.Mismatch; public class AclfFuncSingleNetTest { @Test public void testSingleNet() throws InterpssException { IpssCorePlugin.init(); ITrainCaseBuilder caseBuilder = UtilFunction.createSingleNetBuilder( "testdata/ieee14.ieee", "BusVoltageTrainCaseBuilder"); // at this point, the caseBuilder.loadConfigureAclfNet() has been called and the // base case bus data has been cached /* System.out.println(caseBuilder.getBaseCaseData()[0]); System.out.println(caseBuilder.getBaseCaseData()[2]); System.out.println(caseBuilder.getBaseCaseData()[10]); BusData: Bus1, 0, 0.0, 0.0 BusData: Bus3, 1, 0.0, 0.0 BusData: Bus11, 2, 0.035, 0.018 */ ITrainCaseBuilder.BusData busdata = caseBuilder.getBaseCaseData()[0]; assertTrue("", busdata.id.equals("Bus1")); assertTrue("", busdata.type == ITrainCaseBuilder.BusData.Swing); busdata = caseBuilder.getBaseCaseData()[2]; assertTrue("", busdata.id.equals("Bus3")); assertTrue("", busdata.type == ITrainCaseBuilder.BusData.PV); busdata = caseBuilder.getBaseCaseData()[10]; assertTrue("", busdata.id.equals("Bus11")); assertTrue("", busdata.type == ITrainCaseBuilder.BusData.PQ); assertTrue("", busdata.loadP == 0.035); assertTrue("", busdata.loadQ == 0.018); caseBuilder.createTestCase(); double[] netVolt = caseBuilder.getNetOutput(); Mismatch mis = caseBuilder.calMismatch(netVolt); assertTrue("netVolt is a Loadflow solution, therefore the mismatch should be very small! ", mis.maxMis.abs() < 0.0001); //System.out.println(caseBuilder.calMismatch(netVolt)); } @Test public void testSingleNet1() throws InterpssException { IpssCorePlugin.init(); ITrainCaseBuilder caseBuilder = UtilFunction.createSingleNetBuilder("testdata/ieee14.ieee", "BusVoltageTrainCaseBuilder", "c:/temp/temp/ieee14_busid2no.mapping", "c:/temp/temp/ieee14_branchid2no.mapping"); caseBuilder.createTestCase(); double[] netVolt = caseBuilder.getNetOutput(); assertTrue("The length is decided by the info in the mapping file", netVolt.length == 15*2); Mismatch mis = caseBuilder.calMismatch(netVolt); assertTrue("netVolt is a Loadflow solution, therefore the mismatch should be very small! ", mis.maxMis.abs() < 0.0001); //System.out.println(caseBuilder.calMismatch(netVolt)); } @Test public void testSingleNet_NNLF() throws InterpssException { IpssCorePlugin.init(); ITrainCaseBuilder caseBuilder = UtilFunction.createSingleNetBuilder( "testdata/ieee14.ieee", "NNLFLoadChangeTrainCaseBuilder"); caseBuilder.createTestCase(); double[] netVolt = caseBuilder.getNetOutput(); Mismatch mis = caseBuilder.calMismatch(netVolt); assertTrue("netVolt is a Loadflow solution, therefore the mismatch should be very small! ", mis.maxMis.abs() < 0.0001); //System.out.println(caseBuilder.calMismatch(netVolt)); } }
updated the test case
ipss.dml/src/test/AclfFuncSingleNetTest.java
updated the test case
<ide><path>pss.dml/src/test/AclfFuncSingleNetTest.java <ide> double[] netVolt = caseBuilder.getNetOutput(); <ide> <ide> Mismatch mis = caseBuilder.calMismatch(netVolt); <add> System.out.println("--->" + caseBuilder.calMismatch(netVolt)); <ide> assertTrue("netVolt is a Loadflow solution, therefore the mismatch should be very small! ", <ide> mis.maxMis.abs() < 0.0001); <del> //System.out.println(caseBuilder.calMismatch(netVolt)); <ide> } <ide> <ide> }
JavaScript
mit
5c167e7598d625517a8825d8c1dda3c39be00b57
0
Flexberry/ember-flexberry,Flexberry/ember-flexberry,Flexberry/ember-flexberry,Flexberry/ember-flexberry
import { Model as <%= className %>Mixin<%if (projections) {%>, defineProjections<%}%> } from '../mixins/regenerated/models/<%= name %>'; import <%if(parentModelName) {%><%= parentClassName %>Model from './<%= parentModelName %>';<%}else{%>{ Projection } from 'ember-flexberry-data';<%}%> let Model = <%if(parentModelName) {%><%= parentClassName %>Model.extend<%}else{%>Projection.Model.extend<%}%>(<%= className %>Mixin, { }); <%if(parentModelName) {%>Model.reopenClass({ _parentModelName: '<%= parentModelName %>' });<%}%> <%if(projections) {%>defineProjections(Model);<%}%> export default Model;
blueprints/flexberry-model-init/files/__root__/models/__name__.js
import { Model as <%= className %>Mixin<%if (projections) {%>, defineProjections<%}%> } from '../mixins/regenerated/models/<%= name %>'; import <%if(parentModelName) {%><%= parentClassName %>Model from './<%= parentModelName %>';<%}else{%>{ Projection } from 'ember-flexberry-data';<%}%> let Model = <%if(parentModelName) {%><%= parentClassName %>Model.extend<%}else{%>Projection.Model.extend<%}%>(<%= className %>Mixin, { }); <%if(projections) {%>defineProjections(Model);<%}%> export default Model;
Add generation of parent models definitions
blueprints/flexberry-model-init/files/__root__/models/__name__.js
Add generation of parent models definitions
<ide><path>lueprints/flexberry-model-init/files/__root__/models/__name__.js <ide> let Model = <%if(parentModelName) {%><%= parentClassName %>Model.extend<%}else{%>Projection.Model.extend<%}%>(<%= className %>Mixin, { <ide> <ide> }); <add><%if(parentModelName) {%>Model.reopenClass({ <add> _parentModelName: '<%= parentModelName %>' <add>});<%}%> <ide> <%if(projections) {%>defineProjections(Model);<%}%> <ide> export default Model;
Java
agpl-3.0
97c670a259b379009355c5055d92dc24b5358913
0
ngaut/sql-layer,wfxiang08/sql-layer-1,jaytaylor/sql-layer,qiuyesuifeng/sql-layer,ngaut/sql-layer,jaytaylor/sql-layer,relateiq/sql-layer,qiuyesuifeng/sql-layer,qiuyesuifeng/sql-layer,ngaut/sql-layer,qiuyesuifeng/sql-layer,relateiq/sql-layer,relateiq/sql-layer,jaytaylor/sql-layer,jaytaylor/sql-layer,shunwang/sql-layer-1,shunwang/sql-layer-1,ngaut/sql-layer,wfxiang08/sql-layer-1,shunwang/sql-layer-1,wfxiang08/sql-layer-1,wfxiang08/sql-layer-1,relateiq/sql-layer,shunwang/sql-layer-1
package com.foundationdb.sql.parser; import org.hamcrest.core.StringEndsWith; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.FieldVisitor; import org.objectweb.asm.Handle; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.reflections.Reflections; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeSet; import static org.hamcrest.Matchers.empty; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; public class CheckParserUsagesIT { private static Set<Class<? extends QueryTreeNode>> queryTreeNodes; private static Collection<String> sqlLayerClassPaths; private PropertyFinder finder; @BeforeClass public static void getParserClasses() { Reflections reflections = new Reflections("com.foundationdb.sql.parser"); queryTreeNodes = reflections.getSubTypesOf(QueryTreeNode.class); // Note: queryTreeNode is not counted here. } @BeforeClass public static void getSqlLayerClassNames() throws Exception { sqlLayerClassPaths = getClassesInPackage("com.foundationdb.sql", "com.foundationdb.sql.Main"); System.out.println(sqlLayerClassPaths); } private static Collection<String> getClassesInPackage(String packageName, String sampleClass) { String sampleClassPathSuffix = sampleClass.replaceAll("\\.", "/") + ".class"; String sampleClassPath = CheckParserUsagesIT.class.getClassLoader().getResource(sampleClassPathSuffix).getPath(); assertThat(sampleClassPath, new StringEndsWith(sampleClassPathSuffix)); String packagePath = sampleClassPath.substring(0,sampleClassPath.length()-sampleClassPathSuffix.length()) + packageName.replaceAll("\\.", "/"); return getAllClassesInDirectory(new File(packagePath)); } private static Collection<String> getAllClassesInDirectory(File directory) { Collection<String> result = new HashSet<>(); for (File file : directory.listFiles()) { if (file.isDirectory()) { result.addAll(getAllClassesInDirectory(file)); } else if (file.isFile() && file.getName().endsWith(".class")) { result.add(file.getAbsolutePath()); } } return result; } @Before public void initializeFinder() { finder = new PropertyFinder(); for (Class<? extends QueryTreeNode> nodeClass : queryTreeNodes) { try { ClassReader reader = new ClassReader(nodeClass.getName()); reader.accept(finder, 0); } catch (IOException e) { System.err.println("Could not open class to scan: " + nodeClass.getName()); System.exit(1); } } // Remove any base class methods here, before they get propagated down finder.getNodes().get("com/foundationdb/sql/parser/DDLStatementNode") .removeMethod("getRelativeName", "()Ljava/lang/String;") .removeMethod("getFullName", "()Ljava/lang/String;"); finder.finalizeState(); // Remove any concrete class methods here, base class methods have already been propagated down } @Test public void testAllReferencedClassesHaveReferencedGetters() { PropertyChecker checker = new PropertyChecker(finder.getNodes()); int fullyUsed = 0; int total = 0; Iterator<Map.Entry<String, NodeClass>> iterator = finder.getNodes().entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, NodeClass> nodeClass = iterator.next(); if (nodeClass.getValue().fullyUsed()) { fullyUsed++; iterator.remove(); } total++; } assertTrue(fullyUsed + " < " + total, fullyUsed < total); System.out.println(fullyUsed + " / " + total); for (String usageClass : sqlLayerClassPaths) { try { ClassReader reader = new ClassReader(new FileInputStream(usageClass)); reader.accept(checker, 0); } catch (IOException e) { System.err.println("Failed to check against class"); e.printStackTrace(); System.exit(1); } } int fullyUsed2 = 0; Collection<String> unused = new TreeSet<>(); System.out.println("DeclaredType,SubType,PropertyType,Name,Java Declaration,Code To Remove"); for (NodeClass nodeClass : finder.getNodes().values()) { if (!nodeClass.fullyUsed()) { if (nodeClass.isReferenced && nodeClass.isConcrete()) { String name = nodeClass.getJavaName(); for (String field : nodeClass.fields) { unused.add(name + "." + field); // technically incorrect, not checking for public field inheritance here System.out.println(nodeClass.name + "," + name + ",FIELD," + field); } for (NodeClass.Method method : nodeClass.methods) { unused.add(method.getJavaString(name) + " -- " + method.descriptor); System.out.println(method.className + "," + name + ",METHOD," + method.name + ",\"" + method.getJavaString(null) + "\",\"" + ".removeMethod(\"\"" + method.name + "\"\", \"\"" + method.descriptor + ")\""); } } } else { fullyUsed2++; } } System.out.println("Unused: " + unused.size()); assertThat(unused, empty()); } public static class PropertyFinder extends ClassVisitor { private Map<String, NodeClass> nodes; private NodeClass currentClass; public PropertyFinder() { super(Opcodes.ASM5); nodes = new HashMap<>(); } public Map<String, NodeClass> getNodes() { return nodes; } @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { currentClass = new NodeClass(name, superName, (access & Opcodes.ACC_ABSTRACT) > 0, (access & Opcodes.ACC_INTERFACE) > 0); nodes.put(name, currentClass); } @Override public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { currentClass.addField(access, name); return null; } @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { currentClass.addMethod(access, name, desc); return null; } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); for (NodeClass node : nodes.values()) { stringBuilder.append(node.toString()); stringBuilder.append("\n"); } return stringBuilder.toString(); } public void finalizeState() { for (NodeClass nodeClass : nodes.values()) { nodeClass.incorporateBaseClass(nodes); } } } public static class PropertyChecker extends ClassVisitor{ private Map<String, NodeClass> nodes; public PropertyChecker(Map<String, NodeClass> nodes) { super(Opcodes.ASM5); this.nodes = nodes; } private void markNodesAsVisited(String descriptor, int maxCount) { Collection<String> referencedTypes = getParameterAndReturnTypes(descriptor); assertTrue("Expected Less than " + maxCount + ", but got: " + referencedTypes.size(), referencedTypes.size() < maxCount); for (String referencedType : referencedTypes) { if (nodes.containsKey(referencedType)) { nodes.get(referencedType).reference(); } } } @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { if (nodes.containsKey(superName)) { throw new RuntimeException("Class " + name + " extends " + superName); } } @Override public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { markNodesAsVisited(desc, 1); return null; } @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { markNodesAsVisited(desc, Integer.MAX_VALUE); return new UsageMethodVisitor(); } private Collection<String> getParameterAndReturnTypes(String descriptor) { // TODO return new ArrayList<>(); } private class UsageMethodVisitor extends MethodVisitor{ public UsageMethodVisitor() { super(Opcodes.ASM5); } @Override public void visitInvokeDynamicInsn(String name, String desc, Handle bsm, Object... bsmArgs) { throw new RuntimeException("Unexpected Dynamic Instruction " + name); } @Override public void visitFieldInsn(int opcode, String owner, String name, String desc) { if (nodes.containsKey(owner)) { nodes.get(owner).usedField(name); System.out.println("FIELD: " + owner + "." + name + " " + desc); } } @Override public void visitLocalVariable(String name, String desc, String signature, Label start, Label end, int index) { markNodesAsVisited(desc, 1); } @Override public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) { if (nodes.containsKey(owner)) { nodes.get(owner).usedMethod(name, desc); } } @Override public void visitMethodInsn(int opcode, String owner, String name, String desc) { this.visitMethodInsn(opcode, owner, name, desc, false); } @Override public void visitTypeInsn(int opcode, String type) { if (nodes.containsKey(type)) { nodes.get(type).reference(); } } } } public static class NodeClass { public String name; public String baseClassName; public NodeClass baseClass; public Set<String> fields; private Set<Method> methods; private boolean isAbstract; private boolean isInterface; private boolean isReferenced; public NodeClass(String name, String baseClassName, boolean isAbstract, boolean isInterface) { this.name = name; this.baseClassName = baseClassName; this.isAbstract = isAbstract; this.isInterface = isInterface; fields = new HashSet<>(); methods = new HashSet<>(); } public String getName() { return name; } public String getJavaName() { return name.replaceAll("/", "."); } public String getBaseClassName() { return baseClassName; } public NodeClass getBaseClass() { return baseClass; } public void addField(int access, String fieldName) { if ((access & Opcodes.ACC_PUBLIC) > 0) { if ((access & Opcodes.ACC_STATIC) == 0) { fields.add(fieldName); System.out.println("WARNING " + getJavaName() + " has a public field: " + fieldName); } } } public Method addMethod(int access, String name, String descriptor) { if ((access & Opcodes.ACC_PUBLIC) > 0) { if ((access & Opcodes.ACC_STATIC) == 0) { if (name.startsWith("get")) { Method method = new Method(this.name, name, descriptor); methods.add(method); return method; } } } return null; } public void incorporateBaseClass(Map<String, NodeClass> nodeClasses) { if (baseClass == null) { if (nodeClasses.containsKey(baseClassName)) { baseClass = nodeClasses.get(baseClassName); baseClass.incorporateBaseClass(nodeClasses); fields.addAll(baseClass.fields); methods.addAll(baseClass.methods); } } } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(getJavaName()); stringBuilder.append(": "); for (String field : fields) { stringBuilder.append(field); stringBuilder.append(", "); } for (Method method: methods) { stringBuilder.append(method); stringBuilder.append(", "); } return stringBuilder.toString(); } public void usedMethod(String name, String desc) { if (name.startsWith("get")) { removeMethod(name, desc); } } public void usedField(String name) { fields.remove(name); } public boolean fullyUsed() { return methods.size() == 0 && fields.size() == 0; } public void reference() { isReferenced = true; } public NodeClass removeMethod(String name, String descriptor) { Iterator<Method> iterator = methods.iterator(); while (iterator.hasNext()) { if (iterator.next().equals(name, descriptor)) { iterator.remove(); break; } } return this; } public boolean isConcrete() { return !isAbstract && !isInterface; } public static class Method { private final String descriptor; private final String className; private String name; public Method(String className, String name, String descriptor) { this.className = className; this.name = name; this.descriptor = descriptor; } @Override public String toString() { return name + " " + descriptor; } @Override public boolean equals(Object obj) { if (obj instanceof Method) { Method method = (Method) obj; return method.name.equals(this.name) && method.descriptor.equals(this.descriptor); } return false; } public boolean equals(String name, String descriptor) { return this.name.equals(name) && this.descriptor.equals(descriptor); } public String getJavaString(String className) { StringBuilder stringBuilder = new StringBuilder(); Type type = Type.getType(descriptor); stringBuilder.append(typeToString(type.getReturnType())); stringBuilder.append(" "); if (className != null) { stringBuilder.append(className); stringBuilder.append("."); } stringBuilder.append(name); stringBuilder.append("("); for (Type argumentType : type.getArgumentTypes()) { stringBuilder.append(typeToString(argumentType)); stringBuilder.append(", "); } if (type.getArgumentTypes().length > 0) { stringBuilder.delete(stringBuilder.length() - 2, stringBuilder.length() - 1); } stringBuilder.append(")"); return stringBuilder.toString(); } private String typeToString(Type type) { String className = type.getClassName(); if (type.getSort() == Type.OBJECT) { className = className.substring(className.lastIndexOf('.')+1); } return className; } } } }
src/test/java/com/foundationdb/sql/parser/CheckParserUsagesIT.java
package com.foundationdb.sql.parser; import org.hamcrest.core.StringEndsWith; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.FieldVisitor; import org.objectweb.asm.Handle; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.reflections.Reflections; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeSet; import static org.hamcrest.Matchers.empty; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; public class CheckParserUsagesIT { private static Set<Class<? extends QueryTreeNode>> queryTreeNodes; private static Collection<String> sqlLayerClassPaths; private PropertyFinder finder; @BeforeClass public static void getParserClasses() { Reflections reflections = new Reflections("com.foundationdb.sql.parser"); queryTreeNodes = reflections.getSubTypesOf(QueryTreeNode.class); // Note: queryTreeNode is not counted here. } @BeforeClass public static void getSqlLayerClassNames() throws Exception { sqlLayerClassPaths = getClassesInPackage("com.foundationdb.sql", "com.foundationdb.sql.Main"); System.out.println(sqlLayerClassPaths); } private static Collection<String> getClassesInPackage(String packageName, String sampleClass) { String sampleClassPathSuffix = sampleClass.replaceAll("\\.", "/") + ".class"; String sampleClassPath = CheckParserUsagesIT.class.getClassLoader().getResource(sampleClassPathSuffix).getPath(); assertThat(sampleClassPath, new StringEndsWith(sampleClassPathSuffix)); String packagePath = sampleClassPath.substring(0,sampleClassPath.length()-sampleClassPathSuffix.length()) + packageName.replaceAll("\\.", "/"); return getAllClassesInDirectory(new File(packagePath)); } private static Collection<String> getAllClassesInDirectory(File directory) { Collection<String> result = new HashSet<>(); for (File file : directory.listFiles()) { if (file.isDirectory()) { result.addAll(getAllClassesInDirectory(file)); } else if (file.isFile() && file.getName().endsWith(".class")) { result.add(file.getAbsolutePath()); } } return result; } @Before public void initializeFinder() { finder = new PropertyFinder(); for (Class<? extends QueryTreeNode> nodeClass : queryTreeNodes) { try { ClassReader reader = new ClassReader(nodeClass.getName()); reader.accept(finder, 0); } catch (IOException e) { System.err.println("Could not open class to scan: " + nodeClass.getName()); System.exit(1); } } // Remove any base class methods here, before they get propagated down finder.getNodes().get("com/foundationdb/sql/parser/DDLStatementNode") .removeMethod("getRelativeName", "()Ljava/lang/String;") .removeMethod("getFullName", "()Ljava/lang/String;"); finder.finalizeState(); // Remove any concrete class methods here, base class methods have already been propagated down } @Test public void testAllReferencedClassesHaveReferencedGetters() { PropertyChecker checker = new PropertyChecker(finder.getNodes()); int fullyUsed = 0; int total = 0; Iterator<Map.Entry<String, NodeClass>> iterator = finder.getNodes().entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, NodeClass> nodeClass = iterator.next(); if (nodeClass.getValue().fullyUsed()) { fullyUsed++; iterator.remove(); } total++; } assertTrue(fullyUsed + " < " + total, fullyUsed < total); System.out.println(fullyUsed + " / " + total); for (String usageClass : sqlLayerClassPaths) { try { ClassReader reader = new ClassReader(new FileInputStream(usageClass)); reader.accept(checker, 0); } catch (IOException e) { System.err.println("Failed to check against class"); e.printStackTrace(); System.exit(1); } } int fullyUsed2 = 0; Collection<String> unused = new TreeSet<>(); for (NodeClass nodeClass : finder.getNodes().values()) { if (!nodeClass.fullyUsed()) { if (nodeClass.isReferenced && nodeClass.isConcrete()) { String name = nodeClass.getJavaName(); System.out.println(name.substring(name.lastIndexOf('.')+1)); for (String field : nodeClass.fields) { unused.add(name + "." + field); System.out.println(" " + field); } for (NodeClass.Method method : nodeClass.methods) { unused.add(method.getJavaString(name) + " -- " + method.descriptor); System.out.println(" " + method.getJavaString(null) + " -- " + ".removeMethod(\"" + method.name + "\", \"" + method.descriptor + "\")"); } } } else { fullyUsed2++; } } System.out.println("Unused: " + unused.size()); assertThat(unused, empty()); } public static class PropertyFinder extends ClassVisitor { private Map<String, NodeClass> nodes; private NodeClass currentClass; public PropertyFinder() { super(Opcodes.ASM5); nodes = new HashMap<>(); } public Map<String, NodeClass> getNodes() { return nodes; } @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { currentClass = new NodeClass(name, superName, (access & Opcodes.ACC_ABSTRACT) > 0, (access & Opcodes.ACC_INTERFACE) > 0); nodes.put(name, currentClass); } @Override public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { currentClass.addField(access, name); return null; } // TODO add interface & base class methods @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { currentClass.addMethod(access, name, desc); return null; } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); for (NodeClass node : nodes.values()) { stringBuilder.append(node.toString()); stringBuilder.append("\n"); } return stringBuilder.toString(); } public void finalizeState() { for (NodeClass nodeClass : nodes.values()) { nodeClass.incorporateBaseClass(nodes); } } } public static class PropertyChecker extends ClassVisitor{ private Map<String, NodeClass> nodes; public PropertyChecker(Map<String, NodeClass> nodes) { super(Opcodes.ASM5); this.nodes = nodes; } private void markNodesAsVisited(String descriptor, int maxCount) { Collection<String> referencedTypes = getParameterAndReturnTypes(descriptor); assertTrue("Expected Less than " + maxCount + ", but got: " + referencedTypes.size(), referencedTypes.size() < maxCount); for (String referencedType : referencedTypes) { if (nodes.containsKey(referencedType)) { nodes.get(referencedType).reference(); } } } @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { if (nodes.containsKey(superName)) { throw new RuntimeException("Class " + name + " extends " + superName); } } @Override public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { markNodesAsVisited(desc, 1); return null; } @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { markNodesAsVisited(desc, Integer.MAX_VALUE); return new UsageMethodVisitor(); } private Collection<String> getParameterAndReturnTypes(String descriptor) { // TODO return new ArrayList<>(); } private class UsageMethodVisitor extends MethodVisitor{ public UsageMethodVisitor() { super(Opcodes.ASM5); } @Override public void visitInvokeDynamicInsn(String name, String desc, Handle bsm, Object... bsmArgs) { throw new RuntimeException("Unexpected Dynamic Instruction " + name); } @Override public void visitFieldInsn(int opcode, String owner, String name, String desc) { if (nodes.containsKey(owner)) { nodes.get(owner).usedField(name); System.out.println("FIELD: " + owner + "." + name + " " + desc); } } @Override public void visitLocalVariable(String name, String desc, String signature, Label start, Label end, int index) { markNodesAsVisited(desc, 1); } @Override public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) { if (nodes.containsKey(owner)) { nodes.get(owner).usedMethod(name, desc); } } @Override public void visitMethodInsn(int opcode, String owner, String name, String desc) { this.visitMethodInsn(opcode, owner, name, desc, false); } @Override public void visitTypeInsn(int opcode, String type) { if (nodes.containsKey(type)) { nodes.get(type).reference(); } } } } public static class NodeClass { public String name; public String baseClassName; public NodeClass baseClass; public Set<String> fields; private Set<Method> methods; private boolean isAbstract; private boolean isInterface; private boolean isReferenced; public NodeClass(String name, String baseClassName, boolean isAbstract, boolean isInterface) { this.name = name; this.baseClassName = baseClassName; this.isAbstract = isAbstract; this.isInterface = isInterface; fields = new HashSet<>(); methods = new HashSet<>(); } public String getName() { return name; } public String getJavaName() { return name.replaceAll("/", "."); } public String getBaseClassName() { return baseClassName; } public NodeClass getBaseClass() { return baseClass; } public void addField(int access, String fieldName) { if ((access & Opcodes.ACC_PUBLIC) > 0) { if ((access & Opcodes.ACC_STATIC) == 0) { fields.add(fieldName); System.out.println("WARNING " + getJavaName() + " has a public field: " + fieldName); } } } public Method addMethod(int access, String name, String descriptor) { if ((access & Opcodes.ACC_PUBLIC) > 0) { if ((access & Opcodes.ACC_STATIC) == 0) { if (name.startsWith("get")) { Method method = new Method(name, descriptor); methods.add(method); return method; } } } return null; } public void incorporateBaseClass(Map<String, NodeClass> nodeClasses) { if (baseClass == null) { if (nodeClasses.containsKey(baseClassName)) { baseClass = nodeClasses.get(baseClassName); baseClass.incorporateBaseClass(nodeClasses); fields.addAll(baseClass.fields); methods.addAll(baseClass.methods); } } } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(getJavaName()); stringBuilder.append(": "); for (String field : fields) { stringBuilder.append(field); stringBuilder.append(", "); } for (Method method: methods) { stringBuilder.append(method); stringBuilder.append(", "); } return stringBuilder.toString(); } public void usedMethod(String name, String desc) { if (name.startsWith("get")) { removeMethod(name, desc); } } public void usedField(String name) { fields.remove(name); } public boolean fullyUsed() { return methods.size() == 0 && fields.size() == 0; } public void reference() { isReferenced = true; } public NodeClass removeMethod(String name, String descriptor) { Iterator<Method> iterator = methods.iterator(); while (iterator.hasNext()) { if (iterator.next().equals(name, descriptor)) { iterator.remove(); break; } } return this; } public boolean isConcrete() { return !isAbstract && !isInterface; } public static class Method { private final String descriptor; private String name; public Method(String name, String descriptor) { this.name = name; this.descriptor = descriptor; } @Override public String toString() { return name + " " + descriptor; } @Override public boolean equals(Object obj) { if (obj instanceof Method) { Method method = (Method) obj; return method.name.equals(this.name) && method.descriptor.equals(this.descriptor); } return false; } public boolean equals(String name, String descriptor) { return this.name.equals(name) && this.descriptor.equals(descriptor); } public String getJavaString(String className) { StringBuilder stringBuilder = new StringBuilder(); Type type = Type.getType(descriptor); stringBuilder.append(typeToString(type.getReturnType())); stringBuilder.append(" "); if (className != null) { stringBuilder.append(className); stringBuilder.append("."); } stringBuilder.append(name); stringBuilder.append("("); for (Type argumentType : type.getArgumentTypes()) { stringBuilder.append(typeToString(argumentType)); stringBuilder.append(", "); } if (type.getArgumentTypes().length > 0) { stringBuilder.delete(stringBuilder.length() - 2, stringBuilder.length() - 1); } stringBuilder.append(")"); return stringBuilder.toString(); } private String typeToString(Type type) { String className = type.getClassName(); if (type.getSort() == Type.OBJECT) { className = className.substring(className.lastIndexOf('.')+1); } return className; } } } }
Output for CSV to help with initial analysis
src/test/java/com/foundationdb/sql/parser/CheckParserUsagesIT.java
Output for CSV to help with initial analysis
<ide><path>rc/test/java/com/foundationdb/sql/parser/CheckParserUsagesIT.java <ide> } <ide> int fullyUsed2 = 0; <ide> Collection<String> unused = new TreeSet<>(); <add> System.out.println("DeclaredType,SubType,PropertyType,Name,Java Declaration,Code To Remove"); <ide> for (NodeClass nodeClass : finder.getNodes().values()) { <ide> if (!nodeClass.fullyUsed()) { <ide> if (nodeClass.isReferenced && nodeClass.isConcrete()) { <ide> String name = nodeClass.getJavaName(); <del> System.out.println(name.substring(name.lastIndexOf('.')+1)); <ide> for (String field : nodeClass.fields) { <ide> unused.add(name + "." + field); <del> System.out.println(" " + field); <add> // technically incorrect, not checking for public field inheritance here <add> System.out.println(nodeClass.name + "," + name + ",FIELD," + field); <ide> } <ide> for (NodeClass.Method method : nodeClass.methods) { <ide> unused.add(method.getJavaString(name) + " -- " + method.descriptor); <del> System.out.println(" " + method.getJavaString(null) + " -- " <del> + ".removeMethod(\"" + method.name + "\", \"" + method.descriptor + "\")"); <add> System.out.println(method.className + "," + name + ",METHOD," + method.name + ",\"" + method.getJavaString(null) + "\",\"" <add> + ".removeMethod(\"\"" + method.name + "\"\", \"\"" + method.descriptor + ")\""); <ide> } <ide> } <ide> } else { <ide> return null; <ide> } <ide> <del> // TODO add interface & base class methods <ide> @Override <ide> public MethodVisitor visitMethod(int access, String name, <ide> String desc, String signature, String[] exceptions) { <ide> if ((access & Opcodes.ACC_PUBLIC) > 0) { <ide> if ((access & Opcodes.ACC_STATIC) == 0) { <ide> if (name.startsWith("get")) { <del> Method method = new Method(name, descriptor); <add> Method method = new Method(this.name, name, descriptor); <ide> methods.add(method); <ide> return method; <ide> } <ide> public static class Method { <ide> <ide> private final String descriptor; <add> private final String className; <ide> private String name; <ide> <del> public Method(String name, String descriptor) { <add> public Method(String className, String name, String descriptor) { <add> this.className = className; <ide> this.name = name; <ide> this.descriptor = descriptor; <ide> }
Java
apache-2.0
76f448adad72b66691f836164d9d95fdfe29d633
0
ShellyLC/nifi,ShellyLC/nifi,ShellyLC/nifi,ShellyLC/nifi,ShellyLC/nifi,ShellyLC/nifi
/* * 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.nifi.jms.cf; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map.Entry; import javax.jms.ConnectionFactory; import javax.net.ssl.SSLContext; import org.apache.nifi.annotation.behavior.DynamicProperty; import org.apache.nifi.annotation.documentation.CapabilityDescription; import org.apache.nifi.annotation.documentation.SeeAlso; import org.apache.nifi.annotation.documentation.Tags; import org.apache.nifi.annotation.lifecycle.OnDisabled; import org.apache.nifi.annotation.lifecycle.OnEnabled; import org.apache.nifi.components.PropertyDescriptor; import org.apache.nifi.controller.AbstractControllerService; import org.apache.nifi.controller.ConfigurationContext; import org.apache.nifi.processor.util.StandardValidators; import org.apache.nifi.reporting.InitializationException; import org.apache.nifi.ssl.SSLContextService; import org.apache.nifi.ssl.SSLContextService.ClientAuth; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Provides a factory service that creates and initializes * {@link ConnectionFactory} specific to the third party JMS system. * <p> * It accomplishes it by adjusting current classpath by adding to it the * additional resources (i.e., JMS client libraries) provided by the user via * {@link JMSConnectionFactoryProviderDefinition#CLIENT_LIB_DIR_PATH}, allowing * it then to create an instance of the target {@link ConnectionFactory} based * on the provided {@link JMSConnectionFactoryProviderDefinition#CONNECTION_FACTORY_IMPL} * which can be than access via {@link #getConnectionFactory()} method. * </p> */ @Tags({ "jms", "messaging", "integration", "queue", "topic", "publish", "subscribe" }) @CapabilityDescription("Provides a generic service to create vendor specific javax.jms.ConnectionFactory implementations. " + "ConnectionFactory can be served once this service is configured successfully") @DynamicProperty(name = "The name of a Connection Factory configuration property.", value = "The value of a given Connection Factory configuration property.", description = "The properties that are set following Java Beans convention where a property name is derived from the 'set*' method of the vendor " + "specific ConnectionFactory's implementation. For example, 'com.ibm.mq.jms.MQConnectionFactory.setChannel(String)' would imply 'channel' " + "property and 'com.ibm.mq.jms.MQConnectionFactory.setTransportType(int)' would imply 'transportType' property.") @SeeAlso(classNames = { "org.apache.nifi.jms.processors.ConsumeJMS", "org.apache.nifi.jms.processors.PublishJMS" }) public class JMSConnectionFactoryProvider extends AbstractControllerService implements JMSConnectionFactoryProviderDefinition { private final Logger logger = LoggerFactory.getLogger(JMSConnectionFactoryProvider.class); private static final List<PropertyDescriptor> propertyDescriptors; static { propertyDescriptors = Collections.unmodifiableList(Arrays.asList(CONNECTION_FACTORY_IMPL, CLIENT_LIB_DIR_PATH, BROKER_URI, SSL_CONTEXT_SERVICE)); } private volatile boolean configured; private volatile ConnectionFactory connectionFactory; /** * */ @Override protected List<PropertyDescriptor> getSupportedPropertyDescriptors() { return propertyDescriptors; } /** * */ @Override protected PropertyDescriptor getSupportedDynamicPropertyDescriptor(final String propertyDescriptorName) { return new PropertyDescriptor.Builder() .description("Specifies the value for '" + propertyDescriptorName + "' property to be set on the provided ConnectionFactory implementation.") .name(propertyDescriptorName).addValidator(StandardValidators.NON_EMPTY_VALIDATOR).dynamic(true) .build(); } /** * * @return new instance of {@link ConnectionFactory} */ @Override public ConnectionFactory getConnectionFactory() { if (this.configured) { return this.connectionFactory; } throw new IllegalStateException("ConnectionFactory can not be obtained unless " + "this ControllerService is configured. See onConfigure(ConfigurationContext) method."); } /** * */ @OnEnabled public void enable(ConfigurationContext context) throws InitializationException { try { if (!this.configured) { if (logger.isInfoEnabled()) { logger.info("Configuring " + this.getClass().getSimpleName() + " for '" + context.getProperty(CONNECTION_FACTORY_IMPL).evaluateAttributeExpressions().getValue() + "' to be connected to '" + BROKER_URI + "'"); } // will load user provided libraries/resources on the classpath Utils.addResourcesToClasspath(context.getProperty(CLIENT_LIB_DIR_PATH).evaluateAttributeExpressions().getValue()); this.createConnectionFactoryInstance(context); this.setConnectionFactoryProperties(context); } this.configured = true; } catch (Exception e) { logger.error("Failed to configure " + this.getClass().getSimpleName(), e); this.configured = false; throw new IllegalStateException(e); } } /** * */ @OnDisabled public void disable() { this.connectionFactory = null; this.configured = false; } /** * This operation follows standard bean convention by matching property name * to its corresponding 'setter' method. Once the method was located it is * invoked to set the corresponding property to a value provided by during * service configuration. For example, 'channel' property will correspond to * 'setChannel(..) method and 'queueManager' property will correspond to * setQueueManager(..) method with a single argument. * * There are also few adjustments to accommodate well known brokers. For * example ActiveMQ ConnectionFactory accepts address of the Message Broker * in a form of URL while IBMs in the form of host/port pair (more common). * So this method will use value retrieved from the 'BROKER_URI' static * property 'as is' if ConnectionFactory implementation is coming from * ActiveMQ and for all others (for now) the 'BROKER_URI' value will be * split on ':' and the resulting pair will be used to execute * setHostName(..) and setPort(..) methods on the provided * ConnectionFactory. This may need to be maintained and adjusted to * accommodate other implementation of ConnectionFactory, but only for * URL/Host/Port issue. All other properties are set as dynamic properties * where user essentially provides both property name and value, The bean * convention is also explained in user manual for this component with links * pointing to documentation of various ConnectionFactories. * * @see #setProperty(String, String) method */ private void setConnectionFactoryProperties(ConfigurationContext context) { for (final Entry<PropertyDescriptor, String> entry : context.getProperties().entrySet()) { PropertyDescriptor descriptor = entry.getKey(); String propertyName = descriptor.getName(); if (descriptor.isDynamic()) { this.setProperty(propertyName, entry.getValue()); } else { if (propertyName.equals(BROKER)) { if (context.getProperty(CONNECTION_FACTORY_IMPL).evaluateAttributeExpressions().getValue().startsWith("org.apache.activemq")) { this.setProperty("brokerURL", context.getProperty(descriptor).evaluateAttributeExpressions().getValue()); } else { String[] hostPort = entry.getValue().split(":"); if (hostPort.length == 2) { this.setProperty("hostName", hostPort[0]); this.setProperty("port", hostPort[1]); } else if (hostPort.length != 2) { this.setProperty("serverUrl", entry.getValue()); // for tibco } else { throw new IllegalArgumentException("Failed to parse broker url: " + entry.getValue()); } } SSLContextService sc = context.getProperty(SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class); if (sc != null) { SSLContext ssl = sc.createSSLContext(ClientAuth.NONE); this.setProperty("sSLSocketFactory", ssl.getSocketFactory()); } } // ignore 'else', since it's the only non-dynamic property that is relevant to CF configuration } } } /** * Sets corresponding {@link ConnectionFactory}'s property to a * 'propertyValue' by invoking a 'setter' method that corresponds to * 'propertyName'. For example, 'channel' property will correspond to * 'setChannel(..) method and 'queueManager' property will correspond to * setQueueManager(..) method with a single argument. * * NOTE: There is a limited type conversion to accommodate property value * types since all NiFi configuration properties comes as String. It is * accomplished by checking the argument type of the method and executing * its corresponding conversion to target primitive (e.g., value 'true' will * go thru Boolean.parseBoolean(propertyValue) if method argument is of type * boolean). None-primitive values are not supported at the moment and will * result in {@link IllegalArgumentException}. It is OK though since based * on analysis of several ConnectionFactory implementation the all seem to * follow bean convention and all their properties using Java primitives as * arguments. */ private void setProperty(String propertyName, Object propertyValue) { String methodName = this.toMethodName(propertyName); Method method = Utils.findMethod(methodName, this.connectionFactory.getClass()); if (method != null) { try { Class<?> returnType = method.getParameterTypes()[0]; if (String.class.isAssignableFrom(returnType)) { method.invoke(this.connectionFactory, propertyValue); } else if (int.class.isAssignableFrom(returnType)) { method.invoke(this.connectionFactory, Integer.parseInt((String) propertyValue)); } else if (long.class.isAssignableFrom(returnType)) { method.invoke(this.connectionFactory, Long.parseLong((String) propertyValue)); } else if (boolean.class.isAssignableFrom(returnType)) { method.invoke(this.connectionFactory, Boolean.parseBoolean((String) propertyValue)); } else { method.invoke(this.connectionFactory, propertyValue); } } catch (Exception e) { throw new IllegalStateException("Failed to set property " + propertyName, e); } } else if (propertyName.equals("hostName")) { this.setProperty("host", propertyValue); // try 'host' as another common convention. } } /** * Creates an instance of the {@link ConnectionFactory} from the provided * 'CONNECTION_FACTORY_IMPL'. */ private void createConnectionFactoryInstance(ConfigurationContext context) { String connectionFactoryImplName = context.getProperty(CONNECTION_FACTORY_IMPL).evaluateAttributeExpressions().getValue(); this.connectionFactory = Utils.newDefaultInstance(connectionFactoryImplName); } /** * Will convert propertyName to a method name following bean convention. For * example, 'channel' property will correspond to 'setChannel method and * 'queueManager' property will correspond to setQueueManager method name */ private String toMethodName(String propertyName) { char c[] = propertyName.toCharArray(); c[0] = Character.toUpperCase(c[0]); return "set" + new String(c); } }
nifi-nar-bundles/nifi-jms-bundle/nifi-jms-cf-service/src/main/java/org/apache/nifi/jms/cf/JMSConnectionFactoryProvider.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.nifi.jms.cf; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map.Entry; import javax.jms.ConnectionFactory; import javax.net.ssl.SSLContext; import org.apache.nifi.annotation.behavior.DynamicProperty; import org.apache.nifi.annotation.documentation.CapabilityDescription; import org.apache.nifi.annotation.documentation.SeeAlso; import org.apache.nifi.annotation.documentation.Tags; import org.apache.nifi.annotation.lifecycle.OnDisabled; import org.apache.nifi.annotation.lifecycle.OnEnabled; import org.apache.nifi.components.PropertyDescriptor; import org.apache.nifi.controller.AbstractControllerService; import org.apache.nifi.controller.ConfigurationContext; import org.apache.nifi.processor.util.StandardValidators; import org.apache.nifi.reporting.InitializationException; import org.apache.nifi.ssl.SSLContextService; import org.apache.nifi.ssl.SSLContextService.ClientAuth; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Provides a factory service that creates and initializes * {@link ConnectionFactory} specific to the third party JMS system. * <p> * It accomplishes it by adjusting current classpath by adding to it the * additional resources (i.e., JMS client libraries) provided by the user via * {@link JMSConnectionFactoryProviderDefinition#CLIENT_LIB_DIR_PATH}, allowing * it then to create an instance of the target {@link ConnectionFactory} based * on the provided {@link JMSConnectionFactoryProviderDefinition#CONNECTION_FACTORY_IMPL} * which can be than access via {@link #getConnectionFactory()} method. * </p> */ @Tags({ "jms", "messaging", "integration", "queue", "topic", "publish", "subscribe" }) @CapabilityDescription("Provides a generic service to create vendor specific javax.jms.ConnectionFactory implementations. " + "ConnectionFactory can be served once this service is configured successfully") @DynamicProperty(name = "The name of a Connection Factory configuration property.", value = "The value of a given Connection Factory configuration property.", description = "The properties that are set following Java Beans convention where a property name is derived from the 'set*' method of the vendor " + "specific ConnectionFactory's implementation. For example, 'com.ibm.mq.jms.MQConnectionFactory.setChannel(String)' would imply 'channel' " + "property and 'com.ibm.mq.jms.MQConnectionFactory.setTransportType(int)' would imply 'transportType' property.") @SeeAlso(classNames = { "org.apache.nifi.jms.processors.ConsumeJMS", "org.apache.nifi.jms.processors.PublishJMS" }) public class JMSConnectionFactoryProvider extends AbstractControllerService implements JMSConnectionFactoryProviderDefinition { private final Logger logger = LoggerFactory.getLogger(JMSConnectionFactoryProvider.class); private static final List<PropertyDescriptor> propertyDescriptors; static { propertyDescriptors = Collections.unmodifiableList(Arrays.asList(CONNECTION_FACTORY_IMPL, CLIENT_LIB_DIR_PATH, BROKER_URI, SSL_CONTEXT_SERVICE)); } private volatile boolean configured; private volatile ConnectionFactory connectionFactory; /** * */ @Override protected List<PropertyDescriptor> getSupportedPropertyDescriptors() { return propertyDescriptors; } /** * */ @Override protected PropertyDescriptor getSupportedDynamicPropertyDescriptor(final String propertyDescriptorName) { return new PropertyDescriptor.Builder() .description("Specifies the value for '" + propertyDescriptorName + "' property to be set on the provided ConnectionFactory implementation.") .name(propertyDescriptorName).addValidator(StandardValidators.NON_EMPTY_VALIDATOR).dynamic(true) .build(); } /** * * @return new instance of {@link ConnectionFactory} */ @Override public ConnectionFactory getConnectionFactory() { if (this.configured) { return this.connectionFactory; } throw new IllegalStateException("ConnectionFactory can not be obtained unless " + "this ControllerService is configured. See onConfigure(ConfigurationContext) method."); } /** * */ @OnEnabled public void enable(ConfigurationContext context) throws InitializationException { try { if (!this.configured) { if (logger.isInfoEnabled()) { logger.info("Configuring " + this.getClass().getSimpleName() + " for '" + context.getProperty(CONNECTION_FACTORY_IMPL).evaluateAttributeExpressions().getValue() + "' to be connected to '" + BROKER_URI + "'"); } // will load user provided libraries/resources on the classpath Utils.addResourcesToClasspath(context.getProperty(CLIENT_LIB_DIR_PATH).evaluateAttributeExpressions().getValue()); this.createConnectionFactoryInstance(context); this.setConnectionFactoryProperties(context); } this.configured = true; } catch (Exception e) { logger.error("Failed to configure " + this.getClass().getSimpleName(), e); this.configured = false; throw new IllegalStateException(e); } } /** * */ @OnDisabled public void disable() { this.connectionFactory = null; this.configured = false; } /** * This operation follows standard bean convention by matching property name * to its corresponding 'setter' method. Once the method was located it is * invoked to set the corresponding property to a value provided by during * service configuration. For example, 'channel' property will correspond to * 'setChannel(..) method and 'queueManager' property will correspond to * setQueueManager(..) method with a single argument. * * There are also few adjustments to accommodate well known brokers. For * example ActiveMQ ConnectionFactory accepts address of the Message Broker * in a form of URL while IBMs in the form of host/port pair (more common). * So this method will use value retrieved from the 'BROKER_URI' static * property 'as is' if ConnectionFactory implementation is coming from * ActiveMQ and for all others (for now) the 'BROKER_URI' value will be * split on ':' and the resulting pair will be used to execute * setHostName(..) and setPort(..) methods on the provided * ConnectionFactory. This may need to be maintained and adjusted to * accommodate other implementation of ConnectionFactory, but only for * URL/Host/Port issue. All other properties are set as dynamic properties * where user essentially provides both property name and value, The bean * convention is also explained in user manual for this component with links * pointing to documentation of various ConnectionFactories. * * @see #setProperty(String, String) method */ private void setConnectionFactoryProperties(ConfigurationContext context) { for (final Entry<PropertyDescriptor, String> entry : context.getProperties().entrySet()) { PropertyDescriptor descriptor = entry.getKey(); String propertyName = descriptor.getName(); if (descriptor.isDynamic()) { this.setProperty(propertyName, entry.getValue()); } else { if (propertyName.equals(BROKER)) { if (context.getProperty(CONNECTION_FACTORY_IMPL).evaluateAttributeExpressions().getValue().startsWith("org.apache.activemq")) { this.setProperty("brokerURL", entry.getValue()); } else { String[] hostPort = entry.getValue().split(":"); if (hostPort.length == 2) { this.setProperty("hostName", hostPort[0]); this.setProperty("port", hostPort[1]); } else if (hostPort.length != 2) { this.setProperty("serverUrl", entry.getValue()); // for tibco } else { throw new IllegalArgumentException("Failed to parse broker url: " + entry.getValue()); } } SSLContextService sc = context.getProperty(SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class); if (sc != null) { SSLContext ssl = sc.createSSLContext(ClientAuth.NONE); this.setProperty("sSLSocketFactory", ssl.getSocketFactory()); } } // ignore 'else', since it's the only non-dynamic property that is relevant to CF configuration } } } /** * Sets corresponding {@link ConnectionFactory}'s property to a * 'propertyValue' by invoking a 'setter' method that corresponds to * 'propertyName'. For example, 'channel' property will correspond to * 'setChannel(..) method and 'queueManager' property will correspond to * setQueueManager(..) method with a single argument. * * NOTE: There is a limited type conversion to accommodate property value * types since all NiFi configuration properties comes as String. It is * accomplished by checking the argument type of the method and executing * its corresponding conversion to target primitive (e.g., value 'true' will * go thru Boolean.parseBoolean(propertyValue) if method argument is of type * boolean). None-primitive values are not supported at the moment and will * result in {@link IllegalArgumentException}. It is OK though since based * on analysis of several ConnectionFactory implementation the all seem to * follow bean convention and all their properties using Java primitives as * arguments. */ private void setProperty(String propertyName, Object propertyValue) { String methodName = this.toMethodName(propertyName); Method method = Utils.findMethod(methodName, this.connectionFactory.getClass()); if (method != null) { try { Class<?> returnType = method.getParameterTypes()[0]; if (String.class.isAssignableFrom(returnType)) { method.invoke(this.connectionFactory, propertyValue); } else if (int.class.isAssignableFrom(returnType)) { method.invoke(this.connectionFactory, Integer.parseInt((String) propertyValue)); } else if (long.class.isAssignableFrom(returnType)) { method.invoke(this.connectionFactory, Long.parseLong((String) propertyValue)); } else if (boolean.class.isAssignableFrom(returnType)) { method.invoke(this.connectionFactory, Boolean.parseBoolean((String) propertyValue)); } else { method.invoke(this.connectionFactory, propertyValue); } } catch (Exception e) { throw new IllegalStateException("Failed to set property " + propertyName, e); } } else if (propertyName.equals("hostName")) { this.setProperty("host", propertyValue); // try 'host' as another common convention. } } /** * Creates an instance of the {@link ConnectionFactory} from the provided * 'CONNECTION_FACTORY_IMPL'. */ private void createConnectionFactoryInstance(ConfigurationContext context) { String connectionFactoryImplName = context.getProperty(CONNECTION_FACTORY_IMPL).evaluateAttributeExpressions().getValue(); this.connectionFactory = Utils.newDefaultInstance(connectionFactoryImplName); } /** * Will convert propertyName to a method name following bean convention. For * example, 'channel' property will correspond to 'setChannel method and * 'queueManager' property will correspond to setQueueManager method name */ private String toMethodName(String propertyName) { char c[] = propertyName.toCharArray(); c[0] = Character.toUpperCase(c[0]); return "set" + new String(c); } }
Fixed a bug that nifi-jms-cf-service cannot have a variable as the brokerURL
nifi-nar-bundles/nifi-jms-bundle/nifi-jms-cf-service/src/main/java/org/apache/nifi/jms/cf/JMSConnectionFactoryProvider.java
Fixed a bug that nifi-jms-cf-service cannot have a variable as the brokerURL
<ide><path>ifi-nar-bundles/nifi-jms-bundle/nifi-jms-cf-service/src/main/java/org/apache/nifi/jms/cf/JMSConnectionFactoryProvider.java <ide> } else { <ide> if (propertyName.equals(BROKER)) { <ide> if (context.getProperty(CONNECTION_FACTORY_IMPL).evaluateAttributeExpressions().getValue().startsWith("org.apache.activemq")) { <del> this.setProperty("brokerURL", entry.getValue()); <add> this.setProperty("brokerURL", context.getProperty(descriptor).evaluateAttributeExpressions().getValue()); <ide> } else { <ide> String[] hostPort = entry.getValue().split(":"); <ide> if (hostPort.length == 2) {
Java
apache-2.0
1dc0e93689bbf1bbbbb77155b45ec9f3876a39b7
0
strapdata/elassandra,vroyer/elassandra,strapdata/elassandra,vroyer/elassandra,strapdata/elassandra,strapdata/elassandra,vroyer/elassandra,strapdata/elassandra
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.action.admin.indices.create; import org.elasticsearch.ElasticsearchGenerationException; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.Version; import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.action.IndicesRequest; import org.elasticsearch.action.admin.indices.alias.Alias; import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest; import org.elasticsearch.action.support.ActiveShardCount; import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.action.support.master.AcknowledgedRequest; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.Strings; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.collect.MapBuilder; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.DeprecationHandler; import org.elasticsearch.common.xcontent.LoggingDeprecationHandler; import org.elasticsearch.common.xcontent.NamedXContentRegistry; import org.elasticsearch.common.xcontent.ToXContentObject; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentType; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import static org.elasticsearch.action.ValidateActions.addValidationError; import static org.elasticsearch.common.settings.Settings.Builder.EMPTY_SETTINGS; import static org.elasticsearch.common.settings.Settings.readSettingsFromStream; import static org.elasticsearch.common.settings.Settings.writeSettingsToStream; /** * A request to create an index. Best created with {@link org.elasticsearch.client.Requests#createIndexRequest(String)}. * <p> * The index created can optionally be created with {@link #settings(org.elasticsearch.common.settings.Settings)}. * * @see org.elasticsearch.client.IndicesAdminClient#create(CreateIndexRequest) * @see org.elasticsearch.client.Requests#createIndexRequest(String) * @see CreateIndexResponse */ public class CreateIndexRequest extends AcknowledgedRequest<CreateIndexRequest> implements IndicesRequest, ToXContentObject { public static final ParseField MAPPINGS = new ParseField("mappings"); public static final ParseField SETTINGS = new ParseField("settings"); public static final ParseField ALIASES = new ParseField("aliases"); private String cause = ""; private String index; private Settings settings = EMPTY_SETTINGS; private final Map<String, String> mappings = new HashMap<>(); private final Set<Alias> aliases = new HashSet<>(); private boolean updateAllTypes = false; private ActiveShardCount waitForActiveShards = ActiveShardCount.DEFAULT; public CreateIndexRequest() { } /** * Constructs a new request to create an index with the specified name. */ public CreateIndexRequest(String index) { this(index, EMPTY_SETTINGS); } /** * Constructs a new request to create an index with the specified name and settings. */ public CreateIndexRequest(String index, Settings settings) { this.index = index; this.settings = settings; } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = null; if (index == null) { validationException = addValidationError("index is missing", validationException); } return validationException; } @Override public String[] indices() { return new String[]{index}; } @Override public IndicesOptions indicesOptions() { return IndicesOptions.strictSingleIndexNoExpandForbidClosed(); } /** * The index name to create. */ public String index() { return index; } public CreateIndexRequest index(String index) { this.index = index; return this; } /** * The settings to create the index with. */ public Settings settings() { return settings; } /** * The cause for this index creation. */ public String cause() { return cause; } /** * The settings to create the index with. */ public CreateIndexRequest settings(Settings.Builder settings) { this.settings = settings.build(); return this; } /** * The settings to create the index with. */ public CreateIndexRequest settings(Settings settings) { this.settings = settings; return this; } /** * The settings to create the index with (either json or yaml format) */ public CreateIndexRequest settings(String source, XContentType xContentType) { this.settings = Settings.builder().loadFromSource(source, xContentType).build(); return this; } /** * Allows to set the settings using a json builder. */ public CreateIndexRequest settings(XContentBuilder builder) { settings(Strings.toString(builder), builder.contentType()); return this; } /** * The settings to create the index with (either json/yaml/properties format) */ @SuppressWarnings("unchecked") public CreateIndexRequest settings(Map source) { try { XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON); builder.map(source); settings(Strings.toString(builder), XContentType.JSON); } catch (IOException e) { throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e); } return this; } /** * Adds mapping that will be added when the index gets created. * * @param type The mapping type * @param source The mapping source * @param xContentType The content type of the source */ public CreateIndexRequest mapping(String type, String source, XContentType xContentType) { return mapping(type, new BytesArray(source), xContentType); } /** * Adds mapping that will be added when the index gets created. * * @param type The mapping type * @param source The mapping source * @param xContentType the content type of the mapping source */ private CreateIndexRequest mapping(String type, BytesReference source, XContentType xContentType) { if (mappings.containsKey(type)) { throw new IllegalStateException("mappings for type \"" + type + "\" were already defined"); } Objects.requireNonNull(xContentType); try { mappings.put(type, XContentHelper.convertToJson(source, false, false, xContentType)); return this; } catch (IOException e) { throw new UncheckedIOException("failed to convert to json", e); } } /** * The cause for this index creation. */ public CreateIndexRequest cause(String cause) { this.cause = cause; return this; } /** * Adds mapping that will be added when the index gets created. * * @param type The mapping type * @param source The mapping source */ public CreateIndexRequest mapping(String type, XContentBuilder source) { return mapping(type, BytesReference.bytes(source), source.contentType()); } /** * Adds mapping that will be added when the index gets created. * * @param type The mapping type * @param source The mapping source */ @SuppressWarnings("unchecked") public CreateIndexRequest mapping(String type, Map source) { if (mappings.containsKey(type)) { throw new IllegalStateException("mappings for type \"" + type + "\" were already defined"); } // wrap it in a type map if its not if (source.size() != 1 || !source.containsKey(type)) { source = MapBuilder.<String, Object>newMapBuilder().put(type, source).map(); } try { XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON); builder.map(source); return mapping(type, builder); } catch (IOException e) { throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e); } } /** * A specialized simplified mapping source method, takes the form of simple properties definition: * ("field1", "type=string,store=true"). */ public CreateIndexRequest mapping(String type, Object... source) { mapping(type, PutMappingRequest.buildFromSimplifiedDef(type, source)); return this; } /** * Sets the aliases that will be associated with the index when it gets created */ @SuppressWarnings("unchecked") public CreateIndexRequest aliases(Map source) { try { XContentBuilder builder = XContentFactory.jsonBuilder(); builder.map(source); return aliases(BytesReference.bytes(builder)); } catch (IOException e) { throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e); } } /** * Sets the aliases that will be associated with the index when it gets created */ public CreateIndexRequest aliases(XContentBuilder source) { return aliases(BytesReference.bytes(source)); } /** * Sets the aliases that will be associated with the index when it gets created */ public CreateIndexRequest aliases(String source) { return aliases(new BytesArray(source)); } /** * Sets the aliases that will be associated with the index when it gets created */ public CreateIndexRequest aliases(BytesReference source) { // EMPTY is safe here because we never call namedObject try (XContentParser parser = XContentHelper .createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, source)) { //move to the first alias parser.nextToken(); while ((parser.nextToken()) != XContentParser.Token.END_OBJECT) { alias(Alias.fromXContent(parser)); } return this; } catch(IOException e) { throw new ElasticsearchParseException("Failed to parse aliases", e); } } /** * Adds an alias that will be associated with the index when it gets created */ public CreateIndexRequest alias(Alias alias) { this.aliases.add(alias); return this; } /** * Sets the settings and mappings as a single source. */ public CreateIndexRequest source(String source, XContentType xContentType) { return source(new BytesArray(source), xContentType); } /** * Sets the settings and mappings as a single source. */ public CreateIndexRequest source(XContentBuilder source) { return source(BytesReference.bytes(source), source.contentType()); } /** * Sets the settings and mappings as a single source. */ public CreateIndexRequest source(byte[] source, XContentType xContentType) { return source(source, 0, source.length, xContentType); } /** * Sets the settings and mappings as a single source. */ public CreateIndexRequest source(byte[] source, int offset, int length, XContentType xContentType) { return source(new BytesArray(source, offset, length), xContentType); } /** * Sets the settings and mappings as a single source. */ public CreateIndexRequest source(BytesReference source, XContentType xContentType) { Objects.requireNonNull(xContentType); source(XContentHelper.convertToMap(source, false, xContentType).v2(), LoggingDeprecationHandler.INSTANCE); return this; } /** * Sets the settings and mappings as a single source. */ @SuppressWarnings("unchecked") public CreateIndexRequest source(Map<String, ?> source, DeprecationHandler deprecationHandler) { boolean found = false; for (Map.Entry<String, ?> entry : source.entrySet()) { String name = entry.getKey(); if (SETTINGS.match(name, deprecationHandler)) { found = true; settings((Map<String, Object>) entry.getValue()); } else if (MAPPINGS.match(name, deprecationHandler)) { found = true; Map<String, Object> mappings = (Map<String, Object>) entry.getValue(); for (Map.Entry<String, Object> entry1 : mappings.entrySet()) { mapping(entry1.getKey(), (Map<String, Object>) entry1.getValue()); } } else if (ALIASES.match(name, deprecationHandler)) { found = true; aliases((Map<String, Object>) entry.getValue()); } } if (!found) { // the top level are settings, use them settings(source); } return this; } public Map<String, String> mappings() { return this.mappings; } public Set<Alias> aliases() { return this.aliases; } /** True if all fields that span multiple types should be updated, false otherwise */ public boolean updateAllTypes() { return updateAllTypes; } /** See {@link #updateAllTypes()} * @deprecated useless with 6.x indices which may only have one type */ @Deprecated public CreateIndexRequest updateAllTypes(boolean updateAllTypes) { this.updateAllTypes = updateAllTypes; return this; } public ActiveShardCount waitForActiveShards() { return waitForActiveShards; } /** * Sets the number of shard copies that should be active for index creation to return. * Defaults to {@link ActiveShardCount#DEFAULT}, which will wait for one shard copy * (the primary) to become active. Set this value to {@link ActiveShardCount#ALL} to * wait for all shards (primary and all replicas) to be active before returning. * Otherwise, use {@link ActiveShardCount#from(int)} to set this value to any * non-negative integer, up to the number of copies per shard (number of replicas + 1), * to wait for the desired amount of shard copies to become active before returning. * Index creation will only wait up until the timeout value for the number of shard copies * to be active before returning. Check {@link CreateIndexResponse#isShardsAcknowledged()} to * determine if the requisite shard copies were all started before returning or timing out. * * @param waitForActiveShards number of active shard copies to wait on */ public CreateIndexRequest waitForActiveShards(ActiveShardCount waitForActiveShards) { this.waitForActiveShards = waitForActiveShards; return this; } /** * A shortcut for {@link #waitForActiveShards(ActiveShardCount)} where the numerical * shard count is passed in, instead of having to first call {@link ActiveShardCount#from(int)} * to get the ActiveShardCount. */ public CreateIndexRequest waitForActiveShards(final int waitForActiveShards) { return waitForActiveShards(ActiveShardCount.from(waitForActiveShards)); } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); cause = in.readString(); index = in.readString(); settings = readSettingsFromStream(in); int size = in.readVInt(); for (int i = 0; i < size; i++) { final String type = in.readString(); String source = in.readString(); if (in.getVersion().before(Version.V_6_0_0_alpha1)) { // TODO change to 5.3.0 after backport // we do not know the content type that comes from earlier versions so we autodetect and convert source = XContentHelper.convertToJson(new BytesArray(source), false, false, XContentFactory.xContentType(source)); } mappings.put(type, source); } if (in.getVersion().before(Version.V_6_5_0)) { // This used to be the size of custom metadata classes int customSize = in.readVInt(); assert customSize == 0 : "unexpected custom metadata when none is supported"; if (customSize > 0) { throw new IllegalStateException("unexpected custom metadata when none is supported"); } } int aliasesSize = in.readVInt(); for (int i = 0; i < aliasesSize; i++) { aliases.add(Alias.read(in)); } updateAllTypes = in.readBoolean(); waitForActiveShards = ActiveShardCount.readFrom(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeString(cause); out.writeString(index); writeSettingsToStream(settings, out); out.writeVInt(mappings.size()); for (Map.Entry<String, String> entry : mappings.entrySet()) { out.writeString(entry.getKey()); out.writeString(entry.getValue()); } if (out.getVersion().before(Version.V_6_5_0)) { // Size of custom index metadata, which is removed out.writeVInt(0); } out.writeVInt(aliases.size()); for (Alias alias : aliases) { alias.writeTo(out); } out.writeBoolean(updateAllTypes); waitForActiveShards.writeTo(out); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); innerToXContent(builder, params); builder.endObject(); return builder; } public XContentBuilder innerToXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(SETTINGS.getPreferredName()); settings.toXContent(builder, params); builder.endObject(); builder.startObject(MAPPINGS.getPreferredName()); for (Map.Entry<String, String> entry : mappings.entrySet()) { try (InputStream stream = new BytesArray(entry.getValue()).streamInput()) { builder.rawField(entry.getKey(), stream, XContentType.JSON); } } builder.endObject(); builder.startObject(ALIASES.getPreferredName()); for (Alias alias : aliases) { alias.toXContent(builder, params); } builder.endObject(); return builder; } }
server/src/main/java/org/elasticsearch/action/admin/indices/create/CreateIndexRequest.java
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.action.admin.indices.create; import org.elasticsearch.ElasticsearchGenerationException; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.Version; import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.action.IndicesRequest; import org.elasticsearch.action.admin.indices.alias.Alias; import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest; import org.elasticsearch.action.support.ActiveShardCount; import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.action.support.master.AcknowledgedRequest; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.Strings; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.collect.MapBuilder; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.DeprecationHandler; import org.elasticsearch.common.xcontent.LoggingDeprecationHandler; import org.elasticsearch.common.xcontent.NamedXContentRegistry; import org.elasticsearch.common.xcontent.ToXContentObject; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentType; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import static org.elasticsearch.action.ValidateActions.addValidationError; import static org.elasticsearch.common.settings.Settings.Builder.EMPTY_SETTINGS; import static org.elasticsearch.common.settings.Settings.readSettingsFromStream; import static org.elasticsearch.common.settings.Settings.writeSettingsToStream; /** * A request to create an index. Best created with {@link org.elasticsearch.client.Requests#createIndexRequest(String)}. * <p> * The index created can optionally be created with {@link #settings(org.elasticsearch.common.settings.Settings)}. * * @see org.elasticsearch.client.IndicesAdminClient#create(CreateIndexRequest) * @see org.elasticsearch.client.Requests#createIndexRequest(String) * @see CreateIndexResponse */ public class CreateIndexRequest extends AcknowledgedRequest<CreateIndexRequest> implements IndicesRequest, ToXContentObject { public static final ParseField MAPPINGS = new ParseField("mappings"); public static final ParseField SETTINGS = new ParseField("settings"); public static final ParseField ALIASES = new ParseField("aliases"); private String cause = ""; private String index; private Settings settings = EMPTY_SETTINGS; private final Map<String, String> mappings = new HashMap<>(); private final Set<Alias> aliases = new HashSet<>(); private boolean updateAllTypes = false; private ActiveShardCount waitForActiveShards = ActiveShardCount.DEFAULT; public CreateIndexRequest() { } /** * Constructs a new request to create an index with the specified name. */ public CreateIndexRequest(String index) { this(index, EMPTY_SETTINGS); } /** * Constructs a new request to create an index with the specified name and settings. */ public CreateIndexRequest(String index, Settings settings) { this.index = index; this.settings = settings; } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = null; if (index == null) { validationException = addValidationError("index is missing", validationException); } return validationException; } @Override public String[] indices() { return new String[]{index}; } @Override public IndicesOptions indicesOptions() { return IndicesOptions.strictSingleIndexNoExpandForbidClosed(); } /** * The index name to create. */ public String index() { return index; } public CreateIndexRequest index(String index) { this.index = index; return this; } /** * The settings to create the index with. */ public Settings settings() { return settings; } /** * The cause for this index creation. */ public String cause() { return cause; } /** * The settings to create the index with. */ public CreateIndexRequest settings(Settings.Builder settings) { this.settings = settings.build(); return this; } /** * The settings to create the index with. */ public CreateIndexRequest settings(Settings settings) { this.settings = settings; return this; } /** * The settings to create the index with (either json or yaml format) */ public CreateIndexRequest settings(String source, XContentType xContentType) { this.settings = Settings.builder().loadFromSource(source, xContentType).build(); return this; } /** * Allows to set the settings using a json builder. */ public CreateIndexRequest settings(XContentBuilder builder) { settings(Strings.toString(builder), builder.contentType()); return this; } /** * The settings to create the index with (either json/yaml/properties format) */ @SuppressWarnings("unchecked") public CreateIndexRequest settings(Map source) { try { XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON); builder.map(source); settings(Strings.toString(builder), XContentType.JSON); } catch (IOException e) { throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e); } return this; } /** * Adds mapping that will be added when the index gets created. * * @param type The mapping type * @param source The mapping source * @param xContentType The content type of the source */ public CreateIndexRequest mapping(String type, String source, XContentType xContentType) { return mapping(type, new BytesArray(source), xContentType); } /** * Adds mapping that will be added when the index gets created. * * @param type The mapping type * @param source The mapping source * @param xContentType the content type of the mapping source */ private CreateIndexRequest mapping(String type, BytesReference source, XContentType xContentType) { if (mappings.containsKey(type)) { throw new IllegalStateException("mappings for type \"" + type + "\" were already defined"); } Objects.requireNonNull(xContentType); try { mappings.put(type, XContentHelper.convertToJson(source, false, false, xContentType)); return this; } catch (IOException e) { throw new UncheckedIOException("failed to convert to json", e); } } /** * The cause for this index creation. */ public CreateIndexRequest cause(String cause) { this.cause = cause; return this; } /** * Adds mapping that will be added when the index gets created. * * @param type The mapping type * @param source The mapping source */ public CreateIndexRequest mapping(String type, XContentBuilder source) { return mapping(type, BytesReference.bytes(source), source.contentType()); } /** * Adds mapping that will be added when the index gets created. * * @param type The mapping type * @param source The mapping source */ @SuppressWarnings("unchecked") public CreateIndexRequest mapping(String type, Map source) { if (mappings.containsKey(type)) { throw new IllegalStateException("mappings for type \"" + type + "\" were already defined"); } // wrap it in a type map if its not if (source.size() != 1 || !source.containsKey(type)) { source = MapBuilder.<String, Object>newMapBuilder().put(type, source).map(); } try { XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON); builder.map(source); return mapping(type, builder); } catch (IOException e) { throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e); } } /** * A specialized simplified mapping source method, takes the form of simple properties definition: * ("field1", "type=string,store=true"). */ public CreateIndexRequest mapping(String type, Object... source) { mapping(type, PutMappingRequest.buildFromSimplifiedDef(type, source)); return this; } /** * Sets the aliases that will be associated with the index when it gets created */ @SuppressWarnings("unchecked") public CreateIndexRequest aliases(Map source) { try { XContentBuilder builder = XContentFactory.jsonBuilder(); builder.map(source); return aliases(BytesReference.bytes(builder)); } catch (IOException e) { throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e); } } /** * Sets the aliases that will be associated with the index when it gets created */ public CreateIndexRequest aliases(XContentBuilder source) { return aliases(BytesReference.bytes(source)); } /** * Sets the aliases that will be associated with the index when it gets created */ public CreateIndexRequest aliases(String source) { return aliases(new BytesArray(source)); } /** * Sets the aliases that will be associated with the index when it gets created */ public CreateIndexRequest aliases(BytesReference source) { // EMPTY is safe here because we never call namedObject try (XContentParser parser = XContentHelper .createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, source)) { //move to the first alias parser.nextToken(); while ((parser.nextToken()) != XContentParser.Token.END_OBJECT) { alias(Alias.fromXContent(parser)); } return this; } catch(IOException e) { throw new ElasticsearchParseException("Failed to parse aliases", e); } } /** * Adds an alias that will be associated with the index when it gets created */ public CreateIndexRequest alias(Alias alias) { this.aliases.add(alias); return this; } /** * Sets the settings and mappings as a single source. */ public CreateIndexRequest source(String source, XContentType xContentType) { return source(new BytesArray(source), xContentType); } /** * Sets the settings and mappings as a single source. */ public CreateIndexRequest source(XContentBuilder source) { return source(BytesReference.bytes(source), source.contentType()); } /** * Sets the settings and mappings as a single source. */ public CreateIndexRequest source(byte[] source, XContentType xContentType) { return source(source, 0, source.length, xContentType); } /** * Sets the settings and mappings as a single source. */ public CreateIndexRequest source(byte[] source, int offset, int length, XContentType xContentType) { return source(new BytesArray(source, offset, length), xContentType); } /** * Sets the settings and mappings as a single source. */ public CreateIndexRequest source(BytesReference source, XContentType xContentType) { Objects.requireNonNull(xContentType); source(XContentHelper.convertToMap(source, false, xContentType).v2(), LoggingDeprecationHandler.INSTANCE); return this; } /** * Sets the settings and mappings as a single source. */ @SuppressWarnings("unchecked") public CreateIndexRequest source(Map<String, ?> source, DeprecationHandler deprecationHandler) { boolean found = false; for (Map.Entry<String, ?> entry : source.entrySet()) { String name = entry.getKey(); if (SETTINGS.match(name, deprecationHandler)) { found = true; settings((Map<String, Object>) entry.getValue()); } else if (MAPPINGS.match(name, deprecationHandler)) { found = true; Map<String, Object> mappings = (Map<String, Object>) entry.getValue(); for (Map.Entry<String, Object> entry1 : mappings.entrySet()) { mapping(entry1.getKey(), (Map<String, Object>) entry1.getValue()); } } else if (ALIASES.match(name, deprecationHandler)) { found = true; aliases((Map<String, Object>) entry.getValue()); } else { throw new ElasticsearchParseException("unknown key [{}] for create index", name); } } if (!found) { // the top level are settings, use them settings(source); } return this; } public Map<String, String> mappings() { return this.mappings; } public Set<Alias> aliases() { return this.aliases; } /** True if all fields that span multiple types should be updated, false otherwise */ public boolean updateAllTypes() { return updateAllTypes; } /** See {@link #updateAllTypes()} * @deprecated useless with 6.x indices which may only have one type */ @Deprecated public CreateIndexRequest updateAllTypes(boolean updateAllTypes) { this.updateAllTypes = updateAllTypes; return this; } public ActiveShardCount waitForActiveShards() { return waitForActiveShards; } /** * Sets the number of shard copies that should be active for index creation to return. * Defaults to {@link ActiveShardCount#DEFAULT}, which will wait for one shard copy * (the primary) to become active. Set this value to {@link ActiveShardCount#ALL} to * wait for all shards (primary and all replicas) to be active before returning. * Otherwise, use {@link ActiveShardCount#from(int)} to set this value to any * non-negative integer, up to the number of copies per shard (number of replicas + 1), * to wait for the desired amount of shard copies to become active before returning. * Index creation will only wait up until the timeout value for the number of shard copies * to be active before returning. Check {@link CreateIndexResponse#isShardsAcknowledged()} to * determine if the requisite shard copies were all started before returning or timing out. * * @param waitForActiveShards number of active shard copies to wait on */ public CreateIndexRequest waitForActiveShards(ActiveShardCount waitForActiveShards) { this.waitForActiveShards = waitForActiveShards; return this; } /** * A shortcut for {@link #waitForActiveShards(ActiveShardCount)} where the numerical * shard count is passed in, instead of having to first call {@link ActiveShardCount#from(int)} * to get the ActiveShardCount. */ public CreateIndexRequest waitForActiveShards(final int waitForActiveShards) { return waitForActiveShards(ActiveShardCount.from(waitForActiveShards)); } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); cause = in.readString(); index = in.readString(); settings = readSettingsFromStream(in); int size = in.readVInt(); for (int i = 0; i < size; i++) { final String type = in.readString(); String source = in.readString(); if (in.getVersion().before(Version.V_6_0_0_alpha1)) { // TODO change to 5.3.0 after backport // we do not know the content type that comes from earlier versions so we autodetect and convert source = XContentHelper.convertToJson(new BytesArray(source), false, false, XContentFactory.xContentType(source)); } mappings.put(type, source); } if (in.getVersion().before(Version.V_6_5_0)) { // This used to be the size of custom metadata classes int customSize = in.readVInt(); assert customSize == 0 : "unexpected custom metadata when none is supported"; if (customSize > 0) { throw new IllegalStateException("unexpected custom metadata when none is supported"); } } int aliasesSize = in.readVInt(); for (int i = 0; i < aliasesSize; i++) { aliases.add(Alias.read(in)); } updateAllTypes = in.readBoolean(); waitForActiveShards = ActiveShardCount.readFrom(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeString(cause); out.writeString(index); writeSettingsToStream(settings, out); out.writeVInt(mappings.size()); for (Map.Entry<String, String> entry : mappings.entrySet()) { out.writeString(entry.getKey()); out.writeString(entry.getValue()); } if (out.getVersion().before(Version.V_6_5_0)) { // Size of custom index metadata, which is removed out.writeVInt(0); } out.writeVInt(aliases.size()); for (Alias alias : aliases) { alias.writeTo(out); } out.writeBoolean(updateAllTypes); waitForActiveShards.writeTo(out); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); innerToXContent(builder, params); builder.endObject(); return builder; } public XContentBuilder innerToXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(SETTINGS.getPreferredName()); settings.toXContent(builder, params); builder.endObject(); builder.startObject(MAPPINGS.getPreferredName()); for (Map.Entry<String, String> entry : mappings.entrySet()) { try (InputStream stream = new BytesArray(entry.getValue()).streamInput()) { builder.rawField(entry.getKey(), stream, XContentType.JSON); } } builder.endObject(); builder.startObject(ALIASES.getPreferredName()); for (Alias alias : aliases) { alias.toXContent(builder, params); } builder.endObject(); return builder; } }
Don't be strict for 6.x
server/src/main/java/org/elasticsearch/action/admin/indices/create/CreateIndexRequest.java
Don't be strict for 6.x
<ide><path>erver/src/main/java/org/elasticsearch/action/admin/indices/create/CreateIndexRequest.java <ide> } else if (ALIASES.match(name, deprecationHandler)) { <ide> found = true; <ide> aliases((Map<String, Object>) entry.getValue()); <del> } else { <del> throw new ElasticsearchParseException("unknown key [{}] for create index", name); <ide> } <ide> } <ide> if (!found) {
Java
mit
fd7e20e78326a3dad613fed6b16053bb28e01752
0
SilentChaos512/ScalingHealth
/* * Scaling Health * Copyright (C) 2018 SilentChaos512 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation version 3 * of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.silentchaos512.scalinghealth.client; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.Gui; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.attributes.IAttributeInstance; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.MobEffects; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.MathHelper; import net.minecraftforge.client.GuiIngameForge; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.silentchaos512.lib.config.ConfigBase; import net.silentchaos512.scalinghealth.ScalingHealth; import net.silentchaos512.scalinghealth.config.Config; import java.awt.*; import java.util.Random; /** * Handles display of regular and absorption hearts. * <p>For future reference, much of the vanilla code can be found in {@link GuiIngameForge}.</p> */ public class HeartDisplayHandler extends Gui { public enum TextStyle { DISABLED, ROWS, HEALTH_AND_MAX; private static final String COMMENT = "Determines what the text next to your hearts will display. DISABLED will display nothing, ROWS will display the number of remaining rows that have health left, and HEALTH_AND_MAX will display your actual health and max health values."; public static TextStyle loadFromConfig(ConfigBase config) { return config.loadEnum("Health Text Style", Config.CAT_CLIENT, TextStyle.class, ROWS, COMMENT); } } public enum TextColor { GREEN_TO_RED, WHITE, PSYCHEDELIC; public static final String COMMENT = "Determines the color of the text next to your hearts. GREEN_TO_RED displays green at full health, and moves to red as you lose health. WHITE will just be good old fashioned white text. Set to PSYCHEDELIC if you want to taste the rainbow."; public static TextColor loadFromConfig(ConfigBase config) { return config.loadEnum("Health Text Color", Config.CAT_CLIENT, TextColor.class, GREEN_TO_RED, COMMENT); } } public enum AbsorptionHeartStyle { SHIELD, GOLD_OUTLINE, VANILLA; public static final String COMMENT = "Determines how absorption hearts should be rendered."; public static AbsorptionHeartStyle loadDromConfig(ConfigBase config) { return config.loadEnum("Absorption Heart Style", Config.CAT_CLIENT, AbsorptionHeartStyle.class, SHIELD, COMMENT); } } public static final HeartDisplayHandler INSTANCE = new HeartDisplayHandler(); private static final float COLOR_CHANGE_PERIOD = 150; private static final ResourceLocation TEXTURE = new ResourceLocation(ScalingHealth.MOD_ID_LOWER, "textures/gui/hud.png"); private long lastSystemTime = 0; private int playerHealth = 0; private int lastPlayerHealth = 0; private Random rand = new Random(); private HeartDisplayHandler() { } @SubscribeEvent(receiveCanceled = true) public void onHealthBar(RenderGameOverlayEvent.Pre event) { Minecraft mc = Minecraft.getMinecraft(); EntityPlayer player = mc.player; // Health text TextStyle style = Config.HEART_DISPLAY_TEXT_STYLE; TextColor styleColor = Config.HEART_DISPLAY_TEXT_COLOR; if (event.getType() == ElementType.TEXT && style != TextStyle.DISABLED && mc.playerController.gameIsSurvivalOrAdventure()) { renderHealthText(event, player, style, styleColor); } // Hearts if (event.getType() == ElementType.HEALTH && Config.CHANGE_HEART_RENDERING) { event.setCanceled(true); renderHearts(event, mc, player); } } private void renderHearts(RenderGameOverlayEvent event, Minecraft mc, EntityPlayer player) { final boolean hardcoreMode = mc.world.getWorldInfo().isHardcoreModeEnabled(); int width = event.getResolution().getScaledWidth(); int height = event.getResolution().getScaledHeight(); GlStateManager.enableBlend(); int health = MathHelper.ceil(player.getHealth()); boolean highlight = player.hurtResistantTime / 3 % 2 == 1; int updateCounter = ClientTickHandler.ticksInGame; if (health < playerHealth && player.hurtResistantTime > 0 || health > playerHealth && player.hurtResistantTime > 0) { lastSystemTime = Minecraft.getSystemTime(); } if (Minecraft.getSystemTime() - lastSystemTime > 1000) { playerHealth = health; lastPlayerHealth = health; lastSystemTime = Minecraft.getSystemTime(); } playerHealth = health; int healthLast = lastPlayerHealth; IAttributeInstance attrMaxHealth = player.getEntityAttribute(SharedMonsterAttributes.MAX_HEALTH); float healthMax = Math.min((float) attrMaxHealth.getAttributeValue(), 20); float absorb = MathHelper.ceil(player.getAbsorptionAmount()); int healthRows = absorb > 0 ? 2 : 1; // MathHelper.ceil((healthMax + absorb) / 2f / 10f); int rowHeight = Math.max(10 - (healthRows - 2), 3); rand.setSeed(updateCounter * 312871); int[] lowHealthBob = new int[10]; for (int i = 0; i < lowHealthBob.length; ++i) lowHealthBob[i] = rand.nextInt(2); final int left = width / 2 - 91; final int top = height - GuiIngameForge.left_height; GuiIngameForge.left_height += healthRows * rowHeight; if (rowHeight != 10) GuiIngameForge.left_height += 10 - rowHeight; int regen = -1; if (player.isPotionActive(MobEffects.REGENERATION)) regen = updateCounter % 25; final int TOP = 9 * (hardcoreMode ? 5 : 0); final int BACKGROUND = (highlight ? 25 : 16); int MARGIN = 16; // if (player.isPotionActive(MobEffects.POISON)) // MARGIN += 36; // else if (player.isPotionActive(MobEffects.WITHER)) // MARGIN += 72; // Draw vanilla hearts drawVanillaHearts(health, highlight, healthLast, healthMax, rowHeight, left, top, regen, lowHealthBob, TOP, BACKGROUND, MARGIN); // int potionOffset = player.isPotionActive(MobEffects.WITHER) ? 18 // : (player.isPotionActive(MobEffects.POISON) ? 9 : 0) + (hardcoreMode ? 27 : 0); int potionOffset = hardcoreMode ? 27 : 0; // Draw extra hearts (only top 2 rows) mc.renderEngine.bindTexture(TEXTURE); health = MathHelper.ceil(player.getHealth()); int rowCount = getCustomHeartRowCount(health); int maxHealthRows = getCustomHeartRowCount((int) player.getMaxHealth()); for (int row = Math.max(0, rowCount - 2); row < rowCount; ++row) { int actualRow = row + (Config.REPLACE_VANILLA_HEARTS_WITH_CUSTOM ? 0 : 1); int renderHearts = Math.min((health - 20 * actualRow) / 2, 10); int rowColor = getColorForRow(row); boolean anythingDrawn; // Draw the hearts int j; int y; for (j = 0; j < renderHearts; ++j) { y = top + (j == regen ? -2 : 0); if (health <= 4) y += lowHealthBob[MathHelper.clamp(j, 0, lowHealthBob.length - 1)]; drawTexturedModalRect(left + 8 * j, y, 0, potionOffset, 9, 9, rowColor); } anythingDrawn = j > 0; // Half heart on the end? if (health % 2 == 1 && renderHearts < 10) { y = top + (j == regen ? -2 : 0); if (health <= 4) y += lowHealthBob[MathHelper.clamp(j, 0, lowHealthBob.length - 1)]; drawTexturedModalRect(left + 8 * renderHearts, y, 9, potionOffset, 9, 9, rowColor); anythingDrawn = true; } // Outline for last heart, to make seeing max health a little easier. if (Config.LAST_HEART_OUTLINE_ENABLED && anythingDrawn && row == maxHealthRows - 1) { // Get position of last partial/full heart j = (int) (Math.ceil(player.getMaxHealth() % 20f / 2f)) - 1; if (j < 0) j += 10; y = top + (j == regen ? -2 : 0); if (health <= 4) y += lowHealthBob[MathHelper.clamp(j, 0, lowHealthBob.length - 1)]; drawTexturedModalRect(left + 8 * j, y, 17, 9, 9, 9, Config.LAST_HEART_OUTLINE_COLOR); } } for (int i = 0; i < 10 && i < Math.ceil(health / 2f); ++i) { int y = top + (i == regen ? -2 : 0); if (health <= 4) y += lowHealthBob[MathHelper.clamp(i, 0, lowHealthBob.length - 1)]; // Effect hearts (poison, wither) if (showEffectHearts(player)) { int color = effectHeartColor(player); drawTexturedModalRect(left + 8 * i, y, 0, 54, 9, 9, color); } // Shiny glint on top of the hearts, a single white pixel in the upper left <3 if (!hardcoreMode) { drawTexturedModalRect(left + 8 * i, y, 17, 0, 9, 9, 0xCCFFFFFF); } } /* ========================== * Absorption hearts override * ========================== */ if (Config.ABSORPTION_HEART_STYLE != AbsorptionHeartStyle.VANILLA) { int absorbCeil = (int) Math.ceil(absorb); rowCount = (int) Math.ceil(absorb / 20); // Dark underlay for first row int texX = 17; int texY = Config.ABSORPTION_HEART_STYLE == AbsorptionHeartStyle.SHIELD ? 45 : 54; for (int i = 0; i < 10 && i < absorb / 2; ++i) { int y = top - 10 + (i == regen - 10 ? -2 : 0); drawTexturedModalRect(left + 8 * i, y, texX, texY, 9, 9, 0xFFFFFF); } // Draw the top two absorption rows, just the basic "hearts" texX = Config.ABSORPTION_HEART_STYLE == AbsorptionHeartStyle.SHIELD ? 26 : 0; texY = Config.ABSORPTION_HEART_STYLE == AbsorptionHeartStyle.SHIELD ? 0 : potionOffset; for (int i = Math.max(0, rowCount - 2); i < rowCount; ++i) { int renderHearts = Math.min((absorbCeil - 20 * i) / 2, 10); int rowColor = getColorForRow(i); boolean anythingDrawn; // Draw the hearts int x; int y; for (x = 0; x < renderHearts; ++x) { y = top - 10 + (x == regen - 10 ? -2 : 0); drawTexturedModalRect(left + 8 * x, y, texX, texY, 9, 9, rowColor); } anythingDrawn = x > 0; // Half heart on the end? if (absorbCeil % 2 == 1 && renderHearts < 10) { y = top - 10 + (x == regen - 10 ? -2 : 0); drawTexturedModalRect(left + 8 * renderHearts, y, texX + 9, texY, 9, 9, rowColor); anythingDrawn = true; } } // Add extra bits like outlines on top for (int i = 0; i < 10 && i < absorb / 2; ++i) { int y = top - 10 + (i == regen - 10 ? -2 : 0); if (Config.ABSORPTION_HEART_STYLE == AbsorptionHeartStyle.SHIELD) { // Golden hearts in center (shield style only) drawTexturedModalRect(left + 8 * i, y, 17, 36, 9, 9, 0xFFFFFF); } else if (Config.ABSORPTION_HEART_STYLE == AbsorptionHeartStyle.GOLD_OUTLINE) { // Golden outline drawTexturedModalRect(left + 8 * i, y, 17, 27, 9, 9, 0xFFFFFF); } // Shiny glint on top, same as hearts. if (!hardcoreMode || Config.ABSORPTION_HEART_STYLE == AbsorptionHeartStyle.SHIELD) { drawTexturedModalRect(left + 8 * i, y, 17, 0, 9, 9, 0xCCFFFFFF); } } } GlStateManager.disableBlend(); mc.renderEngine.bindTexture(Gui.ICONS); } private int getCustomHeartRowCount(int health) { return Config.REPLACE_VANILLA_HEARTS_WITH_CUSTOM ? MathHelper.ceil(health / 20f) : health / 20; } private void drawVanillaHearts(int health, boolean highlight, int healthLast, float healthMax, int rowHeight, int left, int top, int regen, int[] lowHealthBob, int TOP, int BACKGROUND, int MARGIN) { float absorb = MathHelper.ceil(Minecraft.getMinecraft().player.getAbsorptionAmount()); float absorbRemaining = absorb; float healthTotal = health + absorb; int iStart = MathHelper.ceil((healthMax + (Config.ABSORPTION_HEART_STYLE == AbsorptionHeartStyle.VANILLA ? absorb : 0)) / 2f) - 1; for (int i = iStart; i >= 0; --i) { int row = MathHelper.ceil((i + 1) / 10f) - 1; int x = left + i % 10 * 8; int y = top - row * rowHeight; if (health <= 4) y += lowHealthBob[MathHelper.clamp(i, 0, lowHealthBob.length - 1)]; if (i == regen) y -= 2; drawTexturedModalRect(x, y, BACKGROUND, TOP, 9, 9); if (highlight) { if (i * 2 + 1 < healthLast) drawTexturedModalRect(x, y, MARGIN + 54, TOP, 9, 9); else if (i * 2 + 1 == healthLast) drawTexturedModalRect(x, y, MARGIN + 63, TOP, 9, 9); } // TODO: Does this fix the rendering issues introduced in 1.3.27? if (absorbRemaining > 0f && Config.ABSORPTION_HEART_STYLE == AbsorptionHeartStyle.VANILLA) { if (absorbRemaining == absorb && absorb % 2f == 1f) { drawTexturedModalRect(x, y, MARGIN + 153, TOP, 9, 9); absorbRemaining -= 1f; } else { if (i * 2 + 1 < healthTotal) drawTexturedModalRect(x, y, MARGIN + 144, TOP, 9, 9); absorbRemaining -= 2f; } } else { if (i * 2 + 1 < health) drawTexturedModalRect(x, y, MARGIN + 36, TOP, 9, 9); else if (i * 2 + 1 == health) drawTexturedModalRect(x, y, MARGIN + 45, TOP, 9, 9); } } } private void renderHealthText(RenderGameOverlayEvent event, EntityPlayer player, TextStyle style, TextColor styleColor) { final float scale = style == TextStyle.ROWS ? 0.65f : 0.5f; final int width = event.getResolution().getScaledWidth(); final int height = event.getResolution().getScaledHeight(); final int left = (int) ((width / 2 - 91) / scale); // GuiIngameForge.left_height == 59 in normal cases. Making it a constant should fix some issues. final int top = (int) ((height - 59 + 21 + (1 / scale)) / scale); // Draw health string String healthString = style == TextStyle.HEALTH_AND_MAX ? (int) player.getHealth() + "/" + (int) player.getMaxHealth() : (int) Math.ceil(player.getHealth() / 20) + "x"; FontRenderer fontRenderer = Minecraft.getMinecraft().fontRenderer; int stringWidth = fontRenderer.getStringWidth(healthString); int color; switch (styleColor) { case GREEN_TO_RED: color = Color.HSBtoRGB(0.34f * playerHealth / player.getMaxHealth(), 0.7f, 1.0f); break; case PSYCHEDELIC: color = Color.HSBtoRGB( (ClientTickHandler.ticksInGame % COLOR_CHANGE_PERIOD) / COLOR_CHANGE_PERIOD, 0.55f * playerHealth / player.getMaxHealth(), 1.0f); break; case WHITE: default: color = 0xDDDDDD; break; } GlStateManager.pushMatrix(); GlStateManager.scale(scale, scale, 1f); fontRenderer.drawStringWithShadow(healthString, left - stringWidth - 2, top, color); GlStateManager.popMatrix(); } private void drawTexturedModalRect(int x, int y, int textureX, int textureY, int width, int height, int color) { float a = ((color >> 24) & 255) / 255f; if (a <= 0f) a = 1f; float r = ((color >> 16) & 255) / 255f; float g = ((color >> 8) & 255) / 255f; float b = (color & 255) / 255f; GlStateManager.color(r, g, b, a); drawTexturedModalRect(x, y, textureX, textureY, width, height); GlStateManager.color(1f, 1f, 1f, 1f); } private int getColorForRow(int row) { return Config.HEART_COLORS[row % Config.HEART_COLORS.length]; } private boolean showEffectHearts(EntityPlayer player) { return player.isPotionActive(MobEffects.POISON) || player.isPotionActive(MobEffects.WITHER); } private int effectHeartColor(EntityPlayer player) { if (player.isPotionActive(MobEffects.WITHER)) return 0x663E47; if (player.isPotionActive(MobEffects.POISON)) return 0x4E9331; return 0xFFFFFF; } }
src/main/java/net/silentchaos512/scalinghealth/client/HeartDisplayHandler.java
/* * Scaling Health * Copyright (C) 2018 SilentChaos512 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation version 3 * of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.silentchaos512.scalinghealth.client; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.Gui; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.attributes.IAttributeInstance; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.MobEffects; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.MathHelper; import net.minecraftforge.client.GuiIngameForge; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.silentchaos512.lib.config.ConfigBase; import net.silentchaos512.scalinghealth.ScalingHealth; import net.silentchaos512.scalinghealth.config.Config; import java.awt.*; import java.util.Random; /** * Handles display of regular and absorption hearts. * <p>For future reference, much of the vanilla code can be found in {@link GuiIngameForge}.</p> */ public class HeartDisplayHandler extends Gui { public enum TextStyle { DISABLED, ROWS, HEALTH_AND_MAX; private static final String COMMENT = "Determines what the text next to your hearts will display. DISABLED will display nothing, ROWS will display the number of remaining rows that have health left, and HEALTH_AND_MAX will display your actual health and max health values."; public static TextStyle loadFromConfig(ConfigBase config) { return config.loadEnum("Health Text Style", Config.CAT_CLIENT, TextStyle.class, ROWS, COMMENT); } } public enum TextColor { GREEN_TO_RED, WHITE, PSYCHEDELIC; public static final String COMMENT = "Determines the color of the text next to your hearts. GREEN_TO_RED displays green at full health, and moves to red as you lose health. WHITE will just be good old fashioned white text. Set to PSYCHEDELIC if you want to taste the rainbow."; public static TextColor loadFromConfig(ConfigBase config) { return config.loadEnum("Health Text Color", Config.CAT_CLIENT, TextColor.class, GREEN_TO_RED, COMMENT); } } public enum AbsorptionHeartStyle { SHIELD, GOLD_OUTLINE, VANILLA; public static final String COMMENT = "Determines how absorption hearts should be rendered."; public static AbsorptionHeartStyle loadDromConfig(ConfigBase config) { return config.loadEnum("Absorption Heart Style", Config.CAT_CLIENT, AbsorptionHeartStyle.class, SHIELD, COMMENT); } } public static final HeartDisplayHandler INSTANCE = new HeartDisplayHandler(); private static final float COLOR_CHANGE_PERIOD = 150; private static final ResourceLocation TEXTURE = new ResourceLocation(ScalingHealth.MOD_ID_LOWER, "textures/gui/hud.png"); private long lastSystemTime = 0; private int playerHealth = 0; private int lastPlayerHealth = 0; private Random rand = new Random(); private HeartDisplayHandler() { } @SubscribeEvent(receiveCanceled = true) public void onHealthBar(RenderGameOverlayEvent.Pre event) { Minecraft mc = Minecraft.getMinecraft(); EntityPlayer player = mc.player; // Health text TextStyle style = Config.HEART_DISPLAY_TEXT_STYLE; TextColor styleColor = Config.HEART_DISPLAY_TEXT_COLOR; if (event.getType() == ElementType.TEXT && style != TextStyle.DISABLED && mc.playerController.gameIsSurvivalOrAdventure()) { renderHealthText(event, player, style, styleColor); } // Hearts if (event.getType() == ElementType.HEALTH && Config.CHANGE_HEART_RENDERING) { event.setCanceled(true); renderHearts(event, mc, player); } } private void renderHearts(RenderGameOverlayEvent event, Minecraft mc, EntityPlayer player) { final boolean hardcoreMode = mc.world.getWorldInfo().isHardcoreModeEnabled(); int width = event.getResolution().getScaledWidth(); int height = event.getResolution().getScaledHeight(); GlStateManager.enableBlend(); int health = MathHelper.ceil(player.getHealth()); boolean highlight = player.hurtResistantTime / 3 % 2 == 1; int updateCounter = ClientTickHandler.ticksInGame; if (health < playerHealth && player.hurtResistantTime > 0 || health > playerHealth && player.hurtResistantTime > 0) { lastSystemTime = Minecraft.getSystemTime(); } if (Minecraft.getSystemTime() - lastSystemTime > 1000) { playerHealth = health; lastPlayerHealth = health; lastSystemTime = Minecraft.getSystemTime(); } playerHealth = health; int healthLast = lastPlayerHealth; IAttributeInstance attrMaxHealth = player.getEntityAttribute(SharedMonsterAttributes.MAX_HEALTH); float healthMax = Math.min((float) attrMaxHealth.getAttributeValue(), 20); float absorb = MathHelper.ceil(player.getAbsorptionAmount()); int healthRows = absorb > 0 ? 2 : 1; // MathHelper.ceil((healthMax + absorb) / 2f / 10f); int rowHeight = Math.max(10 - (healthRows - 2), 3); rand.setSeed(updateCounter * 312871); int[] lowHealthBob = new int[10]; for (int i = 0; i < lowHealthBob.length; ++i) lowHealthBob[i] = rand.nextInt(2); final int left = width / 2 - 91; final int top = height - GuiIngameForge.left_height; GuiIngameForge.left_height += healthRows * rowHeight; if (rowHeight != 10) GuiIngameForge.left_height += 10 - rowHeight; int regen = -1; if (player.isPotionActive(MobEffects.REGENERATION)) regen = updateCounter % 25; final int TOP = 9 * (hardcoreMode ? 5 : 0); final int BACKGROUND = (highlight ? 25 : 16); int MARGIN = 16; // if (player.isPotionActive(MobEffects.POISON)) // MARGIN += 36; // else if (player.isPotionActive(MobEffects.WITHER)) // MARGIN += 72; // Draw vanilla hearts drawVanillaHearts(health, highlight, healthLast, healthMax, rowHeight, left, top, regen, lowHealthBob, TOP, BACKGROUND, MARGIN); // int potionOffset = player.isPotionActive(MobEffects.WITHER) ? 18 // : (player.isPotionActive(MobEffects.POISON) ? 9 : 0) + (hardcoreMode ? 27 : 0); int potionOffset = hardcoreMode ? 27 : 0; // Draw extra hearts (only top 2 rows) mc.renderEngine.bindTexture(TEXTURE); health = MathHelper.ceil(player.getHealth()); int rowCount = getCustomHeartRowCount(health); int maxHealthRows = getCustomHeartRowCount((int) player.getMaxHealth()); for (int row = Math.max(0, rowCount - 2); row < rowCount; ++row) { int actualRow = row + (Config.REPLACE_VANILLA_HEARTS_WITH_CUSTOM ? 0 : 1); int renderHearts = Math.min((health - 20 * actualRow) / 2, 10); int rowColor = getColorForRow(row); boolean anythingDrawn; // Draw the hearts int j; int y; for (j = 0; j < renderHearts; ++j) { y = top + (j == regen ? -2 : 0); if (health <= 4) y += lowHealthBob[MathHelper.clamp(j, 0, lowHealthBob.length - 1)]; drawTexturedModalRect(left + 8 * j, y, 0, potionOffset, 9, 9, rowColor); } anythingDrawn = j > 0; // Half heart on the end? if (health % 2 == 1 && renderHearts < 10) { y = top + (j == regen ? -2 : 0); if (health <= 4) y += lowHealthBob[MathHelper.clamp(j, 0, lowHealthBob.length - 1)]; drawTexturedModalRect(left + 8 * renderHearts, y, 9, potionOffset, 9, 9, rowColor); anythingDrawn = true; } // Outline for last heart, to make seeing max health a little easier. if (Config.LAST_HEART_OUTLINE_ENABLED && anythingDrawn && row == maxHealthRows - 1) { // Get position of last partial/full heart j = (int) (Math.ceil(player.getMaxHealth() % 20f / 2f)) - 1; if (j < 0) j += 10; y = top + (j == regen ? -2 : 0); if (health <= 4) y += lowHealthBob[MathHelper.clamp(j, 0, lowHealthBob.length - 1)]; drawTexturedModalRect(left + 8 * j, y, 17, 9, 9, 9, Config.LAST_HEART_OUTLINE_COLOR); } } for (int i = 0; i < 10 && i < Math.ceil(health / 2f); ++i) { int y = top + (i == regen ? -2 : 0); if (health <= 4) y += lowHealthBob[MathHelper.clamp(i, 0, lowHealthBob.length - 1)]; // Effect hearts (poison, wither) if (showEffectHearts(player)) { int color = effectHeartColor(player); drawTexturedModalRect(left + 8 * i, y, 0, 54, 9, 9, color); } // Shiny glint on top of the hearts, a single white pixel in the upper left <3 if (!hardcoreMode) { drawTexturedModalRect(left + 8 * i, y, 17, 0, 9, 9, 0xCCFFFFFF); } } /* ========================== * Absorption hearts override * ========================== */ if (Config.ABSORPTION_HEART_STYLE != AbsorptionHeartStyle.VANILLA) { int absorbCeil = (int) Math.ceil(absorb); rowCount = (int) Math.ceil(absorb / 20); // Dark underlay for first row int texX = 17; int texY = Config.ABSORPTION_HEART_STYLE == AbsorptionHeartStyle.SHIELD ? 45 : 54; for (int i = 0; i < 10 && i < absorb / 2; ++i) { int y = top - 10 + (i == regen - 10 ? -2 : 0); drawTexturedModalRect(left + 8 * i, y, texX, texY, 9, 9, 0xFFFFFF); } // Draw the top two absorption rows, just the basic "hearts" texX = Config.ABSORPTION_HEART_STYLE == AbsorptionHeartStyle.SHIELD ? 26 : 0; texY = Config.ABSORPTION_HEART_STYLE == AbsorptionHeartStyle.SHIELD ? 0 : potionOffset; for (int i = Math.max(0, rowCount - 2); i < rowCount; ++i) { int renderHearts = Math.min((absorbCeil - 20 * i) / 2, 10); int rowColor = getColorForRow(i); boolean anythingDrawn; // Draw the hearts int x; int y; for (x = 0; x < renderHearts; ++x) { y = top - 10 + (x == regen - 10 ? -2 : 0); drawTexturedModalRect(left + 8 * x, y, texX, texY, 9, 9, rowColor); } anythingDrawn = x > 0; // Half heart on the end? if (absorbCeil % 2 == 1 && renderHearts < 10) { y = top - 10 + (x == regen - 10 ? -2 : 0); drawTexturedModalRect(left + 8 * renderHearts, y, texX + 9, texY, 9, 9, rowColor); anythingDrawn = true; } } // Add extra bits like outlines on top for (int i = 0; i < 10 && i < absorb / 2; ++i) { int y = top - 10 + (i == regen - 10 ? -2 : 0); if (Config.ABSORPTION_HEART_STYLE == AbsorptionHeartStyle.SHIELD) { // Golden hearts in center (shield style only) drawTexturedModalRect(left + 8 * i, y, 17, 36, 9, 9, 0xFFFFFF); } else if (Config.ABSORPTION_HEART_STYLE == AbsorptionHeartStyle.GOLD_OUTLINE) { // Golden outline drawTexturedModalRect(left + 8 * i, y, 17, 27, 9, 9, 0xFFFFFF); } // Shiny glint on top, same as hearts. if (!hardcoreMode || Config.ABSORPTION_HEART_STYLE == AbsorptionHeartStyle.SHIELD) { drawTexturedModalRect(left + 8 * i, y, 17, 0, 9, 9, 0xCCFFFFFF); } } } GlStateManager.disableBlend(); mc.renderEngine.bindTexture(Gui.ICONS); } private int getCustomHeartRowCount(int health) { return Config.REPLACE_VANILLA_HEARTS_WITH_CUSTOM ? MathHelper.ceil(health / 20f) : health / 20; } private void drawVanillaHearts(int health, boolean highlight, int healthLast, float healthMax, int rowHeight, int left, int top, int regen, int[] lowHealthBob, int TOP, int BACKGROUND, int MARGIN) { float absorb = MathHelper.ceil(Minecraft.getMinecraft().player.getAbsorptionAmount()); float absorbRemaining = absorb; float healthTotal = health + absorb; int iStart = MathHelper.ceil((healthMax + (Config.ABSORPTION_HEART_STYLE == AbsorptionHeartStyle.VANILLA ? absorb : 0)) / 2f) - 1; for (int i = iStart; i >= 0; --i) { int row = MathHelper.ceil((i + 1) / 10f) - 1; int x = left + i % 10 * 8; int y = top - row * rowHeight; if (health <= 4) y += lowHealthBob[MathHelper.clamp(i, 0, lowHealthBob.length - 1)]; if (i == regen) y -= 2; drawTexturedModalRect(x, y, BACKGROUND, TOP, 9, 9); if (highlight) { if (i * 2 + 1 < healthLast) drawTexturedModalRect(x, y, MARGIN + 54, TOP, 9, 9); else if (i * 2 + 1 == healthLast) drawTexturedModalRect(x, y, MARGIN + 63, TOP, 9, 9); } if (absorbRemaining > 0f) { if (absorbRemaining == absorb && absorb % 2f == 1f) { drawTexturedModalRect(x, y, MARGIN + 153, TOP, 9, 9); absorbRemaining -= 1f; } else { if (i * 2 + 1 < healthTotal) drawTexturedModalRect(x, y, MARGIN + 144, TOP, 9, 9); absorbRemaining -= 2f; } } else { if (i * 2 + 1 < health) drawTexturedModalRect(x, y, MARGIN + 36, TOP, 9, 9); else if (i * 2 + 1 == health) drawTexturedModalRect(x, y, MARGIN + 45, TOP, 9, 9); } } } private void renderHealthText(RenderGameOverlayEvent event, EntityPlayer player, TextStyle style, TextColor styleColor) { final float scale = style == TextStyle.ROWS ? 0.65f : 0.5f; final int width = event.getResolution().getScaledWidth(); final int height = event.getResolution().getScaledHeight(); final int left = (int) ((width / 2 - 91) / scale); // GuiIngameForge.left_height == 59 in normal cases. Making it a constant should fix some issues. final int top = (int) ((height - 59 + 21 + (1 / scale)) / scale); // Draw health string String healthString = style == TextStyle.HEALTH_AND_MAX ? (int) player.getHealth() + "/" + (int) player.getMaxHealth() : (int) Math.ceil(player.getHealth() / 20) + "x"; FontRenderer fontRenderer = Minecraft.getMinecraft().fontRenderer; int stringWidth = fontRenderer.getStringWidth(healthString); int color; switch (styleColor) { case GREEN_TO_RED: color = Color.HSBtoRGB(0.34f * playerHealth / player.getMaxHealth(), 0.7f, 1.0f); break; case PSYCHEDELIC: color = Color.HSBtoRGB( (ClientTickHandler.ticksInGame % COLOR_CHANGE_PERIOD) / COLOR_CHANGE_PERIOD, 0.55f * playerHealth / player.getMaxHealth(), 1.0f); break; case WHITE: default: color = 0xDDDDDD; break; } GlStateManager.pushMatrix(); GlStateManager.scale(scale, scale, 1f); fontRenderer.drawStringWithShadow(healthString, left - stringWidth - 2, top, color); GlStateManager.popMatrix(); } private void drawTexturedModalRect(int x, int y, int textureX, int textureY, int width, int height, int color) { float a = ((color >> 24) & 255) / 255f; if (a <= 0f) a = 1f; float r = ((color >> 16) & 255) / 255f; float g = ((color >> 8) & 255) / 255f; float b = (color & 255) / 255f; GlStateManager.color(r, g, b, a); drawTexturedModalRect(x, y, textureX, textureY, width, height); GlStateManager.color(1f, 1f, 1f, 1f); } private int getColorForRow(int row) { return Config.HEART_COLORS[row % Config.HEART_COLORS.length]; } private boolean showEffectHearts(EntityPlayer player) { return player.isPotionActive(MobEffects.POISON) || player.isPotionActive(MobEffects.WITHER); } private int effectHeartColor(EntityPlayer player) { if (player.isPotionActive(MobEffects.WITHER)) return 0x663E47; if (player.isPotionActive(MobEffects.POISON)) return 0x4E9331; return 0xFFFFFF; } }
Should fix absorption hearts trailing normal hearts in some cases
src/main/java/net/silentchaos512/scalinghealth/client/HeartDisplayHandler.java
Should fix absorption hearts trailing normal hearts in some cases
<ide><path>rc/main/java/net/silentchaos512/scalinghealth/client/HeartDisplayHandler.java <ide> drawTexturedModalRect(x, y, MARGIN + 63, TOP, 9, 9); <ide> } <ide> <del> if (absorbRemaining > 0f) { <add> // TODO: Does this fix the rendering issues introduced in 1.3.27? <add> if (absorbRemaining > 0f && Config.ABSORPTION_HEART_STYLE == AbsorptionHeartStyle.VANILLA) { <ide> if (absorbRemaining == absorb && absorb % 2f == 1f) { <ide> drawTexturedModalRect(x, y, MARGIN + 153, TOP, 9, 9); <ide> absorbRemaining -= 1f;
JavaScript
mpl-2.0
96bcd99ed50f043dc0d1b4ce21d7dee4c9652bbe
0
CUModSquad/Camelot-Unchained,Ajackster/Camelot-Unchained,saddieeiddas/Camelot-Unchained,csegames/Camelot-Unchained,Mehuge/Camelot-Unchained,Mehuge/Camelot-Unchained,Mehuge/Camelot-Unchained,CUModSquad/Camelot-Unchained,Ajackster/Camelot-Unchained,Ajackster/Camelot-Unchained,csegames/Camelot-Unchained,csegames/Camelot-Unchained,saddieeiddas/Camelot-Unchained,saddieeiddas/Camelot-Unchained,CUModSquad/Camelot-Unchained
const webpack = require('webpack'); const path = require('path'); const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin'); const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; module.exports = function (e, rawArgv) { const argv = rawArgv ? rawArgv : {}; const mode = argv.mode ? argv.mode : 'development'; const env = { NODE_ENV: process.env.NODE_ENV || mode, }; const outputPath = process.env.CUUI_DEV_OUTPUT_PATH ? process.env.CUUI_DEV_OUTPUT_PATH : argv.watch ? path.resolve(__dirname, 'dist') : path.resolve(__dirname, 'build'); const config = { mode, devtool: mode === 'development' ? 'source-map' : 'source-map', entry: { hud: ['./src/index.tsx'], }, output: { path: outputPath, filename: 'js/[name].js', chunkFilename: 'js/[name].js', }, optimization: { minimize: mode === 'production' ? false /* make this true if minimization is desired */ : false, splitChunks: { chunks: 'async', cacheGroups: { vendors: { test: /[\\/]node_modules[\\/]/, chunks: 'all', priority: -10, }, gqlDocuments: { test: /gqlDocuments/, chunks: 'all', priority: -10, }, default: { minChunks: 2, priority: -20, chunks: 'async', reuseExistingChunk: true } }, }, runtimeChunk: 'single', }, resolve: { alias: { 'react': path.dirname( require.resolve('react/package.json') ), components: path.resolve(__dirname, 'src/components'), 'UI/TabbedDialog': path.resolve(__dirname, 'src/components/UI/TabbedDialog/index'), UI: path.resolve(__dirname, 'src/components/UI'), actions: path.resolve(__dirname, 'src/services/actions'), lib: path.resolve(__dirname, 'src/lib'), services: path.resolve(__dirname, 'src/services'), widgets: path.resolve(__dirname, 'src/widgets'), HUDContext: path.resolve(__dirname, 'src/components/HUD/context'), }, extensions: ['.web.ts', '.ts', '.web.tsx', '.tsx', '.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'], }, module: { rules: [ { oneOf: [ { test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/], loader: require.resolve('url-loader'), options: { limit: 10000, name: 'static/media/[name].[ext]', }, }, { test: /\.tsx?$/, exclude: /node_modules/, use: [ { loader: require.resolve('cache-loader'), }, { loader: require.resolve('thread-loader'), options: { workers: require('os').cpus().length - 1, }, }, { loader: require.resolve('babel-loader'), options: { cacheDirectory: true }, }, { loader: require.resolve('ts-loader'), options: { transpileOnly: true, happyPackMode: true, compilerOptions: { sourceMap: true, }, } } ] }, { exclude: [/\.js$/, /\.html$/, /\.json$/, /\.tsx?$/], loader: require.resolve('file-loader'), options: { name: 'static/media/[name].[ext]', }, }, ], }, ], }, plugins: [ new ForkTsCheckerWebpackPlugin({ checkSyntacticErrors: true, tslint: true, // can turn this off if required formatter: 'codeframe', async: true, }), new webpack.DefinePlugin({ 'process.env': Object.keys(env).reduce((e, key) => { e[key] = JSON.stringify(env[key]); return e; }, {}), }), // new webpack.HotModuleReplacementPlugin(), new BundleAnalyzerPlugin({ analyzerMode: 'disabled', generateStatsFile: true, statsFilename: 'asset-stats.json', }), ], node: { dgram: 'empty', fs: 'empty', net: 'empty', tls: 'empty', child_process: 'empty', dns: 'empty', }, performance: { hints: false, }, }; return config; }
game/hud/webpack.config.js
const webpack = require('webpack'); const path = require('path'); const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin'); const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; module.exports = function (e, rawArgv) { const argv = rawArgv ? rawArgv : {}; const mode = argv.mode ? argv.mode : 'development'; const env = { NODE_ENV: process.env.NODE_ENV || mode, }; const outputPath = process.env.CUUI_DEV_OUTPUT_PATH ? process.env.CUUI_DEV_OUTPUT_PATH : argv.watch ? path.resolve(__dirname, 'dist') : path.resolve(__dirname, 'build'); const config = { mode, devtool: mode === 'development' ? 'eval-source-map' : 'source-map', entry: { hud: ['./src/index.tsx'], }, output: { path: outputPath, filename: 'js/[name].js', chunkFilename: 'js/[name].js', }, optimization: { minimize: mode === 'production' ? false /* make this true if minimization is desired */ : false, splitChunks: { chunks: 'async', cacheGroups: { vendors: { test: /[\\/]node_modules[\\/]/, chunks: 'all', priority: -10, }, gqlDocuments: { test: /gqlDocuments/, chunks: 'all', priority: -10, }, default: { minChunks: 2, priority: -20, chunks: 'async', reuseExistingChunk: true } }, }, runtimeChunk: 'single', }, resolve: { alias: { 'react': path.dirname( require.resolve('react/package.json') ), components: path.resolve(__dirname, 'src/components'), 'UI/TabbedDialog': path.resolve(__dirname, 'src/components/UI/TabbedDialog/index'), UI: path.resolve(__dirname, 'src/components/UI'), actions: path.resolve(__dirname, 'src/services/actions'), lib: path.resolve(__dirname, 'src/lib'), services: path.resolve(__dirname, 'src/services'), widgets: path.resolve(__dirname, 'src/widgets'), HUDContext: path.resolve(__dirname, 'src/components/HUD/context'), }, extensions: ['.web.ts', '.ts', '.web.tsx', '.tsx', '.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'], }, module: { rules: [ { oneOf: [ { test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/], loader: require.resolve('url-loader'), options: { limit: 10000, name: 'static/media/[name].[ext]', }, }, { test: /\.tsx?$/, exclude: /node_modules/, use: [ { loader: require.resolve('cache-loader'), }, { loader: require.resolve('thread-loader'), options: { workers: require('os').cpus().length - 1, }, }, { loader: require.resolve('babel-loader'), options: { cacheDirectory: true }, }, { loader: require.resolve('ts-loader'), options: { transpileOnly: true, happyPackMode: true, compilerOptions: { sourceMap: true, }, } } ] }, { exclude: [/\.js$/, /\.html$/, /\.json$/, /\.tsx?$/], loader: require.resolve('file-loader'), options: { name: 'static/media/[name].[ext]', }, }, ], }, ], }, plugins: [ new ForkTsCheckerWebpackPlugin({ checkSyntacticErrors: true, tslint: true, // can turn this off if required formatter: 'codeframe', async: true, }), new webpack.DefinePlugin({ 'process.env': Object.keys(env).reduce((e, key) => { e[key] = JSON.stringify(env[key]); return e; }, {}), }), // new webpack.HotModuleReplacementPlugin(), new BundleAnalyzerPlugin({ analyzerMode: 'disabled', generateStatsFile: true, statsFilename: 'asset-stats.json', }), ], node: { dgram: 'empty', fs: 'empty', net: 'empty', tls: 'empty', child_process: 'empty', dns: 'empty', }, performance: { hints: false, }, }; return config; }
change webpack sourcemap type (#213)
game/hud/webpack.config.js
change webpack sourcemap type (#213)
<ide><path>ame/hud/webpack.config.js <ide> <ide> const config = { <ide> mode, <del> devtool: mode === 'development' ? 'eval-source-map' : 'source-map', <add> devtool: mode === 'development' ? 'source-map' : 'source-map', <ide> entry: { <ide> hud: ['./src/index.tsx'], <ide> },
Java
apache-2.0
4cccc599e6607b135a84d37c027b15371a284784
0
adessaigne/camel,cunningt/camel,apache/camel,apache/camel,christophd/camel,cunningt/camel,apache/camel,tdiesler/camel,cunningt/camel,nikhilvibhav/camel,nikhilvibhav/camel,tdiesler/camel,pax95/camel,christophd/camel,tadayosi/camel,apache/camel,tadayosi/camel,nikhilvibhav/camel,adessaigne/camel,pax95/camel,cunningt/camel,tdiesler/camel,tadayosi/camel,nikhilvibhav/camel,cunningt/camel,adessaigne/camel,christophd/camel,adessaigne/camel,christophd/camel,tadayosi/camel,christophd/camel,pax95/camel,pax95/camel,pax95/camel,tadayosi/camel,adessaigne/camel,pax95/camel,tdiesler/camel,apache/camel,cunningt/camel,tdiesler/camel,adessaigne/camel,apache/camel,christophd/camel,tadayosi/camel,tdiesler/camel
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.kafka; import java.util.Properties; import java.util.concurrent.ExecutorService; import org.apache.camel.Category; import org.apache.camel.Consumer; import org.apache.camel.MultipleConsumersSupport; import org.apache.camel.Processor; import org.apache.camel.Producer; import org.apache.camel.spi.ClassResolver; import org.apache.camel.spi.UriEndpoint; import org.apache.camel.spi.UriParam; import org.apache.camel.support.DefaultEndpoint; import org.apache.camel.support.SynchronousDelegateProducer; import org.apache.camel.util.CastUtils; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.producer.Partitioner; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.security.auth.AuthenticateCallbackHandler; import org.apache.kafka.common.serialization.Deserializer; import org.apache.kafka.common.serialization.Serializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Sent and receive messages to/from an Apache Kafka broker. */ @UriEndpoint(firstVersion = "2.13.0", scheme = "kafka", title = "Kafka", syntax = "kafka:topic", category = { Category.MESSAGING }) public class KafkaEndpoint extends DefaultEndpoint implements MultipleConsumersSupport { private static final Logger LOG = LoggerFactory.getLogger(KafkaEndpoint.class); private static final String CALLBACK_HANDLER_CLASS_CONFIG = "sasl.login.callback.handler.class"; @UriParam private KafkaConfiguration configuration = new KafkaConfiguration(); public KafkaEndpoint() { } public KafkaEndpoint(String endpointUri, KafkaComponent component) { super(endpointUri, component); } @Override public KafkaComponent getComponent() { return (KafkaComponent) super.getComponent(); } public KafkaConfiguration getConfiguration() { return configuration; } public void setConfiguration(KafkaConfiguration configuration) { this.configuration = configuration; } @Override public Consumer createConsumer(Processor processor) throws Exception { KafkaConsumer consumer = new KafkaConsumer(this, processor); configureConsumer(consumer); return consumer; } @Override public Producer createProducer() throws Exception { KafkaProducer producer = createProducer(this); if (getConfiguration().isSynchronous()) { return new SynchronousDelegateProducer(producer); } else { return producer; } } @Override public boolean isMultipleConsumersSupported() { return true; } <T> Class<T> loadClass(Object o, ClassResolver resolver, Class<T> type) { if (o == null || o instanceof Class) { return CastUtils.cast((Class<?>) o); } String name = o.toString(); Class<T> c = resolver.resolveClass(name, type); if (c == null) { c = resolver.resolveClass(name, type, getClass().getClassLoader()); } if (c == null) { c = resolver.resolveClass(name, type, org.apache.kafka.clients.producer.KafkaProducer.class.getClassLoader()); } return c; } void replaceWithClass(Properties props, String key, ClassResolver resolver, Class<?> type) { Class<?> c = loadClass(props.get(key), resolver, type); if (c != null) { props.put(key, c); } } public void updateClassProperties(Properties props) { try { if (getCamelContext() != null) { ClassResolver resolver = getCamelContext().getClassResolver(); replaceWithClass(props, ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, resolver, Serializer.class); replaceWithClass(props, ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, resolver, Serializer.class); replaceWithClass(props, ProducerConfig.PARTITIONER_CLASS_CONFIG, resolver, Partitioner.class); replaceWithClass(props, ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, resolver, Deserializer.class); replaceWithClass(props, ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, resolver, Deserializer.class); // because he property is not available in Kafka client, use a static string replaceWithClass(props, CALLBACK_HANDLER_CLASS_CONFIG, resolver, AuthenticateCallbackHandler.class); } } catch (Exception t) { // can ignore and Kafka itself might be able to handle it, if not, // it will throw an exception LOG.debug("Problem loading classes for Serializers", t); } } public ExecutorService createExecutor() { return getCamelContext().getExecutorServiceManager().newFixedThreadPool(this, "KafkaConsumer[" + configuration.getTopic() + "]", configuration.getConsumerStreams()); } public ExecutorService createProducerExecutor() { int core = getConfiguration().getWorkerPoolCoreSize(); int max = getConfiguration().getWorkerPoolMaxSize(); return getCamelContext().getExecutorServiceManager().newThreadPool(this, "KafkaProducer[" + configuration.getTopic() + "]", core, max); } protected KafkaProducer createProducer(KafkaEndpoint endpoint) { return new KafkaProducer(endpoint); } }
components/camel-kafka/src/main/java/org/apache/camel/component/kafka/KafkaEndpoint.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.kafka; import java.util.Properties; import java.util.concurrent.ExecutorService; import org.apache.camel.Category; import org.apache.camel.Consumer; import org.apache.camel.MultipleConsumersSupport; import org.apache.camel.Processor; import org.apache.camel.Producer; import org.apache.camel.spi.ClassResolver; import org.apache.camel.spi.UriEndpoint; import org.apache.camel.spi.UriParam; import org.apache.camel.support.DefaultEndpoint; import org.apache.camel.support.SynchronousDelegateProducer; import org.apache.camel.util.CastUtils; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.producer.Partitioner; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.security.auth.AuthenticateCallbackHandler; import org.apache.kafka.common.serialization.Deserializer; import org.apache.kafka.common.serialization.Serializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Sent and receive messages to/from an Apache Kafka broker. */ @UriEndpoint(firstVersion = "2.13.0", scheme = "kafka", title = "Kafka", syntax = "kafka:topic", category = { Category.MESSAGING }) public class KafkaEndpoint extends DefaultEndpoint implements MultipleConsumersSupport { private static final Logger LOG = LoggerFactory.getLogger(KafkaEndpoint.class); @UriParam private KafkaConfiguration configuration = new KafkaConfiguration(); public KafkaEndpoint() { } public KafkaEndpoint(String endpointUri, KafkaComponent component) { super(endpointUri, component); } @Override public KafkaComponent getComponent() { return (KafkaComponent) super.getComponent(); } public KafkaConfiguration getConfiguration() { return configuration; } public void setConfiguration(KafkaConfiguration configuration) { this.configuration = configuration; } @Override public Consumer createConsumer(Processor processor) throws Exception { KafkaConsumer consumer = new KafkaConsumer(this, processor); configureConsumer(consumer); return consumer; } @Override public Producer createProducer() throws Exception { KafkaProducer producer = createProducer(this); if (getConfiguration().isSynchronous()) { return new SynchronousDelegateProducer(producer); } else { return producer; } } @Override public boolean isMultipleConsumersSupported() { return true; } <T> Class<T> loadClass(Object o, ClassResolver resolver, Class<T> type) { if (o == null || o instanceof Class) { return CastUtils.cast((Class<?>) o); } String name = o.toString(); Class<T> c = resolver.resolveClass(name, type); if (c == null) { c = resolver.resolveClass(name, type, getClass().getClassLoader()); } if (c == null) { c = resolver.resolveClass(name, type, org.apache.kafka.clients.producer.KafkaProducer.class.getClassLoader()); } return c; } void replaceWithClass(Properties props, String key, ClassResolver resolver, Class<?> type) { Class<?> c = loadClass(props.get(key), resolver, type); if (c != null) { props.put(key, c); } } public void updateClassProperties(Properties props) { try { if (getCamelContext() != null) { ClassResolver resolver = getCamelContext().getClassResolver(); replaceWithClass(props, ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, resolver, Serializer.class); replaceWithClass(props, ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, resolver, Serializer.class); replaceWithClass(props, ProducerConfig.PARTITIONER_CLASS_CONFIG, resolver, Partitioner.class); replaceWithClass(props, ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, resolver, Deserializer.class); replaceWithClass(props, ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, resolver, Deserializer.class); // as long as the property is not available in Kafka client, use a static string final String CH_PROPERTY = "sasl.login.callback.handler.class"; replaceWithClass(props, CH_PROPERTY, resolver, AuthenticateCallbackHandler.class); } } catch (Exception t) { // can ignore and Kafka itself might be able to handle it, if not, // it will throw an exception LOG.debug("Problem loading classes for Serializers", t); } } public ExecutorService createExecutor() { return getCamelContext().getExecutorServiceManager().newFixedThreadPool(this, "KafkaConsumer[" + configuration.getTopic() + "]", configuration.getConsumerStreams()); } public ExecutorService createProducerExecutor() { int core = getConfiguration().getWorkerPoolCoreSize(); int max = getConfiguration().getWorkerPoolMaxSize(); return getCamelContext().getExecutorServiceManager().newThreadPool(this, "KafkaProducer[" + configuration.getTopic() + "]", core, max); } protected KafkaProducer createProducer(KafkaEndpoint endpoint) { return new KafkaProducer(endpoint); } }
CAMEL-16138: Resolve class of AuthenticationCallBackHandler to avoid ClassNotFoundException in OSGI environment. (#5188)
components/camel-kafka/src/main/java/org/apache/camel/component/kafka/KafkaEndpoint.java
CAMEL-16138: Resolve class of AuthenticationCallBackHandler to avoid ClassNotFoundException in OSGI environment. (#5188)
<ide><path>omponents/camel-kafka/src/main/java/org/apache/camel/component/kafka/KafkaEndpoint.java <ide> public class KafkaEndpoint extends DefaultEndpoint implements MultipleConsumersSupport { <ide> <ide> private static final Logger LOG = LoggerFactory.getLogger(KafkaEndpoint.class); <add> <add> private static final String CALLBACK_HANDLER_CLASS_CONFIG = "sasl.login.callback.handler.class"; <ide> <ide> @UriParam <ide> private KafkaConfiguration configuration = new KafkaConfiguration(); <ide> replaceWithClass(props, ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, resolver, Deserializer.class); <ide> replaceWithClass(props, ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, resolver, Deserializer.class); <ide> <del> // as long as the property is not available in Kafka client, use a static string <del> final String CH_PROPERTY = "sasl.login.callback.handler.class"; <del> replaceWithClass(props, CH_PROPERTY, resolver, AuthenticateCallbackHandler.class); <add> // because he property is not available in Kafka client, use a static string <add> replaceWithClass(props, CALLBACK_HANDLER_CLASS_CONFIG, resolver, AuthenticateCallbackHandler.class); <ide> } <ide> } catch (Exception t) { <ide> // can ignore and Kafka itself might be able to handle it, if not,
JavaScript
mit
c8867bce7cfa490c5e155e919f59a3b41813ffae
0
bruecksen/isimip,bruecksen/isimip,bruecksen/isimip,bruecksen/isimip
$(function() { // Die Tabllen im widget-table haben spezielle Funktionen wie Paginierung, function updateTable(table) { var activepage = table.data('activepage'); var filter = table.data('filter'); var rowsperpage = table.data('rowsperpage'); var searchvalue = table.data('searchvalue'); // set all rows to show and then apply filters, search and pagination table.find('tbody tr').addClass('widget-table-show'); // disable rows by filter // iterate filters $.each(filter, function(colnumber, value) { // console.log('apply filer for colnumber', colnumber, 'and value', value); // iterate rows table.find('tbody tr').each(function() { // hide rows not matching filter var row = $(this); var showcolline = false; row.find('td:nth-child(' + colnumber + ')').find('.widget-table-col-line').each(function() { var colline = $(this); var collinetext = colline.text(); // console.log($.trim(collinetext), $.trim(value)); if ( $.trim(collinetext) == $.trim(value) ) { showcolline = true; } }); if (!showcolline) { row.removeClass('widget-table-show'); } }); }); // disable rows by search string var searchwords = searchvalue.match(/\S+/g); if (searchwords) { // iterate rows table.find('tbody tr').each(function() { // hide rows not matching filter var row = $(this); var hit = true; // if all words are somewhere in the row // iterate search words $.each(searchwords, function(i, searchword) { var wordhit = false; // if this word is somewhere in the row searchword = searchword.toLowerCase(); row.find('td').each(function() { // does any column contain the word? if ($(this).text().toLowerCase().indexOf(searchword) > -1) wordhit = true; }); if (!wordhit) hit = false; // fail }); if (!hit) row.removeClass('widget-table-show'); }); } // Pagination var rowsintable = table.find('tbody tr.widget-table-show').length; // rows in the table, all pages // show or hide message that no rows to show if (rowsintable) { table.find('.widget-table-noentriesmessage td').hide(); } else { table.find('.widget-table-noentriesmessage td').show(); } var numberofpages = Math.ceil(rowsintable / rowsperpage); // save back table.data('numberofpages', numberofpages); // hide rows in other pages table.find('tbody tr.widget-table-show').each(function(rownumber) { if ((rowsperpage * (activepage-1) > rownumber) || (rowsperpage * activepage <= rownumber)) { $(this).removeClass('widget-table-show'); } }); // show the pagination links needed table.find('.widget-pagination-pagelink').each(function() { if (($(this).data('pagenumber') > numberofpages) || (numberofpages < 2)) { $(this).hide(); } else { $(this).show(); } }); table.find('tbody tr:not(.widget-table-show)').hide(); table.find('tbody tr.widget-table-show').show().removeClass('widget-table-show'); table.find('.widget-pagination-pagelink:not([data-pagenumber='+ activepage +'])').removeClass('widget-pagination-pagelink-active'); table.find('.widget-pagination-pagelink[data-pagenumber='+ activepage +']').addClass('widget-pagination-pagelink-active'); // Update status in prev next buttons: if (activepage == 1) { table.find('.widget-pagination-prevbutton').addClass('disabled'); } else { table.find('.widget-pagination-prevbutton').removeClass('disabled'); } if (activepage >= numberofpages) { // ( when numberofpages = 0 is activepage still 1 ) table.find('.widget-pagination-nextbutton').addClass('disabled'); } else { table.find('.widget-pagination-nextbutton').removeClass('disabled'); } // Update links to download CSV or PDF with current filter $('a[data-tableid]').each(function() { var filternames = table.data('filternames'); var param = ""; $.each(filter, function(colnumber, value) { param += "&" + encodeURIComponent([filternames[colnumber]]) + "=" + encodeURIComponent(value); }); if (searchvalue) { param += "&searchvalue=" + encodeURIComponent( searchvalue ) } if (param) { // replace first & with ? param = param.replace('&','?'); } var baseurl = $(this).attr('href'); // Strip parameter if (baseurl.indexOf('?') > 0) { baseurl = baseurl.substring(0, baseurl.indexOf('?')); } $(this).attr('href', baseurl + param); }); console.log('Table updated. activepage:',activepage,'filter:',filter,'rowsperpage:',rowsperpage,'rowsintable:',rowsintable,'numberofpages:',numberofpages, 'searchvalue:', searchvalue); $(window).trigger('colsreordered'); // Update URL // TODO } $('.widget-table').each(function() { var table = $(this); // initialize table settings var filter = table.data('filter'); if (!filter) table.data('filter', {}); var activepage = table.data('activepage'); if (!activepage) table.data('activepage', 1); var rowsperpage = table.data('rowsperpage'); if (!rowsperpage) table.data('rowsperpage', 2000); var searchvalue = table.data('searchvalue'); if (!searchvalue) table.data('searchvalue', ''); table.find('.widget-table-showmore-button').click(function() { table.find('tbody tr').show(); $(this).remove(); }); // Click on page navigation table.find('.widget-pagination-pagelink').click(function(event) { event.preventDefault(); table.data('activepage', $(this).data('pagenumber')); updateTable(table); }); table.find('.widget-pagination-prevbutton').click(function() { var activepage = table.data('activepage'); if (activepage > 1) activepage--; table.data('activepage', activepage); updateTable(table); }); table.find('.widget-pagination-nextbutton').click(function() { var activepage = table.data('activepage'); var numberofpages = table.data('numberofpages'); if (activepage < numberofpages) activepage++; // console.log('Button clicked. Now: activepage', activepage, 'numberofpages',numberofpages); table.data('activepage', activepage); updateTable(table); }); }); $('.widget-table-selector').each(function() { var table = $('#' + $(this).data('tableid')); var filter = table.data('filter'); var filternames = {}; // name attributes of filters $(this).find('select').each(function() { var selector = $(this); var colnumber = selector.data('colnumber'); filternames[colnumber] = selector.attr('name'); selector.change(function() { // Show first page after filter change table.data('activepage', 1); var filtervalue = selector.val(); if (filtervalue != 'tableselectordefaultall') { // set filter // console.log('set filter for col ', colnumber, ' filtervalue: ', filtervalue); filter[ "" + colnumber ] = filtervalue; } else { // unset filter // console.log('unset filter for col ', colnumber); delete filter[ "" + colnumber ]; } updateTable(table); }); }); table.data('filternames', filternames); $(this).find('.widget-table-selector-search').on('keyup change paste input', function() { // Show first page after filter change table.data('activepage', 1); table.data('searchvalue', $(this).val()); updateTable(table); }); }); }); $(function() { $('.widget-expandable .widget-expandable-listitem-toggleable .widget-expandable-listitem-term').click(function() { $(this).closest('.widget-expandable-listitem').toggleClass('widget-expandable-listitem-term-open'); }); }); $(function() { $('.widget-singleselect, .widget-multiselect').each(function() { var selectfield = $(this); var containerChecked = selectfield.find('.widget-options-checked'); var containerNotChecked = selectfield.find('.widget-options-notchecked'); function sortItems() { // Put selected to top and unselected to bottom container // Eventually sort items alphabetically containerChecked.find('label').each(function() { // move unchecked items down if (!$(this).find('input').prop('checked')) { var item = $(this).detach(); item.appendTo( containerNotChecked ); } }); containerNotChecked.find('label').each(function() { // move checked items up if ($(this).find('input').prop('checked')) { var item = $(this).detach(); item.appendTo( containerChecked ); } }); } if (selectfield.hasClass('widget-multiselect-nullable')) { // Radios are deselectable selectfield.on('click', '.widget-options-checked label', function(event) { // deselect this $(this).find('input').prop('checked', false); // Nicht gleich wieder aktivieren. event.preventDefault(); // Vorsichtshalber nochmal sortieren. sortItems(); }); } selectfield.on('change', 'input', function() { sortItems(); }); selectfield.find('.widget-select-customvalue').keypress(function (event) { var key = event.which; if(key == 13) { // the enter key code var value = $(this).val(); // remove options that were manually entered before if this is a radio var singleselect = $(this).hasClass('widget-select-customvalue-singleselect'); if (singleselect) { selectfield.find('.widget-select-newcustomvalue').remove(); } // TODO: Make sure item is no duplicate // clone item template var newitem = $(selectfield.find('.widget-options-template').html()); newitem .addClass('widget-select-newcustomvalue') .find('input') .prop('checked', true) .prop('value', value) .parent() .find('span').text(value); containerChecked.append(newitem); sortItems(); // reset input $(this).val(''); // Do not submit form event.preventDefault(); return false; } }); }); }); $(function() { $('.seeallblock .widget-readmorelink').click(function(event) { event.preventDefault(); $(this).closest('.seeallblock').find('.col-sm-3').show(); $(this).remove(); $(window).trigger('resize'); }); }); $(function() { // Smooth scrolling to anchors // https://stackoverflow.com/questions/14804941 $("a.anchor-scroll").on('click', function(e) { e.preventDefault(); var hash = this.hash; $('html, body').stop().animate({ scrollTop: $(this.hash).offset().top }, 600, function(){ window.location.hash = hash; }); }); }); $(function() { function alignrows() { // reset height of teasers $('.widget-page-teaser-magicgrow').css('min-height', 0); // Grow page teasers to row height $('.widget-page-teaser-magicgrow').each(function() { var pageTeaser = $(this); var row = pageTeaser.closest('.row'); // Do nothing for XS if (pageTeaser.find('.widget-page-teaser-xs-detector').is(':visible')) { return; } var rowHeight = row.height(); var col = row.find('> div').has(pageTeaser); var colHeight = col.height(); var pageTeaserHeight = pageTeaser.outerHeight(); // set min height pageTeaser.css('min-height', pageTeaserHeight + rowHeight - colHeight); }); } $(window).on('resize load', function() { alignrows(); }); setTimeout(alignrows, 500); }); $(function() { function aligncols() { // Grow page teasers to row height $('.widget-table').each(function() { var table = $(this); var tableWidth = table.width(); var firstRowCols = table.find('tbody > tr > td'); // reset width of cols firstRowCols.css('width', 'auto'); // force table cols to maximum of 50% table width firstRowCols.each(function() { if ($(this).width() > tableWidth * 0.5) { $(this).width(tableWidth * 0.5); } }); }); console.log('Table Colums set to max 50% width.'); } $(window).on('resize colsreordered', function() { aligncols(); }); aligncols(); }); $(function() { $('abbr[data-original-title], abbr[title]').each(function() { var initiator = $(this); initiator.popover({ 'template': '<div class="popover" role="tooltip"><div class="arrow"></div><div class="popover-content"></div></div>', 'content': initiator.attr('title'), }); // http://stackoverflow.com/questions/32581987/need-click-twice-after-hide-a-shown-bootstrap-popover initiator.on('hidden.bs.popover', function (e) { $(e.target).data("bs.popover").inState = { click: false, hover: false, focus: false } }); // Close popover on click outside initiating element $('body').click(function(e) { var target = $(e.target); if (!target.closest(initiator).length) { initiator.popover('hide'); } }); }); }); $(function() { // Paper editor Date.prototype.yyyymmdd = function() { var yyyy = this.getFullYear().toString(); var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based var dd = this.getDate().toString(); return yyyy +"-"+ (mm[1]?mm:"0"+mm[0]) +"-"+ (dd[1]?dd:"0"+dd[0]); // padding }; $('.widget-paper-editor').each(function() { var paperEditor = $(this); function checkMaxPaperCount() { var maxPaperCount = paperEditor.data('maxpapercount'); if (!maxPaperCount) return; var paperCount = paperEditor.find('.widget-paper-list .widget-paper-visualisation').length; // Show buttons for adding new papers only when allowed number of papers // larger than actual number of papers. if (maxPaperCount <= paperCount) { paperEditor.find('.widget-paper-addbuttons').hide(); } else { paperEditor.find('.widget-paper-addbuttons').show(); } } function addPaper(title) { if (title) { var url = paperEditor.data('apibaseurl'); // Same Origin mirror of this: http://api.crossref.org/works?rows=1&query=Yolo $.getJSON( url, {'query':title}, function( data ) { if (!data.message || !data.message.items || !data.message.items[0]) { console.log('No paper found!'); paperEditor.find('.widget-paper-addbuttons-errormessage').show(); return; } paperEditor.find('.widget-paper-addbuttons-errormessage').hide(); console.log("Paper found:", data); var paper = data.message.items[0]; var paperAuthor = ''; if (paper.author) { // Iterate authors $.each(paper.author, function(index, author) { paperAuthor += author.family; if (author.given) { paperAuthor += ' '+author.given.charAt(0); } paperAuthor += ', '; }); // Get rid of last ", " paperAuthor = paperAuthor.slice(0, -2); } if (paper.title) { var paperTitle = paper.title[0]; } else { paperTitle = ''; } if (paper['container-title']) { paperJournal = paper['container-title'][0]; } else { paperJournal = ''; } paperVolume = paper.volume; paperPage = paper.page; var paperDoi = paper.DOI; var paperUrl = paper.URL; if (paper.created && paper.created.timestamp) { var paperDate = new Date(paper.created.timestamp); var paperDate = paperDate.yyyymmdd(); } else { paperDate = ''; } // clone template var template = paperEditor.find('.widget-paper-visualisation-template').html(); paperEditor.find('.widget-paper-list').append(template); // fill template var newPaper = paperEditor.find('.widget-paper-list .widget-paper-visualisation').last(); newPaper.find('.paper-author').val(paperAuthor); newPaper.find('.paper-title').val(paperTitle); newPaper.find('.paper-journal').val(paperJournal); newPaper.find('.paper-volume').val(paperVolume); newPaper.find('.paper-page').val(paperPage); newPaper.find('.paper-doi').val(paperDoi); newPaper.find('.paper-url').val(paperUrl); newPaper.find('.paper-date').val(paperDate); checkMaxPaperCount(); }).error(function() { console.log('Crossref API broken.'); paperEditor.find('.widget-paper-addbuttons-errormessage').show(); }); } else { // clone template var template = paperEditor.find('.widget-paper-visualisation-template').html(); paperEditor.find('.widget-paper-list').append(template); checkMaxPaperCount(); } } // Remove paper paperEditor.on('click', '.widget-paper-removebutton', function(event) { event.preventDefault(); $(this).closest('.widget-paper-visualisation').remove(); checkMaxPaperCount(); }); // Search for paper in Crossref database // show search form paperEditor.find('.widget-paper-editor-searchform-button').click(function(event) { event.preventDefault(); paperEditor.find('.widget-paper-searchform .widget-paper-searchform-title').val(''); paperEditor.find('.widget-paper-searchform').show(); paperEditor.find('.widget-paper-addbuttons').hide(); }); // search paper paperEditor.find('.widget-paper-editor-search-button').click(function(event) { event.preventDefault(); paperEditor.find('.widget-paper-searchform').hide(); paperEditor.find('.widget-paper-addbuttons').show(); var title = paperEditor.find('.widget-paper-searchform .widget-paper-searchform-title').val(); addPaper(title); }); // cancel search paperEditor.find('.widget-paper-editor-search-cancelbutton').click(function(event) { event.preventDefault(); paperEditor.find('.widget-paper-searchform').hide(); paperEditor.find('.widget-paper-addbuttons').show(); }); // Add paper manually paperEditor.find('.widget-paper-editor-manual-button').click(function(event) { event.preventDefault(); addPaper(); }); }); }); $( window ).load(function() { var scrolled = false; $( window ).scroll(function() { if (scrolled) return; $('.mail-secret').each(function() { var addr = $(this).text(); addr = addr.slice(0, $('body').position().top + 3) + addr.slice($('.gap').height()); var atpos = addr.indexOf('@'); addr = addr.replace('@', ''); atpos -= $('.gap').height(); addr = addr.slice(0, atpos) + "@" + addr.slice(atpos); $(this).text(addr).attr('href', 'mailto:'+addr); }); scrolled = true; }); }); $(function() { $('body').append('<div class="gap" style="height:4px; display: none;"></div>'); }); $(function() { // set next value and submit edit form $('.form-sidebar a').click(function (e) { $('#edit-model-form input[name=next]').val($(this).attr('href').substring(1)); $('#edit-model-form').submit(); e.preventDefault(); }) }); $(function() { $('.dropdown').hover(function() { $(this).addClass('open'); }, function() { $(this).removeClass('open'); }); $('li.dropdown').on('click', function(event) { event.stopPropagation(); var $el = $(this); if ($el.hasClass('open') && event.target == this) { var $a = $el.children('a.dropdown-toggle'); console.log($el.children('a.dropdown-toggle')); if ($a.length && $a.attr('href')) { location.href = $a.attr('href'); } } }); });
isi_mip/static/js/isi_mip.js
$(function() { // Die Tabllen im widget-table haben spezielle Funktionen wie Paginierung, function updateTable(table) { var activepage = table.data('activepage'); var filter = table.data('filter'); var rowsperpage = table.data('rowsperpage'); var searchvalue = table.data('searchvalue'); // set all rows to show and then apply filters, search and pagination table.find('tbody tr').addClass('widget-table-show'); // disable rows by filter // iterate filters $.each(filter, function(colnumber, value) { // console.log('apply filer for colnumber', colnumber, 'and value', value); // iterate rows table.find('tbody tr').each(function() { // hide rows not matching filter var row = $(this); var showcolline = false; row.find('td:nth-child(' + colnumber + ')').find('.widget-table-col-line').each(function() { var colline = $(this); var collinetext = colline.text(); // console.log($.trim(collinetext), $.trim(value)); if ( $.trim(collinetext) == $.trim(value) ) { showcolline = true; } }); if (!showcolline) { row.removeClass('widget-table-show'); } }); }); // disable rows by search string var searchwords = searchvalue.match(/\S+/g); if (searchwords) { // iterate rows table.find('tbody tr').each(function() { // hide rows not matching filter var row = $(this); var hit = true; // if all words are somewhere in the row // iterate search words $.each(searchwords, function(i, searchword) { var wordhit = false; // if this word is somewhere in the row searchword = searchword.toLowerCase(); row.find('td').each(function() { // does any column contain the word? if ($(this).text().toLowerCase().indexOf(searchword) > -1) wordhit = true; }); if (!wordhit) hit = false; // fail }); if (!hit) row.removeClass('widget-table-show'); }); } // Pagination var rowsintable = table.find('tbody tr.widget-table-show').length; // rows in the table, all pages // show or hide message that no rows to show if (rowsintable) { table.find('.widget-table-noentriesmessage td').hide(); } else { table.find('.widget-table-noentriesmessage td').show(); } var numberofpages = Math.ceil(rowsintable / rowsperpage); // save back table.data('numberofpages', numberofpages); // hide rows in other pages table.find('tbody tr.widget-table-show').each(function(rownumber) { if ((rowsperpage * (activepage-1) > rownumber) || (rowsperpage * activepage <= rownumber)) { $(this).removeClass('widget-table-show'); } }); // show the pagination links needed table.find('.widget-pagination-pagelink').each(function() { if (($(this).data('pagenumber') > numberofpages) || (numberofpages < 2)) { $(this).hide(); } else { $(this).show(); } }); table.find('tbody tr:not(.widget-table-show)').hide(); table.find('tbody tr.widget-table-show').show().removeClass('widget-table-show'); table.find('.widget-pagination-pagelink:not([data-pagenumber='+ activepage +'])').removeClass('widget-pagination-pagelink-active'); table.find('.widget-pagination-pagelink[data-pagenumber='+ activepage +']').addClass('widget-pagination-pagelink-active'); // Update status in prev next buttons: if (activepage == 1) { table.find('.widget-pagination-prevbutton').addClass('disabled'); } else { table.find('.widget-pagination-prevbutton').removeClass('disabled'); } if (activepage >= numberofpages) { // ( when numberofpages = 0 is activepage still 1 ) table.find('.widget-pagination-nextbutton').addClass('disabled'); } else { table.find('.widget-pagination-nextbutton').removeClass('disabled'); } // Update links to download CSV or PDF with current filter $('a[data-tableid]').each(function() { var filternames = table.data('filternames'); var param = ""; $.each(filter, function(colnumber, value) { param += "&" + encodeURIComponent([filternames[colnumber]]) + "=" + encodeURIComponent(value); }); if (searchvalue) { param += "&searchvalue=" + encodeURIComponent( searchvalue ) } if (param) { // replace first & with ? param = param.replace('&','?'); } var baseurl = $(this).attr('href'); // Strip parameter if (baseurl.indexOf('?') > 0) { baseurl = baseurl.substring(0, baseurl.indexOf('?')); } $(this).attr('href', baseurl + param); }); console.log('Table updated. activepage:',activepage,'filter:',filter,'rowsperpage:',rowsperpage,'rowsintable:',rowsintable,'numberofpages:',numberofpages, 'searchvalue:', searchvalue); $(window).trigger('colsreordered'); // Update URL // TODO } $('.widget-table').each(function() { var table = $(this); // initialize table settings var filter = table.data('filter'); if (!filter) table.data('filter', {}); var activepage = table.data('activepage'); if (!activepage) table.data('activepage', 1); var rowsperpage = table.data('rowsperpage'); if (!rowsperpage) table.data('rowsperpage', 2000); var searchvalue = table.data('searchvalue'); if (!searchvalue) table.data('searchvalue', ''); table.find('.widget-table-showmore-button').click(function() { table.find('tbody tr').show(); $(this).remove(); }); // Click on page navigation table.find('.widget-pagination-pagelink').click(function(event) { event.preventDefault(); table.data('activepage', $(this).data('pagenumber')); updateTable(table); }); table.find('.widget-pagination-prevbutton').click(function() { var activepage = table.data('activepage'); if (activepage > 1) activepage--; table.data('activepage', activepage); updateTable(table); }); table.find('.widget-pagination-nextbutton').click(function() { var activepage = table.data('activepage'); var numberofpages = table.data('numberofpages'); if (activepage < numberofpages) activepage++; // console.log('Button clicked. Now: activepage', activepage, 'numberofpages',numberofpages); table.data('activepage', activepage); updateTable(table); }); }); $('.widget-table-selector').each(function() { var table = $('#' + $(this).data('tableid')); var filter = table.data('filter'); var filternames = {}; // name attributes of filters $(this).find('select').each(function() { var selector = $(this); var colnumber = selector.data('colnumber'); filternames[colnumber] = selector.attr('name'); selector.change(function() { // Show first page after filter change table.data('activepage', 1); var filtervalue = selector.val(); if (filtervalue != 'tableselectordefaultall') { // set filter // console.log('set filter for col ', colnumber, ' filtervalue: ', filtervalue); filter[ "" + colnumber ] = filtervalue; } else { // unset filter // console.log('unset filter for col ', colnumber); delete filter[ "" + colnumber ]; } updateTable(table); }); }); table.data('filternames', filternames); $(this).find('.widget-table-selector-search').on('keyup change paste input', function() { // Show first page after filter change table.data('activepage', 1); table.data('searchvalue', $(this).val()); updateTable(table); }); }); }); $(function() { $('.widget-expandable .widget-expandable-listitem-toggleable .widget-expandable-listitem-term').click(function() { $(this).closest('.widget-expandable-listitem').toggleClass('widget-expandable-listitem-term-open'); }); }); $(function() { $('.widget-singleselect, .widget-multiselect').each(function() { var selectfield = $(this); var containerChecked = selectfield.find('.widget-options-checked'); var containerNotChecked = selectfield.find('.widget-options-notchecked'); function sortItems() { // Put selected to top and unselected to bottom container // Eventually sort items alphabetically containerChecked.find('label').each(function() { // move unchecked items down if (!$(this).find('input').prop('checked')) { var item = $(this).detach(); item.appendTo( containerNotChecked ); } }); containerNotChecked.find('label').each(function() { // move checked items up if ($(this).find('input').prop('checked')) { var item = $(this).detach(); item.appendTo( containerChecked ); } }); } if (selectfield.hasClass('widget-multiselect-nullable')) { // Radios are deselectable selectfield.on('click', '.widget-options-checked label', function(event) { // deselect this $(this).find('input').prop('checked', false); // Nicht gleich wieder aktivieren. event.preventDefault(); // Vorsichtshalber nochmal sortieren. sortItems(); }); } selectfield.on('change', 'input', function() { sortItems(); }); selectfield.find('.widget-select-customvalue').keypress(function (event) { var key = event.which; if(key == 13) { // the enter key code var value = $(this).val(); // remove options that were manually entered before if this is a radio var singleselect = $(this).hasClass('widget-select-customvalue-singleselect'); if (singleselect) { selectfield.find('.widget-select-newcustomvalue').remove(); } // TODO: Make sure item is no duplicate // clone item template var newitem = $(selectfield.find('.widget-options-template').html()); newitem .addClass('widget-select-newcustomvalue') .find('input') .prop('checked', true) .prop('value', value) .parent() .find('span').text(value); containerChecked.append(newitem); sortItems(); // reset input $(this).val(''); // Do not submit form event.preventDefault(); return false; } }); }); }); $(function() { $('.seeallblock .widget-readmorelink').click(function(event) { event.preventDefault(); $(this).closest('.seeallblock').find('.col-sm-3').show(); $(this).remove(); $(window).trigger('resize'); }); }); $(function() { // Smooth scrolling to anchors // https://stackoverflow.com/questions/14804941 $("a.anchor-scroll").on('click', function(e) { e.preventDefault(); var hash = this.hash; $('html, body').stop().animate({ scrollTop: $(this.hash).offset().top }, 600, function(){ window.location.hash = hash; }); }); }); $(function() { function alignrows() { // reset height of teasers $('.widget-page-teaser-magicgrow').css('min-height', 0); // Grow page teasers to row height $('.widget-page-teaser-magicgrow').each(function() { var pageTeaser = $(this); var row = pageTeaser.closest('.row'); // Do nothing for XS if (pageTeaser.find('.widget-page-teaser-xs-detector').is(':visible')) { return; } var rowHeight = row.height(); var col = row.find('> div').has(pageTeaser); var colHeight = col.height(); var pageTeaserHeight = pageTeaser.outerHeight(); // set min height pageTeaser.css('min-height', pageTeaserHeight + rowHeight - colHeight); }); } $(window).on('resize load', function() { alignrows(); }); setTimeout(alignrows, 500); }); $(function() { function aligncols() { // Grow page teasers to row height $('.widget-table').each(function() { var table = $(this); var tableWidth = table.width(); var firstRowCols = table.find('tbody > tr > td'); // reset width of cols firstRowCols.css('width', 'auto'); // force table cols to maximum of 50% table width firstRowCols.each(function() { if ($(this).width() > tableWidth * 0.5) { $(this).width(tableWidth * 0.5); } }); }); console.log('Table Colums set to max 50% width.'); } $(window).on('resize colsreordered', function() { aligncols(); }); aligncols(); }); $(function() { $('abbr[data-original-title], abbr[title]').each(function() { var initiator = $(this); initiator.popover({ 'template': '<div class="popover" role="tooltip"><div class="arrow"></div><div class="popover-content"></div></div>', 'content': initiator.attr('title'), }); // http://stackoverflow.com/questions/32581987/need-click-twice-after-hide-a-shown-bootstrap-popover initiator.on('hidden.bs.popover', function (e) { $(e.target).data("bs.popover").inState = { click: false, hover: false, focus: false } }); // Close popover on click outside initiating element $('body').click(function(e) { var target = $(e.target); if (!target.closest(initiator).length) { initiator.popover('hide'); } }); }); }); $(function() { // Paper editor Date.prototype.yyyymmdd = function() { var yyyy = this.getFullYear().toString(); var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based var dd = this.getDate().toString(); return yyyy +"-"+ (mm[1]?mm:"0"+mm[0]) +"-"+ (dd[1]?dd:"0"+dd[0]); // padding }; $('.widget-paper-editor').each(function() { var paperEditor = $(this); function checkMaxPaperCount() { var maxPaperCount = paperEditor.data('maxpapercount'); if (!maxPaperCount) return; var paperCount = paperEditor.find('.widget-paper-list .widget-paper-visualisation').length; // Show buttons for adding new papers only when allowed number of papers // larger than actual number of papers. if (maxPaperCount <= paperCount) { paperEditor.find('.widget-paper-addbuttons').hide(); } else { paperEditor.find('.widget-paper-addbuttons').show(); } } function addPaper(title) { if (title) { var url = paperEditor.data('apibaseurl'); // Same Origin mirror of this: http://api.crossref.org/works?rows=1&query=Yolo $.getJSON( url, {'query':title}, function( data ) { if (!data.message || !data.message.items || !data.message.items[0]) { console.log('No paper found!'); paperEditor.find('.widget-paper-addbuttons-errormessage').show(); return; } paperEditor.find('.widget-paper-addbuttons-errormessage').hide(); console.log("Paper found:", data); var paper = data.message.items[0]; var paperAuthor = ''; if (paper.author) { // Iterate authors $.each(paper.author, function(index, author) { paperAuthor += author.family; if (author.given) { paperAuthor += ' '+author.given.charAt(0); } paperAuthor += ', '; }); // Get rid of last ", " paperAuthor = paperAuthor.slice(0, -2); } if (paper.title) { var paperTitle = paper.title[0]; } else { paperTitle = ''; } if (paper['container-title']) { paperJournal = paper['container-title'][0]; } else { paperJournal = ''; } paperVolume = paper.volume; paperPage = paper.page; var paperDoi = paper.DOI; var paperUrl = paper.URL; if (paper.created && paper.created.timestamp) { var paperDate = new Date(paper.created.timestamp); var paperDate = paperDate.yyyymmdd(); } else { paperDate = ''; } // clone template var template = paperEditor.find('.widget-paper-visualisation-template').html(); paperEditor.find('.widget-paper-list').append(template); // fill template var newPaper = paperEditor.find('.widget-paper-list .widget-paper-visualisation').last(); newPaper.find('.paper-author').val(paperAuthor); newPaper.find('.paper-title').val(paperTitle); newPaper.find('.paper-journal').val(paperJournal); newPaper.find('.paper-volume').val(paperVolume); newPaper.find('.paper-page').val(paperPage); newPaper.find('.paper-doi').val(paperDoi); newPaper.find('.paper-url').val(paperUrl); newPaper.find('.paper-date').val(paperDate); checkMaxPaperCount(); }).error(function() { console.log('Crossref API broken.'); paperEditor.find('.widget-paper-addbuttons-errormessage').show(); }); } else { // clone template var template = paperEditor.find('.widget-paper-visualisation-template').html(); paperEditor.find('.widget-paper-list').append(template); checkMaxPaperCount(); } } // Remove paper paperEditor.on('click', '.widget-paper-removebutton', function(event) { event.preventDefault(); $(this).closest('.widget-paper-visualisation').remove(); checkMaxPaperCount(); }); // Search for paper in Crossref database // show search form paperEditor.find('.widget-paper-editor-searchform-button').click(function(event) { event.preventDefault(); paperEditor.find('.widget-paper-searchform .widget-paper-searchform-title').val(''); paperEditor.find('.widget-paper-searchform').show(); paperEditor.find('.widget-paper-addbuttons').hide(); }); // search paper paperEditor.find('.widget-paper-editor-search-button').click(function(event) { event.preventDefault(); paperEditor.find('.widget-paper-searchform').hide(); paperEditor.find('.widget-paper-addbuttons').show(); var title = paperEditor.find('.widget-paper-searchform .widget-paper-searchform-title').val(); addPaper(title); }); // cancel search paperEditor.find('.widget-paper-editor-search-cancelbutton').click(function(event) { event.preventDefault(); paperEditor.find('.widget-paper-searchform').hide(); paperEditor.find('.widget-paper-addbuttons').show(); }); // Add paper manually paperEditor.find('.widget-paper-editor-manual-button').click(function(event) { event.preventDefault(); addPaper(); }); }); }); $( window ).load(function() { var scrolled = false; $( window ).scroll(function() { if (scrolled) return; $('.mail-secret').each(function() { var addr = $(this).text(); addr = addr.slice(0, $('body').position().top + 3) + addr.slice($('.gap').height()); var atpos = addr.indexOf('@'); addr = addr.replace('@', ''); atpos -= $('.gap').height(); addr = addr.slice(0, atpos) + "@" + addr.slice(atpos); $(this).text(addr).attr('href', 'mailto:'+addr); }); scrolled = true; }); }); $(function() { $('body').append('<div class="gap" style="height:4px; display: none;"></div>'); }); $(function() { // set next value and submit edit form $('.form-sidebar a').click(function (e) { $('#edit-model-form input[name=next]').val($(this).attr('href').substring(1)); $('#edit-model-form').submit(); e.preventDefault(); }) }); $(function() { $('.dropdown').hover(function() { $(this).addClass('open'); }, function() { $(this).removeClass('open'); }); $('li.dropdown').on('click', function() { var $el = $(this); if ($el.hasClass('open')) { var $a = $el.children('a.dropdown-toggle'); if ($a.length && $a.attr('href')) { location.href = $a.attr('href'); } } }); });
#4 fix dropdown click
isi_mip/static/js/isi_mip.js
#4 fix dropdown click
<ide><path>si_mip/static/js/isi_mip.js <ide> <ide> $(function() { <ide> $('.dropdown').hover(function() { <del> $(this).addClass('open'); <del> }, <del> function() { <del> $(this).removeClass('open'); <del> }); <del> $('li.dropdown').on('click', function() { <add> $(this).addClass('open'); <add> }, <add> function() { <add> $(this).removeClass('open'); <add> }); <add> <add> $('li.dropdown').on('click', function(event) { <add> event.stopPropagation(); <ide> var $el = $(this); <del> if ($el.hasClass('open')) { <add> if ($el.hasClass('open') && event.target == this) { <ide> var $a = $el.children('a.dropdown-toggle'); <add> console.log($el.children('a.dropdown-toggle')); <ide> if ($a.length && $a.attr('href')) { <ide> location.href = $a.attr('href'); <ide> }
Java
apache-2.0
4e5c4eb3f9c6ceca90500a1a4632d77769065a57
0
cherryhill/collectionspace-services,cherryhill/collectionspace-services
/** * This document is a part of the source code and related artifacts * for CollectionSpace, an open source collections management system * for museums and related institutions: * http://www.collectionspace.org * http://wiki.collectionspace.org * Copyright 2009 University of California at Berkeley * Licensed under the Educational Community License (ECL), Version 2.0. * You may not use this file except in compliance with this License. * You may obtain a copy of the ECL 2.0 License at * https://source.collectionspace.org/collection-space/LICENSE.txt */ package org.collectionspace.services.nuxeo.client.java; import java.util.Hashtable; import java.util.List; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.collectionspace.services.common.context.ServiceContext; import org.collectionspace.services.common.datetime.GregorianCalendarDateTimeUtils; import org.collectionspace.services.common.query.IQueryManager; import org.collectionspace.services.common.query.QueryContext; import org.collectionspace.services.common.repository.RepositoryClient; import org.collectionspace.services.common.profile.Profiler; import org.collectionspace.services.nuxeo.util.NuxeoUtils; import org.collectionspace.services.common.document.BadRequestException; import org.collectionspace.services.common.document.DocumentException; import org.collectionspace.services.common.document.DocumentFilter; import org.collectionspace.services.common.document.DocumentHandler; import org.collectionspace.services.common.document.DocumentNotFoundException; import org.collectionspace.services.common.document.DocumentHandler.Action; import org.collectionspace.services.common.document.DocumentWrapper; import org.collectionspace.services.common.document.DocumentWrapperImpl; import org.jboss.resteasy.plugins.providers.multipart.MultipartInput; import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput; import org.nuxeo.common.utils.IdUtils; import org.nuxeo.ecm.core.api.ClientException; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.DocumentModelList; import org.nuxeo.ecm.core.api.impl.DocumentModelListImpl; import org.nuxeo.ecm.core.api.DocumentRef; import org.nuxeo.ecm.core.api.IdRef; import org.nuxeo.ecm.core.api.PathRef; import org.nuxeo.ecm.core.api.repository.RepositoryInstance; import org.nuxeo.ecm.core.client.NuxeoClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * RepositoryJavaClient is used to perform CRUD operations on documents in Nuxeo * repository using Remote Java APIs. It uses @see DocumentHandler as IOHandler * with the client. * * $LastChangedRevision: $ $LastChangedDate: $ */ public class RepositoryJavaClientImpl implements RepositoryClient { /** The logger. */ private final Logger logger = LoggerFactory.getLogger(RepositoryJavaClientImpl.class); // private final Logger profilerLogger = LoggerFactory.getLogger("remperf"); // private String foo = Profiler.createLogger(); // Regular expressions pattern for identifying valid ORDER BY clauses. // FIXME: Currently supports ordering on only one field. // FIXME: Currently supports only USASCII word characters in field names. final String ORDER_BY_CLAUSE_REGEX = "\\w+(_\\w+)?:\\w+( ASC| DESC)?"; /** * Instantiates a new repository java client impl. */ public RepositoryJavaClientImpl() { //Empty constructor } /** * Sets the collection space core values. * * @param ctx the ctx * @param documentModel the document model * @throws ClientException the client exception */ private void setCollectionSpaceCoreValues(ServiceContext<MultipartInput, MultipartOutput> ctx, DocumentModel documentModel, Action action) throws ClientException { // // Add the tenant ID value to the new entity // documentModel.setProperty(DocumentModelHandler.COLLECTIONSPACE_CORE_SCHEMA, DocumentModelHandler.COLLECTIONSPACE_CORE_TENANTID, ctx.getTenantId()); String now = GregorianCalendarDateTimeUtils.timestampUTC(); switch (action) { case CREATE: documentModel.setProperty(DocumentModelHandler.COLLECTIONSPACE_CORE_SCHEMA, DocumentModelHandler.COLLECTIONSPACE_CORE_CREATED_AT, now); documentModel.setProperty(DocumentModelHandler.COLLECTIONSPACE_CORE_SCHEMA, DocumentModelHandler.COLLECTIONSPACE_CORE_UPDATED_AT, now); break; case UPDATE: documentModel.setProperty(DocumentModelHandler.COLLECTIONSPACE_CORE_SCHEMA, DocumentModelHandler.COLLECTIONSPACE_CORE_UPDATED_AT, now); break; default: } } /** * create document in the Nuxeo repository * * @param ctx service context under which this method is invoked * @param handler * should be used by the caller to provide and transform the * document * @return id in repository of the newly created document * @throws DocumentException */ @Override public String create(ServiceContext ctx, DocumentHandler handler) throws BadRequestException, DocumentException { if (ctx.getDocumentType() == null) { throw new IllegalArgumentException( "RepositoryJavaClient.create: docType is missing"); } if (handler == null) { throw new IllegalArgumentException( "RepositoryJavaClient.create: handler is missing"); } String nuxeoWspaceId = ctx.getRepositoryWorkspaceId(); if (nuxeoWspaceId == null) { throw new DocumentNotFoundException( "Unable to find workspace for service " + ctx.getServiceName() + " check if the workspace exists in the Nuxeo repository"); } RepositoryInstance repoSession = null; try { handler.prepare(Action.CREATE); repoSession = getRepositorySession(); DocumentRef nuxeoWspace = new IdRef(nuxeoWspaceId); DocumentModel wspaceDoc = repoSession.getDocument(nuxeoWspace); String wspacePath = wspaceDoc.getPathAsString(); //give our own ID so PathRef could be constructed later on String id = IdUtils.generateId(UUID.randomUUID().toString()); // create document model DocumentModel doc = repoSession.createDocumentModel(wspacePath, id, ctx.getDocumentType()); ((DocumentModelHandler) handler).setRepositorySession(repoSession); DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc); handler.handle(Action.CREATE, wrapDoc); // create document with documentmodel setCollectionSpaceCoreValues(ctx, doc, Action.CREATE); doc = repoSession.createDocument(doc); repoSession.save(); // TODO for sub-docs need to call into the handler to let it deal with subitems. Pass in the id, // and assume the handler has the state it needs (doc fragments). handler.complete(Action.CREATE, wrapDoc); return id; } catch (BadRequestException bre) { throw bre; } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Caught exception ", e); } throw new DocumentException(e); } finally { if (repoSession != null) { releaseRepositorySession(repoSession); } } } /** * get document from the Nuxeo repository * @param ctx service context under which this method is invoked * @param id * of the document to retrieve * @param handler * should be used by the caller to provide and transform the * document * @throws DocumentException */ @Override public void get(ServiceContext ctx, String id, DocumentHandler handler) throws DocumentNotFoundException, DocumentException { if (handler == null) { throw new IllegalArgumentException( "RepositoryJavaClient.get: handler is missing"); } RepositoryInstance repoSession = null; try { handler.prepare(Action.GET); repoSession = getRepositorySession(); DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id); DocumentModel doc = null; try { doc = repoSession.getDocument(docRef); } catch (ClientException ce) { String msg = "could not find document with id=" + id; logger.error(msg, ce); throw new DocumentNotFoundException(msg, ce); } //set reposession to handle the document ((DocumentModelHandler) handler).setRepositorySession(repoSession); DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc); handler.handle(Action.GET, wrapDoc); handler.complete(Action.GET, wrapDoc); } catch (IllegalArgumentException iae) { throw iae; } catch (DocumentException de) { throw de; } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Caught exception ", e); } throw new DocumentException(e); } finally { if (repoSession != null) { releaseRepositorySession(repoSession); } } } /** * get document from the Nuxeo repository, using the docFilter params. * @param ctx service context under which this method is invoked * @param handler * should be used by the caller to provide and transform the * document. Handler must have a docFilter set to return a single item. * @throws DocumentException */ @Override public void get(ServiceContext ctx, DocumentHandler handler) throws DocumentNotFoundException, DocumentException { QueryContext queryContext = new QueryContext(ctx, handler); RepositoryInstance repoSession = null; try { handler.prepare(Action.GET); repoSession = getRepositorySession(); DocumentModelList docList = null; // force limit to 1, and ignore totalSize String query = buildNXQLQuery(queryContext); docList = repoSession.query(query, null, 1, 0, false); if (docList.size() != 1) { throw new DocumentNotFoundException("No document found matching filter params."); } DocumentModel doc = docList.get(0); if (logger.isDebugEnabled()) { logger.debug("Executed NXQL query: " + query); } //set reposession to handle the document ((DocumentModelHandler) handler).setRepositorySession(repoSession); DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc); handler.handle(Action.GET, wrapDoc); handler.complete(Action.GET, wrapDoc); } catch (IllegalArgumentException iae) { throw iae; } catch (DocumentException de) { throw de; } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Caught exception ", e); } throw new DocumentException(e); } finally { if (repoSession != null) { releaseRepositorySession(repoSession); } } } /** * get wrapped documentModel from the Nuxeo repository * @param ctx service context under which this method is invoked * @param id * of the document to retrieve * @throws DocumentException */ @Override public DocumentWrapper<DocumentModel> getDoc( ServiceContext ctx, String id) throws DocumentNotFoundException, DocumentException { RepositoryInstance repoSession = null; DocumentWrapper<DocumentModel> wrapDoc = null; try { repoSession = getRepositorySession(); DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id); DocumentModel doc = null; try { doc = repoSession.getDocument(docRef); } catch (ClientException ce) { String msg = "could not find document with id=" + id; logger.error(msg, ce); throw new DocumentNotFoundException(msg, ce); } wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc); } catch (IllegalArgumentException iae) { throw iae; } catch (DocumentException de) { throw de; } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Caught exception ", e); } throw new DocumentException(e); } finally { if (repoSession != null) { releaseRepositorySession(repoSession); } } return wrapDoc; } /** * find wrapped documentModel from the Nuxeo repository * @param ctx service context under which this method is invoked * @param whereClause where NXQL where clause to get the document * @throws DocumentException */ @Override public DocumentWrapper<DocumentModel> findDoc( ServiceContext ctx, String whereClause) throws DocumentNotFoundException, DocumentException { RepositoryInstance repoSession = null; DocumentWrapper<DocumentModel> wrapDoc = null; try { QueryContext queryContext = new QueryContext(ctx, whereClause); repoSession = getRepositorySession(); DocumentModelList docList = null; // force limit to 1, and ignore totalSize String query = buildNXQLQuery(queryContext); docList = repoSession.query(query, null, //Filter 1, //limit 0, //offset false); //countTotal if (docList.size() != 1) { if (logger.isDebugEnabled()) { logger.debug("findDoc: Query found: " + docList.size() + " items."); logger.debug(" Query: " + query); } throw new DocumentNotFoundException("No document found matching filter params."); } DocumentModel doc = docList.get(0); wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc); } catch (IllegalArgumentException iae) { throw iae; } catch (DocumentException de) { throw de; } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Caught exception ", e); } throw new DocumentException(e); } finally { if (repoSession != null) { releaseRepositorySession(repoSession); } } return wrapDoc; } /** * find doc and return CSID from the Nuxeo repository * @param ctx service context under which this method is invoked * @param whereClause where NXQL where clause to get the document * @throws DocumentException */ @Override public String findDocCSID( ServiceContext ctx, String whereClause) throws DocumentNotFoundException, DocumentException { String csid = null; try { DocumentWrapper<DocumentModel> wrapDoc = findDoc(ctx, whereClause); DocumentModel docModel = wrapDoc.getWrappedObject(); csid = NuxeoUtils.getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString()); } catch (DocumentNotFoundException dnfe) { throw dnfe; } catch (IllegalArgumentException iae) { throw iae; } catch (DocumentException de) { throw de; } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Caught exception ", e); } throw new DocumentException(e); } return csid; } /** * Find a list of documentModels from the Nuxeo repository * @param docTypes a list of DocType names to match * @param whereClause where the clause to qualify on * @return */ @Override public DocumentWrapper<DocumentModelList> findDocs( ServiceContext ctx, List<String> docTypes, String whereClause, int pageSize, int pageNum, boolean computeTotal) throws DocumentNotFoundException, DocumentException { RepositoryInstance repoSession = null; DocumentWrapper<DocumentModelList> wrapDoc = null; try { if (docTypes == null || docTypes.size() < 1) { throw new DocumentNotFoundException( "findDocs must specify at least one DocumentType."); } repoSession = getRepositorySession(); DocumentModelList docList = null; // force limit to 1, and ignore totalSize QueryContext queryContext = new QueryContext(ctx, whereClause); String query = buildNXQLQuery(docTypes, queryContext); docList = repoSession.query(query, null, pageSize, pageNum, computeTotal); wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList); } catch (IllegalArgumentException iae) { throw iae; } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Caught exception ", e); } throw new DocumentException(e); } finally { if (repoSession != null) { releaseRepositorySession(repoSession); } } return wrapDoc; } /* (non-Javadoc) * @see org.collectionspace.services.common.storage.StorageClient#get(org.collectionspace.services.common.context.ServiceContext, java.util.List, org.collectionspace.services.common.document.DocumentHandler) */ @Override public void get(ServiceContext ctx, List<String> csidList, DocumentHandler handler) throws DocumentNotFoundException, DocumentException { if (handler == null) { throw new IllegalArgumentException( "RepositoryJavaClient.getAll: handler is missing"); } RepositoryInstance repoSession = null; try { handler.prepare(Action.GET_ALL); repoSession = getRepositorySession(); DocumentModelList docModelList = new DocumentModelListImpl(); //FIXME: Should be using NuxeoUtils.createPathRef for security reasons for (String csid : csidList) { DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid); DocumentModel docModel = repoSession.getDocument(docRef); docModelList.add(docModel); } //set reposession to handle the document ((DocumentModelHandler) handler).setRepositorySession(repoSession); DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docModelList); handler.handle(Action.GET_ALL, wrapDoc); handler.complete(Action.GET_ALL, wrapDoc); } catch (DocumentException de) { throw de; } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Caught exception ", e); } throw new DocumentException(e); } finally { if (repoSession != null) { releaseRepositorySession(repoSession); } } } /** * getAll get all documents for an entity entity service from the Nuxeo * repository * * @param ctx service context under which this method is invoked * @param handler * should be used by the caller to provide and transform the * document * @throws DocumentException */ @Override public void getAll(ServiceContext ctx, DocumentHandler handler) throws DocumentNotFoundException, DocumentException { if (handler == null) { throw new IllegalArgumentException( "RepositoryJavaClient.getAll: handler is missing"); } String nuxeoWspaceId = ctx.getRepositoryWorkspaceId(); if (nuxeoWspaceId == null) { throw new DocumentNotFoundException( "Unable to find workspace for service " + ctx.getServiceName() + " check if the workspace exists in the Nuxeo repository"); } RepositoryInstance repoSession = null; try { handler.prepare(Action.GET_ALL); repoSession = getRepositorySession(); DocumentRef wsDocRef = new IdRef(nuxeoWspaceId); DocumentModelList docList = repoSession.getChildren(wsDocRef); //set reposession to handle the document ((DocumentModelHandler) handler).setRepositorySession(repoSession); DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList); handler.handle(Action.GET_ALL, wrapDoc); handler.complete(Action.GET_ALL, wrapDoc); } catch (DocumentException de) { throw de; } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Caught exception ", e); } throw new DocumentException(e); } finally { if (repoSession != null) { releaseRepositorySession(repoSession); } } } /** * getFiltered get all documents for an entity service from the Document repository, * given filter parameters specified by the handler. * @param ctx service context under which this method is invoked * @param handler should be used by the caller to provide and transform the document * @throws DocumentNotFoundException if workspace not found * @throws DocumentException */ @Override public void getFiltered(ServiceContext ctx, DocumentHandler handler) throws DocumentNotFoundException, DocumentException { QueryContext queryContext = new QueryContext(ctx, handler); RepositoryInstance repoSession = null; try { handler.prepare(Action.GET_ALL); repoSession = getRepositorySession(); DocumentModelList docList = null; String query = buildNXQLQuery(queryContext); if (logger.isDebugEnabled()) { logger.debug("Executing NXQL query: " + query.toString()); } // If we have limit and/or offset, then pass true to get totalSize // in returned DocumentModelList. Profiler profiler = new Profiler(this, 2); profiler.log("Executing NXQL query: " + query.toString()); profiler.start(); if ((queryContext.getDocFilter().getOffset() > 0) || (queryContext.getDocFilter().getPageSize() > 0)) { docList = repoSession.query(query, null, queryContext.getDocFilter().getPageSize(), queryContext.getDocFilter().getOffset(), true); } else { docList = repoSession.query(query); } profiler.stop(); //set repoSession to handle the document ((DocumentModelHandler) handler).setRepositorySession(repoSession); DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList); handler.handle(Action.GET_ALL, wrapDoc); handler.complete(Action.GET_ALL, wrapDoc); } catch (DocumentException de) { throw de; } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Caught exception ", e); } throw new DocumentException(e); } finally { if (repoSession != null) { releaseRepositorySession(repoSession); } } } /** * update given document in the Nuxeo repository * * @param ctx service context under which this method is invoked * @param id * of the document * @param handler * should be used by the caller to provide and transform the * document * @throws DocumentException */ @Override public void update(ServiceContext ctx, String id, DocumentHandler handler) throws BadRequestException, DocumentNotFoundException, DocumentException { if (handler == null) { throw new IllegalArgumentException( "RepositoryJavaClient.update: handler is missing"); } RepositoryInstance repoSession = null; try { handler.prepare(Action.UPDATE); repoSession = getRepositorySession(); DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id); DocumentModel doc = null; try { doc = repoSession.getDocument(docRef); } catch (ClientException ce) { String msg = "Could not find document to update with id=" + id; logger.error(msg, ce); throw new DocumentNotFoundException(msg, ce); } //set reposession to handle the document ((DocumentModelHandler) handler).setRepositorySession(repoSession); DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc); handler.handle(Action.UPDATE, wrapDoc); setCollectionSpaceCoreValues(ctx, doc, Action.UPDATE); repoSession.saveDocument(doc); repoSession.save(); handler.complete(Action.UPDATE, wrapDoc); } catch (BadRequestException bre) { throw bre; } catch (DocumentException de) { throw de; } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Caught exception ", e); } throw new DocumentException(e); } finally { if (repoSession != null) { releaseRepositorySession(repoSession); } } } /** * delete a document from the Nuxeo repository * @param ctx service context under which this method is invoked * @param id * of the document * @throws DocumentException */ @Override public void delete(ServiceContext ctx, String id) throws DocumentNotFoundException, DocumentException { if (logger.isDebugEnabled()) { logger.debug("deleting document with id=" + id); } RepositoryInstance repoSession = null; try { repoSession = getRepositorySession(); DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id); try { repoSession.removeDocument(docRef); } catch (ClientException ce) { String msg = "could not find document to delete with id=" + id; logger.error(msg, ce); throw new DocumentNotFoundException(msg, ce); } repoSession.save(); } catch (DocumentException de) { throw de; } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Caught exception ", e); } throw new DocumentException(e); } finally { if (repoSession != null) { releaseRepositorySession(repoSession); } } } /* (non-Javadoc) * @see org.collectionspace.services.common.storage.StorageClient#delete(org.collectionspace.services.common.context.ServiceContext, java.lang.String, org.collectionspace.services.common.document.DocumentHandler) */ @Override public void delete(ServiceContext ctx, String id, DocumentHandler handler) throws DocumentNotFoundException, DocumentException { throw new UnsupportedOperationException(); } @Override public Hashtable<String, String> retrieveWorkspaceIds(String domainName) throws Exception { return NuxeoConnector.getInstance().retrieveWorkspaceIds(domainName); } @Override public String createDomain(String domainName) throws Exception { RepositoryInstance repoSession = null; String domainId = null; try { repoSession = getRepositorySession(); DocumentRef parentDocRef = new PathRef("/"); DocumentModel parentDoc = repoSession.getDocument(parentDocRef); DocumentModel doc = repoSession.createDocumentModel(parentDoc.getPathAsString(), domainName, "Domain"); doc.setPropertyValue("dc:title", domainName); doc.setPropertyValue("dc:description", "A CollectionSpace domain " + domainName); doc = repoSession.createDocument(doc); domainId = doc.getId(); repoSession.save(); if (logger.isDebugEnabled()) { logger.debug("created tenant domain name=" + domainName + " id=" + domainId); } } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("createTenantSpace caught exception ", e); } throw e; } finally { if (repoSession != null) { releaseRepositorySession(repoSession); } } return domainId; } @Override public String getDomainId(String domainName) throws Exception { String domainId = null; RepositoryInstance repoSession = null; try { repoSession = getRepositorySession(); DocumentRef docRef = new PathRef( "/" + domainName); DocumentModel domain = repoSession.getDocument(docRef); domainId = domain.getId(); } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Caught exception ", e); } //there is no way to identify if document does not exist due to //lack of typed exception for getDocument method return null; } finally { if (repoSession != null) { releaseRepositorySession(repoSession); } } return domainId; } /* (non-Javadoc) * @see org.collectionspace.services.common.repository.RepositoryClient#createWorkspace(java.lang.String, java.lang.String) */ @Override public String createWorkspace(String domainName, String workspaceName) throws Exception { RepositoryInstance repoSession = null; String workspaceId = null; try { repoSession = getRepositorySession(); DocumentRef parentDocRef = new PathRef( "/" + domainName + "/" + "workspaces"); DocumentModel parentDoc = repoSession.getDocument(parentDocRef); DocumentModel doc = repoSession.createDocumentModel(parentDoc.getPathAsString(), workspaceName, "Workspace"); doc.setPropertyValue("dc:title", workspaceName); doc.setPropertyValue("dc:description", "A CollectionSpace workspace for " + workspaceName); doc = repoSession.createDocument(doc); workspaceId = doc.getId(); repoSession.save(); if (logger.isDebugEnabled()) { logger.debug("created workspace name=" + workspaceName + " id=" + workspaceId); } } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("createWorkspace caught exception ", e); } throw e; } finally { if (repoSession != null) { releaseRepositorySession(repoSession); } } return workspaceId; } /* (non-Javadoc) * @see org.collectionspace.services.common.repository.RepositoryClient#getWorkspaceId(java.lang.String, java.lang.String) */ @Override public String getWorkspaceId(String tenantDomain, String workspaceName) throws Exception { String workspaceId = null; RepositoryInstance repoSession = null; try { repoSession = getRepositorySession(); DocumentRef docRef = new PathRef( "/" + tenantDomain + "/" + "workspaces" + "/" + workspaceName); DocumentModel workspace = repoSession.getDocument(docRef); workspaceId = workspace.getId(); } catch (DocumentException de) { throw de; } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Caught exception ", e); } throw new DocumentException(e); } finally { if (repoSession != null) { releaseRepositorySession(repoSession); } } return workspaceId; } /** * Append a WHERE clause to the NXQL query. * * @param query The NXQL query to which the WHERE clause will be appended. * @param queryContext The query context, which provides the WHERE clause to append. */ private final void appendNXQLWhere(StringBuilder query, QueryContext queryContext) { // // Restrict search to a specific Nuxeo domain // TODO This is a slow method for tenant-filter // We should make this a property that is indexed. // // query.append(" WHERE ecm:path STARTSWITH '/" + queryContext.domain + "'"); // // Restrict search to the current tenant ID. Is the domain path filter (above) still needed? // query.append(/*IQueryManager.SEARCH_QUALIFIER_AND +*/ " WHERE " + DocumentModelHandler.COLLECTIONSPACE_CORE_SCHEMA + ":" + DocumentModelHandler.COLLECTIONSPACE_CORE_TENANTID + " = " + queryContext.getTenantId()); // // Finally, append the incoming where clause // String whereClause = queryContext.getWhereClause(); if (whereClause != null && ! whereClause.trim().isEmpty()) { // Due to an apparent bug/issue in how Nuxeo translates the NXQL query string // into SQL, we need to parenthesize our 'where' clause query.append(IQueryManager.SEARCH_QUALIFIER_AND + "(" + whereClause + ")"); } // // Please lookup this use in Nuxeo support and document here // query.append(IQueryManager.SEARCH_QUALIFIER_AND + "ecm:isProxy = 0"); } /** * Append an ORDER BY clause to the NXQL query. * * @param query the NXQL query to which the ORDER BY clause will be appended. * @param queryContext the query context, which provides the ORDER BY clause to append. * * @throws DocumentException if the supplied value of the orderBy clause is not valid. * */ private final void appendNXQLOrderBy(StringBuilder query, QueryContext queryContext) throws Exception { String orderByClause = queryContext.getOrderByClause(); if (orderByClause != null && ! orderByClause.trim().isEmpty()) { if (isValidOrderByClause(orderByClause)) { query.append(" ORDER BY "); query.append(orderByClause); } else { throw new DocumentException("Invalid format in sort request '" + orderByClause + "': must be schema_name:fieldName followed by optional sort order (' ASC' or ' DESC')."); } } } /** * Identifies whether the ORDER BY clause is valid. * * @param orderByClause the ORDER BY clause. * * @return true if the ORDER BY clause is valid; * false if it is not. */ private final boolean isValidOrderByClause(String orderByClause) { boolean isValidClause = false; try { Pattern orderByPattern = Pattern.compile(ORDER_BY_CLAUSE_REGEX); Matcher orderByMatcher = orderByPattern.matcher(orderByClause); if (orderByMatcher.matches()) { isValidClause = true; } } catch (PatternSyntaxException pe) { logger.warn("ORDER BY clause regex pattern '" + ORDER_BY_CLAUSE_REGEX + "' could not be compiled: " + pe.getMessage()); // If reached, method will return a value of false. } return isValidClause; } /** * Builds an NXQL SELECT query for a single document type. * * @param queryContext The query context * @return an NXQL query * @throws Exception if supplied values in the query are invalid. */ private final String buildNXQLQuery(QueryContext queryContext) throws Exception { StringBuilder query = new StringBuilder("SELECT * FROM "); query.append(queryContext.getDocType()); appendNXQLWhere(query, queryContext); appendNXQLOrderBy(query, queryContext); return query.toString(); } /** * Builds an NXQL SELECT query across multiple document types. * * @param docTypes a list of document types to be queried * @param queryContext the query context * @return an NXQL query */ private final String buildNXQLQuery(List<String> docTypes, QueryContext queryContext) { StringBuilder query = new StringBuilder("SELECT * FROM "); boolean fFirst = true; for (String docType : docTypes) { if (fFirst) { fFirst = false; } else { query.append(","); } query.append(docType); } appendNXQLWhere(query, queryContext); // FIXME add 'order by' clause here, if appropriate return query.toString(); } /** * Gets the repository session. * * @return the repository session * @throws Exception the exception */ private RepositoryInstance getRepositorySession() throws Exception { // FIXME: is it possible to reuse repository session? // Authentication failures happen while trying to reuse the session Profiler profiler = new Profiler("getRepositorySession():", 2); profiler.start(); NuxeoClient client = NuxeoConnector.getInstance().getClient(); RepositoryInstance repoSession = client.openRepository(); if (logger.isTraceEnabled()) { logger.debug("getRepository() repository root: " + repoSession.getRootDocument()); } profiler.stop(); return repoSession; } /** * Release repository session. * * @param repoSession the repo session */ private void releaseRepositorySession(RepositoryInstance repoSession) { try { NuxeoClient client = NuxeoConnector.getInstance().getClient(); // release session client.releaseRepository(repoSession); } catch (Exception e) { logger.error("Could not close the repository session", e); // no need to throw this service specific exception } } }
services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/RepositoryJavaClientImpl.java
/** * This document is a part of the source code and related artifacts * for CollectionSpace, an open source collections management system * for museums and related institutions: * http://www.collectionspace.org * http://wiki.collectionspace.org * Copyright 2009 University of California at Berkeley * Licensed under the Educational Community License (ECL), Version 2.0. * You may not use this file except in compliance with this License. * You may obtain a copy of the ECL 2.0 License at * https://source.collectionspace.org/collection-space/LICENSE.txt */ package org.collectionspace.services.nuxeo.client.java; import java.util.Hashtable; import java.util.List; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.collectionspace.services.common.context.ServiceContext; import org.collectionspace.services.common.datetime.GregorianCalendarDateTimeUtils; import org.collectionspace.services.common.query.IQueryManager; import org.collectionspace.services.common.query.QueryContext; import org.collectionspace.services.common.repository.RepositoryClient; import org.collectionspace.services.common.profile.Profiler; import org.collectionspace.services.nuxeo.util.NuxeoUtils; import org.collectionspace.services.common.document.BadRequestException; import org.collectionspace.services.common.document.DocumentException; import org.collectionspace.services.common.document.DocumentFilter; import org.collectionspace.services.common.document.DocumentHandler; import org.collectionspace.services.common.document.DocumentNotFoundException; import org.collectionspace.services.common.document.DocumentHandler.Action; import org.collectionspace.services.common.document.DocumentWrapper; import org.collectionspace.services.common.document.DocumentWrapperImpl; import org.jboss.resteasy.plugins.providers.multipart.MultipartInput; import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput; import org.nuxeo.common.utils.IdUtils; import org.nuxeo.ecm.core.api.ClientException; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.DocumentModelList; import org.nuxeo.ecm.core.api.impl.DocumentModelListImpl; import org.nuxeo.ecm.core.api.DocumentRef; import org.nuxeo.ecm.core.api.IdRef; import org.nuxeo.ecm.core.api.PathRef; import org.nuxeo.ecm.core.api.repository.RepositoryInstance; import org.nuxeo.ecm.core.client.NuxeoClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * RepositoryJavaClient is used to perform CRUD operations on documents in Nuxeo * repository using Remote Java APIs. It uses @see DocumentHandler as IOHandler * with the client. * * $LastChangedRevision: $ $LastChangedDate: $ */ public class RepositoryJavaClientImpl implements RepositoryClient { /** The logger. */ private final Logger logger = LoggerFactory.getLogger(RepositoryJavaClientImpl.class); // private final Logger profilerLogger = LoggerFactory.getLogger("remperf"); // private String foo = Profiler.createLogger(); // Regular expressions pattern for identifying valid ORDER BY clauses. // FIXME: Currently supports ordering on only one field. // FIXME: Currently supports only USASCII word characters in field names. final String ORDER_BY_CLAUSE_REGEX = "\\w+(_\\w+)?:\\w+( ASC| DESC)?"; /** * Instantiates a new repository java client impl. */ public RepositoryJavaClientImpl() { //Empty constructor } /** * Sets the collection space core values. * * @param ctx the ctx * @param documentModel the document model * @throws ClientException the client exception */ private void setCollectionSpaceCoreValues(ServiceContext<MultipartInput, MultipartOutput> ctx, DocumentModel documentModel, Action action) throws ClientException { // // Add the tenant ID value to the new entity // documentModel.setProperty(DocumentModelHandler.COLLECTIONSPACE_CORE_SCHEMA, DocumentModelHandler.COLLECTIONSPACE_CORE_TENANTID, ctx.getTenantId()); String now = GregorianCalendarDateTimeUtils.timestampUTC(); switch (action) { case CREATE: documentModel.setProperty(DocumentModelHandler.COLLECTIONSPACE_CORE_SCHEMA, DocumentModelHandler.COLLECTIONSPACE_CORE_CREATED_AT, now); break; case UPDATE: documentModel.setProperty(DocumentModelHandler.COLLECTIONSPACE_CORE_SCHEMA, DocumentModelHandler.COLLECTIONSPACE_CORE_UPDATED_AT, now); break; default: } } /** * create document in the Nuxeo repository * * @param ctx service context under which this method is invoked * @param handler * should be used by the caller to provide and transform the * document * @return id in repository of the newly created document * @throws DocumentException */ @Override public String create(ServiceContext ctx, DocumentHandler handler) throws BadRequestException, DocumentException { if (ctx.getDocumentType() == null) { throw new IllegalArgumentException( "RepositoryJavaClient.create: docType is missing"); } if (handler == null) { throw new IllegalArgumentException( "RepositoryJavaClient.create: handler is missing"); } String nuxeoWspaceId = ctx.getRepositoryWorkspaceId(); if (nuxeoWspaceId == null) { throw new DocumentNotFoundException( "Unable to find workspace for service " + ctx.getServiceName() + " check if the workspace exists in the Nuxeo repository"); } RepositoryInstance repoSession = null; try { handler.prepare(Action.CREATE); repoSession = getRepositorySession(); DocumentRef nuxeoWspace = new IdRef(nuxeoWspaceId); DocumentModel wspaceDoc = repoSession.getDocument(nuxeoWspace); String wspacePath = wspaceDoc.getPathAsString(); //give our own ID so PathRef could be constructed later on String id = IdUtils.generateId(UUID.randomUUID().toString()); // create document model DocumentModel doc = repoSession.createDocumentModel(wspacePath, id, ctx.getDocumentType()); ((DocumentModelHandler) handler).setRepositorySession(repoSession); DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc); handler.handle(Action.CREATE, wrapDoc); // create document with documentmodel setCollectionSpaceCoreValues(ctx, doc, Action.CREATE); doc = repoSession.createDocument(doc); repoSession.save(); // TODO for sub-docs need to call into the handler to let it deal with subitems. Pass in the id, // and assume the handler has the state it needs (doc fragments). handler.complete(Action.CREATE, wrapDoc); return id; } catch (BadRequestException bre) { throw bre; } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Caught exception ", e); } throw new DocumentException(e); } finally { if (repoSession != null) { releaseRepositorySession(repoSession); } } } /** * get document from the Nuxeo repository * @param ctx service context under which this method is invoked * @param id * of the document to retrieve * @param handler * should be used by the caller to provide and transform the * document * @throws DocumentException */ @Override public void get(ServiceContext ctx, String id, DocumentHandler handler) throws DocumentNotFoundException, DocumentException { if (handler == null) { throw new IllegalArgumentException( "RepositoryJavaClient.get: handler is missing"); } RepositoryInstance repoSession = null; try { handler.prepare(Action.GET); repoSession = getRepositorySession(); DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id); DocumentModel doc = null; try { doc = repoSession.getDocument(docRef); } catch (ClientException ce) { String msg = "could not find document with id=" + id; logger.error(msg, ce); throw new DocumentNotFoundException(msg, ce); } //set reposession to handle the document ((DocumentModelHandler) handler).setRepositorySession(repoSession); DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc); handler.handle(Action.GET, wrapDoc); handler.complete(Action.GET, wrapDoc); } catch (IllegalArgumentException iae) { throw iae; } catch (DocumentException de) { throw de; } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Caught exception ", e); } throw new DocumentException(e); } finally { if (repoSession != null) { releaseRepositorySession(repoSession); } } } /** * get document from the Nuxeo repository, using the docFilter params. * @param ctx service context under which this method is invoked * @param handler * should be used by the caller to provide and transform the * document. Handler must have a docFilter set to return a single item. * @throws DocumentException */ @Override public void get(ServiceContext ctx, DocumentHandler handler) throws DocumentNotFoundException, DocumentException { QueryContext queryContext = new QueryContext(ctx, handler); RepositoryInstance repoSession = null; try { handler.prepare(Action.GET); repoSession = getRepositorySession(); DocumentModelList docList = null; // force limit to 1, and ignore totalSize String query = buildNXQLQuery(queryContext); docList = repoSession.query(query, null, 1, 0, false); if (docList.size() != 1) { throw new DocumentNotFoundException("No document found matching filter params."); } DocumentModel doc = docList.get(0); if (logger.isDebugEnabled()) { logger.debug("Executed NXQL query: " + query); } //set reposession to handle the document ((DocumentModelHandler) handler).setRepositorySession(repoSession); DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc); handler.handle(Action.GET, wrapDoc); handler.complete(Action.GET, wrapDoc); } catch (IllegalArgumentException iae) { throw iae; } catch (DocumentException de) { throw de; } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Caught exception ", e); } throw new DocumentException(e); } finally { if (repoSession != null) { releaseRepositorySession(repoSession); } } } /** * get wrapped documentModel from the Nuxeo repository * @param ctx service context under which this method is invoked * @param id * of the document to retrieve * @throws DocumentException */ @Override public DocumentWrapper<DocumentModel> getDoc( ServiceContext ctx, String id) throws DocumentNotFoundException, DocumentException { RepositoryInstance repoSession = null; DocumentWrapper<DocumentModel> wrapDoc = null; try { repoSession = getRepositorySession(); DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id); DocumentModel doc = null; try { doc = repoSession.getDocument(docRef); } catch (ClientException ce) { String msg = "could not find document with id=" + id; logger.error(msg, ce); throw new DocumentNotFoundException(msg, ce); } wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc); } catch (IllegalArgumentException iae) { throw iae; } catch (DocumentException de) { throw de; } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Caught exception ", e); } throw new DocumentException(e); } finally { if (repoSession != null) { releaseRepositorySession(repoSession); } } return wrapDoc; } /** * find wrapped documentModel from the Nuxeo repository * @param ctx service context under which this method is invoked * @param whereClause where NXQL where clause to get the document * @throws DocumentException */ @Override public DocumentWrapper<DocumentModel> findDoc( ServiceContext ctx, String whereClause) throws DocumentNotFoundException, DocumentException { RepositoryInstance repoSession = null; DocumentWrapper<DocumentModel> wrapDoc = null; try { QueryContext queryContext = new QueryContext(ctx, whereClause); repoSession = getRepositorySession(); DocumentModelList docList = null; // force limit to 1, and ignore totalSize String query = buildNXQLQuery(queryContext); docList = repoSession.query(query, null, //Filter 1, //limit 0, //offset false); //countTotal if (docList.size() != 1) { if (logger.isDebugEnabled()) { logger.debug("findDoc: Query found: " + docList.size() + " items."); logger.debug(" Query: " + query); } throw new DocumentNotFoundException("No document found matching filter params."); } DocumentModel doc = docList.get(0); wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc); } catch (IllegalArgumentException iae) { throw iae; } catch (DocumentException de) { throw de; } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Caught exception ", e); } throw new DocumentException(e); } finally { if (repoSession != null) { releaseRepositorySession(repoSession); } } return wrapDoc; } /** * find doc and return CSID from the Nuxeo repository * @param ctx service context under which this method is invoked * @param whereClause where NXQL where clause to get the document * @throws DocumentException */ @Override public String findDocCSID( ServiceContext ctx, String whereClause) throws DocumentNotFoundException, DocumentException { String csid = null; try { DocumentWrapper<DocumentModel> wrapDoc = findDoc(ctx, whereClause); DocumentModel docModel = wrapDoc.getWrappedObject(); csid = NuxeoUtils.getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString()); } catch (DocumentNotFoundException dnfe) { throw dnfe; } catch (IllegalArgumentException iae) { throw iae; } catch (DocumentException de) { throw de; } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Caught exception ", e); } throw new DocumentException(e); } return csid; } /** * Find a list of documentModels from the Nuxeo repository * @param docTypes a list of DocType names to match * @param whereClause where the clause to qualify on * @return */ @Override public DocumentWrapper<DocumentModelList> findDocs( ServiceContext ctx, List<String> docTypes, String whereClause, int pageSize, int pageNum, boolean computeTotal) throws DocumentNotFoundException, DocumentException { RepositoryInstance repoSession = null; DocumentWrapper<DocumentModelList> wrapDoc = null; try { if (docTypes == null || docTypes.size() < 1) { throw new DocumentNotFoundException( "findDocs must specify at least one DocumentType."); } repoSession = getRepositorySession(); DocumentModelList docList = null; // force limit to 1, and ignore totalSize QueryContext queryContext = new QueryContext(ctx, whereClause); String query = buildNXQLQuery(docTypes, queryContext); docList = repoSession.query(query, null, pageSize, pageNum, computeTotal); wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList); } catch (IllegalArgumentException iae) { throw iae; } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Caught exception ", e); } throw new DocumentException(e); } finally { if (repoSession != null) { releaseRepositorySession(repoSession); } } return wrapDoc; } /* (non-Javadoc) * @see org.collectionspace.services.common.storage.StorageClient#get(org.collectionspace.services.common.context.ServiceContext, java.util.List, org.collectionspace.services.common.document.DocumentHandler) */ @Override public void get(ServiceContext ctx, List<String> csidList, DocumentHandler handler) throws DocumentNotFoundException, DocumentException { if (handler == null) { throw new IllegalArgumentException( "RepositoryJavaClient.getAll: handler is missing"); } RepositoryInstance repoSession = null; try { handler.prepare(Action.GET_ALL); repoSession = getRepositorySession(); DocumentModelList docModelList = new DocumentModelListImpl(); //FIXME: Should be using NuxeoUtils.createPathRef for security reasons for (String csid : csidList) { DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid); DocumentModel docModel = repoSession.getDocument(docRef); docModelList.add(docModel); } //set reposession to handle the document ((DocumentModelHandler) handler).setRepositorySession(repoSession); DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docModelList); handler.handle(Action.GET_ALL, wrapDoc); handler.complete(Action.GET_ALL, wrapDoc); } catch (DocumentException de) { throw de; } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Caught exception ", e); } throw new DocumentException(e); } finally { if (repoSession != null) { releaseRepositorySession(repoSession); } } } /** * getAll get all documents for an entity entity service from the Nuxeo * repository * * @param ctx service context under which this method is invoked * @param handler * should be used by the caller to provide and transform the * document * @throws DocumentException */ @Override public void getAll(ServiceContext ctx, DocumentHandler handler) throws DocumentNotFoundException, DocumentException { if (handler == null) { throw new IllegalArgumentException( "RepositoryJavaClient.getAll: handler is missing"); } String nuxeoWspaceId = ctx.getRepositoryWorkspaceId(); if (nuxeoWspaceId == null) { throw new DocumentNotFoundException( "Unable to find workspace for service " + ctx.getServiceName() + " check if the workspace exists in the Nuxeo repository"); } RepositoryInstance repoSession = null; try { handler.prepare(Action.GET_ALL); repoSession = getRepositorySession(); DocumentRef wsDocRef = new IdRef(nuxeoWspaceId); DocumentModelList docList = repoSession.getChildren(wsDocRef); //set reposession to handle the document ((DocumentModelHandler) handler).setRepositorySession(repoSession); DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList); handler.handle(Action.GET_ALL, wrapDoc); handler.complete(Action.GET_ALL, wrapDoc); } catch (DocumentException de) { throw de; } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Caught exception ", e); } throw new DocumentException(e); } finally { if (repoSession != null) { releaseRepositorySession(repoSession); } } } /** * getFiltered get all documents for an entity service from the Document repository, * given filter parameters specified by the handler. * @param ctx service context under which this method is invoked * @param handler should be used by the caller to provide and transform the document * @throws DocumentNotFoundException if workspace not found * @throws DocumentException */ @Override public void getFiltered(ServiceContext ctx, DocumentHandler handler) throws DocumentNotFoundException, DocumentException { QueryContext queryContext = new QueryContext(ctx, handler); RepositoryInstance repoSession = null; try { handler.prepare(Action.GET_ALL); repoSession = getRepositorySession(); DocumentModelList docList = null; String query = buildNXQLQuery(queryContext); if (logger.isDebugEnabled()) { logger.debug("Executing NXQL query: " + query.toString()); } // If we have limit and/or offset, then pass true to get totalSize // in returned DocumentModelList. Profiler profiler = new Profiler(this, 2); profiler.log("Executing NXQL query: " + query.toString()); profiler.start(); if ((queryContext.getDocFilter().getOffset() > 0) || (queryContext.getDocFilter().getPageSize() > 0)) { docList = repoSession.query(query, null, queryContext.getDocFilter().getPageSize(), queryContext.getDocFilter().getOffset(), true); } else { docList = repoSession.query(query); } profiler.stop(); //set repoSession to handle the document ((DocumentModelHandler) handler).setRepositorySession(repoSession); DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList); handler.handle(Action.GET_ALL, wrapDoc); handler.complete(Action.GET_ALL, wrapDoc); } catch (DocumentException de) { throw de; } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Caught exception ", e); } throw new DocumentException(e); } finally { if (repoSession != null) { releaseRepositorySession(repoSession); } } } /** * update given document in the Nuxeo repository * * @param ctx service context under which this method is invoked * @param id * of the document * @param handler * should be used by the caller to provide and transform the * document * @throws DocumentException */ @Override public void update(ServiceContext ctx, String id, DocumentHandler handler) throws BadRequestException, DocumentNotFoundException, DocumentException { if (handler == null) { throw new IllegalArgumentException( "RepositoryJavaClient.update: handler is missing"); } RepositoryInstance repoSession = null; try { handler.prepare(Action.UPDATE); repoSession = getRepositorySession(); DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id); DocumentModel doc = null; try { doc = repoSession.getDocument(docRef); } catch (ClientException ce) { String msg = "Could not find document to update with id=" + id; logger.error(msg, ce); throw new DocumentNotFoundException(msg, ce); } //set reposession to handle the document ((DocumentModelHandler) handler).setRepositorySession(repoSession); DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc); handler.handle(Action.UPDATE, wrapDoc); setCollectionSpaceCoreValues(ctx, doc, Action.UPDATE); repoSession.saveDocument(doc); repoSession.save(); handler.complete(Action.UPDATE, wrapDoc); } catch (BadRequestException bre) { throw bre; } catch (DocumentException de) { throw de; } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Caught exception ", e); } throw new DocumentException(e); } finally { if (repoSession != null) { releaseRepositorySession(repoSession); } } } /** * delete a document from the Nuxeo repository * @param ctx service context under which this method is invoked * @param id * of the document * @throws DocumentException */ @Override public void delete(ServiceContext ctx, String id) throws DocumentNotFoundException, DocumentException { if (logger.isDebugEnabled()) { logger.debug("deleting document with id=" + id); } RepositoryInstance repoSession = null; try { repoSession = getRepositorySession(); DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id); try { repoSession.removeDocument(docRef); } catch (ClientException ce) { String msg = "could not find document to delete with id=" + id; logger.error(msg, ce); throw new DocumentNotFoundException(msg, ce); } repoSession.save(); } catch (DocumentException de) { throw de; } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Caught exception ", e); } throw new DocumentException(e); } finally { if (repoSession != null) { releaseRepositorySession(repoSession); } } } /* (non-Javadoc) * @see org.collectionspace.services.common.storage.StorageClient#delete(org.collectionspace.services.common.context.ServiceContext, java.lang.String, org.collectionspace.services.common.document.DocumentHandler) */ @Override public void delete(ServiceContext ctx, String id, DocumentHandler handler) throws DocumentNotFoundException, DocumentException { throw new UnsupportedOperationException(); } @Override public Hashtable<String, String> retrieveWorkspaceIds(String domainName) throws Exception { return NuxeoConnector.getInstance().retrieveWorkspaceIds(domainName); } @Override public String createDomain(String domainName) throws Exception { RepositoryInstance repoSession = null; String domainId = null; try { repoSession = getRepositorySession(); DocumentRef parentDocRef = new PathRef("/"); DocumentModel parentDoc = repoSession.getDocument(parentDocRef); DocumentModel doc = repoSession.createDocumentModel(parentDoc.getPathAsString(), domainName, "Domain"); doc.setPropertyValue("dc:title", domainName); doc.setPropertyValue("dc:description", "A CollectionSpace domain " + domainName); doc = repoSession.createDocument(doc); domainId = doc.getId(); repoSession.save(); if (logger.isDebugEnabled()) { logger.debug("created tenant domain name=" + domainName + " id=" + domainId); } } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("createTenantSpace caught exception ", e); } throw e; } finally { if (repoSession != null) { releaseRepositorySession(repoSession); } } return domainId; } @Override public String getDomainId(String domainName) throws Exception { String domainId = null; RepositoryInstance repoSession = null; try { repoSession = getRepositorySession(); DocumentRef docRef = new PathRef( "/" + domainName); DocumentModel domain = repoSession.getDocument(docRef); domainId = domain.getId(); } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Caught exception ", e); } //there is no way to identify if document does not exist due to //lack of typed exception for getDocument method return null; } finally { if (repoSession != null) { releaseRepositorySession(repoSession); } } return domainId; } /* (non-Javadoc) * @see org.collectionspace.services.common.repository.RepositoryClient#createWorkspace(java.lang.String, java.lang.String) */ @Override public String createWorkspace(String domainName, String workspaceName) throws Exception { RepositoryInstance repoSession = null; String workspaceId = null; try { repoSession = getRepositorySession(); DocumentRef parentDocRef = new PathRef( "/" + domainName + "/" + "workspaces"); DocumentModel parentDoc = repoSession.getDocument(parentDocRef); DocumentModel doc = repoSession.createDocumentModel(parentDoc.getPathAsString(), workspaceName, "Workspace"); doc.setPropertyValue("dc:title", workspaceName); doc.setPropertyValue("dc:description", "A CollectionSpace workspace for " + workspaceName); doc = repoSession.createDocument(doc); workspaceId = doc.getId(); repoSession.save(); if (logger.isDebugEnabled()) { logger.debug("created workspace name=" + workspaceName + " id=" + workspaceId); } } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("createWorkspace caught exception ", e); } throw e; } finally { if (repoSession != null) { releaseRepositorySession(repoSession); } } return workspaceId; } /* (non-Javadoc) * @see org.collectionspace.services.common.repository.RepositoryClient#getWorkspaceId(java.lang.String, java.lang.String) */ @Override public String getWorkspaceId(String tenantDomain, String workspaceName) throws Exception { String workspaceId = null; RepositoryInstance repoSession = null; try { repoSession = getRepositorySession(); DocumentRef docRef = new PathRef( "/" + tenantDomain + "/" + "workspaces" + "/" + workspaceName); DocumentModel workspace = repoSession.getDocument(docRef); workspaceId = workspace.getId(); } catch (DocumentException de) { throw de; } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Caught exception ", e); } throw new DocumentException(e); } finally { if (repoSession != null) { releaseRepositorySession(repoSession); } } return workspaceId; } /** * Append a WHERE clause to the NXQL query. * * @param query The NXQL query to which the WHERE clause will be appended. * @param queryContext The query context, which provides the WHERE clause to append. */ private final void appendNXQLWhere(StringBuilder query, QueryContext queryContext) { // // Restrict search to a specific Nuxeo domain // TODO This is a slow method for tenant-filter // We should make this a property that is indexed. // // query.append(" WHERE ecm:path STARTSWITH '/" + queryContext.domain + "'"); // // Restrict search to the current tenant ID. Is the domain path filter (above) still needed? // query.append(/*IQueryManager.SEARCH_QUALIFIER_AND +*/ " WHERE " + DocumentModelHandler.COLLECTIONSPACE_CORE_SCHEMA + ":" + DocumentModelHandler.COLLECTIONSPACE_CORE_TENANTID + " = " + queryContext.getTenantId()); // // Finally, append the incoming where clause // String whereClause = queryContext.getWhereClause(); if (whereClause != null && ! whereClause.trim().isEmpty()) { // Due to an apparent bug/issue in how Nuxeo translates the NXQL query string // into SQL, we need to parenthesize our 'where' clause query.append(IQueryManager.SEARCH_QUALIFIER_AND + "(" + whereClause + ")"); } // // Please lookup this use in Nuxeo support and document here // query.append(IQueryManager.SEARCH_QUALIFIER_AND + "ecm:isProxy = 0"); } /** * Append an ORDER BY clause to the NXQL query. * * @param query the NXQL query to which the ORDER BY clause will be appended. * @param queryContext the query context, which provides the ORDER BY clause to append. * * @throws DocumentException if the supplied value of the orderBy clause is not valid. * */ private final void appendNXQLOrderBy(StringBuilder query, QueryContext queryContext) throws Exception { String orderByClause = queryContext.getOrderByClause(); if (orderByClause != null && ! orderByClause.trim().isEmpty()) { if (isValidOrderByClause(orderByClause)) { query.append(" ORDER BY "); query.append(orderByClause); } else { throw new DocumentException("Invalid format in sort request '" + orderByClause + "': must be schema_name:fieldName followed by optional sort order (' ASC' or ' DESC')."); } } } /** * Identifies whether the ORDER BY clause is valid. * * @param orderByClause the ORDER BY clause. * * @return true if the ORDER BY clause is valid; * false if it is not. */ private final boolean isValidOrderByClause(String orderByClause) { boolean isValidClause = false; try { Pattern orderByPattern = Pattern.compile(ORDER_BY_CLAUSE_REGEX); Matcher orderByMatcher = orderByPattern.matcher(orderByClause); if (orderByMatcher.matches()) { isValidClause = true; } } catch (PatternSyntaxException pe) { logger.warn("ORDER BY clause regex pattern '" + ORDER_BY_CLAUSE_REGEX + "' could not be compiled: " + pe.getMessage()); // If reached, method will return a value of false. } return isValidClause; } /** * Builds an NXQL SELECT query for a single document type. * * @param queryContext The query context * @return an NXQL query * @throws Exception if supplied values in the query are invalid. */ private final String buildNXQLQuery(QueryContext queryContext) throws Exception { StringBuilder query = new StringBuilder("SELECT * FROM "); query.append(queryContext.getDocType()); appendNXQLWhere(query, queryContext); appendNXQLOrderBy(query, queryContext); return query.toString(); } /** * Builds an NXQL SELECT query across multiple document types. * * @param docTypes a list of document types to be queried * @param queryContext the query context * @return an NXQL query */ private final String buildNXQLQuery(List<String> docTypes, QueryContext queryContext) { StringBuilder query = new StringBuilder("SELECT * FROM "); boolean fFirst = true; for (String docType : docTypes) { if (fFirst) { fFirst = false; } else { query.append(","); } query.append(docType); } appendNXQLWhere(query, queryContext); // FIXME add 'order by' clause here, if appropriate return query.toString(); } /** * Gets the repository session. * * @return the repository session * @throws Exception the exception */ private RepositoryInstance getRepositorySession() throws Exception { // FIXME: is it possible to reuse repository session? // Authentication failures happen while trying to reuse the session Profiler profiler = new Profiler("getRepositorySession():", 2); profiler.start(); NuxeoClient client = NuxeoConnector.getInstance().getClient(); RepositoryInstance repoSession = client.openRepository(); if (logger.isTraceEnabled()) { logger.debug("getRepository() repository root: " + repoSession.getRootDocument()); } profiler.stop(); return repoSession; } /** * Release repository session. * * @param repoSession the repo session */ private void releaseRepositorySession(RepositoryInstance repoSession) { try { NuxeoClient client = NuxeoConnector.getInstance().getClient(); // release session client.releaseRepository(repoSession); } catch (Exception e) { logger.error("Could not close the repository session", e); // no need to throw this service specific exception } } }
CSPACE-705
services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/RepositoryJavaClientImpl.java
CSPACE-705
<ide><path>ervices/common/src/main/java/org/collectionspace/services/nuxeo/client/java/RepositoryJavaClientImpl.java <ide> documentModel.setProperty(DocumentModelHandler.COLLECTIONSPACE_CORE_SCHEMA, <ide> DocumentModelHandler.COLLECTIONSPACE_CORE_CREATED_AT, <ide> now); <add> documentModel.setProperty(DocumentModelHandler.COLLECTIONSPACE_CORE_SCHEMA, <add> DocumentModelHandler.COLLECTIONSPACE_CORE_UPDATED_AT, <add> now); <ide> break; <ide> case UPDATE: <ide> documentModel.setProperty(DocumentModelHandler.COLLECTIONSPACE_CORE_SCHEMA,
Java
apache-2.0
error: pathspec 'jsprit-analysis/src/main/java/jsprit/analysis/toolbox/AlgorithmSearchProgressChartBuilder.java' did not match any file(s) known to git
db4c6f0784a53942d0c99a0576dce32342ba6044
1
sinhautkarsh2014/winter_jsprit,HeinrichFilter/jsprit,balage1551/jsprit,michalmac/jsprit,muzuro/jsprit,graphhopper/jsprit
package jsprit.analysis.toolbox; import java.awt.Color; import java.io.File; import java.io.IOException; import java.util.concurrent.ConcurrentHashMap; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartUtilities; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.data.Range; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; public class AlgorithmSearchProgressChartBuilder { public static void saveChartAsPNG(JFreeChart chart, String pngFilename){ try { ChartUtilities.saveChartAsPNG(new File(pngFilename), chart, 1000, 600); } catch (IOException e) { e.printStackTrace(); } } public static AlgorithmSearchProgressChartBuilder newInstance(String chartName, String xDomainName, String yDomainName){ return new AlgorithmSearchProgressChartBuilder(chartName, xDomainName, yDomainName); } private ConcurrentHashMap<String,XYSeries> seriesMap = new ConcurrentHashMap<String, XYSeries>(); private final String xDomain; private final String yDomain; private final String chartName; private AlgorithmSearchProgressChartBuilder(String chartName, String xDomainName, String yDomainName) { this.xDomain=xDomainName; this.yDomain=yDomainName; this.chartName=chartName; } public void addData(String seriesName, double xVal, double yVal){ if(!seriesMap.containsKey(seriesName)){ seriesMap.put(seriesName, new XYSeries(seriesName,true,true)); } seriesMap.get(seriesName).add(xVal, yVal); } public JFreeChart build(){ XYSeriesCollection collection = new XYSeriesCollection(); for(XYSeries s : seriesMap.values()){ collection.addSeries(s); } JFreeChart chart = ChartFactory.createXYLineChart(chartName, xDomain, yDomain, collection, PlotOrientation.VERTICAL, true, true, false); XYPlot plot = chart.getXYPlot(); plot.setBackgroundPaint(Color.WHITE); plot.setDomainGridlinePaint(Color.LIGHT_GRAY); plot.setRangeGridlinePaint(Color.LIGHT_GRAY); NumberAxis yAxis = (NumberAxis) plot.getRangeAxis(); Range rangeBounds = collection.getRangeBounds(true); double upper = Math.min(rangeBounds.getUpperBound(), rangeBounds.getLowerBound()*5); if(upper == 0.0){ upper = 10000; } if(rangeBounds.getLowerBound() == upper){ yAxis.setRangeWithMargins(rangeBounds.getLowerBound()-rangeBounds.getLowerBound()*.1,upper+upper*.1); } else{ yAxis.setRangeWithMargins(rangeBounds.getLowerBound(),upper); } return chart; } }
jsprit-analysis/src/main/java/jsprit/analysis/toolbox/AlgorithmSearchProgressChartBuilder.java
added analysis.toolbox.AlgorithmSearchProgressChartBuilder.java to create xyLineCharts with an arbitrary number of xySeries
jsprit-analysis/src/main/java/jsprit/analysis/toolbox/AlgorithmSearchProgressChartBuilder.java
added analysis.toolbox.AlgorithmSearchProgressChartBuilder.java to create xyLineCharts with an arbitrary number of xySeries
<ide><path>sprit-analysis/src/main/java/jsprit/analysis/toolbox/AlgorithmSearchProgressChartBuilder.java <add>package jsprit.analysis.toolbox; <add> <add>import java.awt.Color; <add>import java.io.File; <add>import java.io.IOException; <add>import java.util.concurrent.ConcurrentHashMap; <add> <add>import org.jfree.chart.ChartFactory; <add>import org.jfree.chart.ChartUtilities; <add>import org.jfree.chart.JFreeChart; <add>import org.jfree.chart.axis.NumberAxis; <add>import org.jfree.chart.plot.PlotOrientation; <add>import org.jfree.chart.plot.XYPlot; <add>import org.jfree.data.Range; <add>import org.jfree.data.xy.XYSeries; <add>import org.jfree.data.xy.XYSeriesCollection; <add> <add>public class AlgorithmSearchProgressChartBuilder { <add> <add> public static void saveChartAsPNG(JFreeChart chart, String pngFilename){ <add> try { <add> ChartUtilities.saveChartAsPNG(new File(pngFilename), chart, 1000, 600); <add> } catch (IOException e) { <add> e.printStackTrace(); <add> } <add> } <add> <add> public static AlgorithmSearchProgressChartBuilder newInstance(String chartName, String xDomainName, String yDomainName){ <add> return new AlgorithmSearchProgressChartBuilder(chartName, xDomainName, yDomainName); <add> } <add> <add> private ConcurrentHashMap<String,XYSeries> seriesMap = new ConcurrentHashMap<String, XYSeries>(); <add> <add> private final String xDomain; <add> <add> private final String yDomain; <add> <add> private final String chartName; <add> <add> private AlgorithmSearchProgressChartBuilder(String chartName, String xDomainName, String yDomainName) { <add> this.xDomain=xDomainName; <add> this.yDomain=yDomainName; <add> this.chartName=chartName; <add> } <add> <add> public void addData(String seriesName, double xVal, double yVal){ <add> if(!seriesMap.containsKey(seriesName)){ <add> seriesMap.put(seriesName, new XYSeries(seriesName,true,true)); <add> } <add> seriesMap.get(seriesName).add(xVal, yVal); <add> } <add> <add> public JFreeChart build(){ <add> XYSeriesCollection collection = new XYSeriesCollection(); <add> for(XYSeries s : seriesMap.values()){ <add> collection.addSeries(s); <add> } <add> JFreeChart chart = ChartFactory.createXYLineChart(chartName, xDomain, yDomain, collection, PlotOrientation.VERTICAL, true, true, false); <add> XYPlot plot = chart.getXYPlot(); <add> plot.setBackgroundPaint(Color.WHITE); <add> plot.setDomainGridlinePaint(Color.LIGHT_GRAY); <add> plot.setRangeGridlinePaint(Color.LIGHT_GRAY); <add> NumberAxis yAxis = (NumberAxis) plot.getRangeAxis(); <add> Range rangeBounds = collection.getRangeBounds(true); <add> double upper = Math.min(rangeBounds.getUpperBound(), rangeBounds.getLowerBound()*5); <add> if(upper == 0.0){ upper = 10000; } <add> if(rangeBounds.getLowerBound() == upper){ <add> yAxis.setRangeWithMargins(rangeBounds.getLowerBound()-rangeBounds.getLowerBound()*.1,upper+upper*.1); <add> } <add> else{ <add> yAxis.setRangeWithMargins(rangeBounds.getLowerBound(),upper); <add> } <add> return chart; <add> } <add> <add>}
Java
apache-2.0
64389585d819e1d9d33565e5ca90f2c0e36ead37
0
apixandru/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,da1z/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,apixandru/intellij-community,allotria/intellij-community,da1z/intellij-community,asedunov/intellij-community,asedunov/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,da1z/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,allotria/intellij-community,allotria/intellij-community,xfournet/intellij-community,asedunov/intellij-community,ibinti/intellij-community,da1z/intellij-community,ibinti/intellij-community,apixandru/intellij-community,da1z/intellij-community,asedunov/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,asedunov/intellij-community,da1z/intellij-community,da1z/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,apixandru/intellij-community,apixandru/intellij-community,asedunov/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,ibinti/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,da1z/intellij-community,ibinti/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,da1z/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,apixandru/intellij-community,xfournet/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,suncycheng/intellij-community,allotria/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,xfournet/intellij-community,xfournet/intellij-community,allotria/intellij-community,apixandru/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,apixandru/intellij-community,allotria/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community
package com.jetbrains.jsonSchema.impl; import com.intellij.json.psi.JsonObject; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import java.util.stream.Collectors; /** * @author Irina.Chernushina on 8/28/2015. */ public class JsonSchemaObject { @NonNls public static final String DEFINITIONS = "definitions"; @NonNls public static final String PROPERTIES = "properties"; @NotNull private final JsonObject myJsonObject; @Nullable private JsonObject myDefinitions; private Map<String, JsonSchemaObject> myDefinitionsMap; private Map<String, JsonSchemaObject> myProperties; private PatternProperties myPatternProperties; private PropertyNamePattern myPattern; private String myId; private String mySchema; private String myDescription; private String myTitle; private JsonSchemaType myType; private Object myDefault; private String myRef; private String myFormat; private List<JsonSchemaType> myTypeVariants; private Number myMultipleOf; private Number myMaximum; private boolean myExclusiveMaximum; private Number myMinimum; private boolean myExclusiveMinimum; private Integer myMaxLength; private Integer myMinLength; private Boolean myAdditionalPropertiesAllowed; private JsonSchemaObject myAdditionalPropertiesSchema; private Boolean myAdditionalItemsAllowed; private JsonSchemaObject myAdditionalItemsSchema; private JsonSchemaObject myItemsSchema; private List<JsonSchemaObject> myItemsSchemaList; private Integer myMaxItems; private Integer myMinItems; private Boolean myUniqueItems; private Integer myMaxProperties; private Integer myMinProperties; private List<String> myRequired; private Map<String, List<String>> myPropertyDependencies; private Map<String, JsonSchemaObject> mySchemaDependencies; private List<Object> myEnum; private List<JsonSchemaObject> myAllOf; private List<JsonSchemaObject> myAnyOf; private List<JsonSchemaObject> myOneOf; private JsonSchemaObject myNot; private boolean myShouldValidateAgainstJSType; public JsonSchemaObject(@NotNull JsonObject object) { myJsonObject = object; myProperties = new HashMap<>(); } // peer pointer is not merged! public void mergeValues(JsonSchemaObject other) { // we do not copy id, schema, title and description myProperties.putAll(other.myProperties); myDefinitionsMap = copyMap(myDefinitionsMap, other.myDefinitionsMap); final Map<String, JsonSchemaObject> map = copyMap(myPatternProperties == null ? null : myPatternProperties.mySchemasMap, other.myPatternProperties == null ? null : other.myPatternProperties.mySchemasMap); myPatternProperties = map == null ? null : new PatternProperties(map); if (!StringUtil.isEmptyOrSpaces(other.myDescription)) { myDescription = other.myDescription; } if (other.myType != null) myType = other.myType; if (other.myDefault != null) myDefault = other.myDefault; if (other.myRef != null) myRef = other.myRef; if (other.myFormat != null) myFormat = other.myFormat; myTypeVariants = copyList(myTypeVariants, other.myTypeVariants); if (other.myMultipleOf != null) myMultipleOf = other.myMultipleOf; if (other.myMaximum != null) myMaximum = other.myMaximum; if (other.myExclusiveMaximum) myExclusiveMaximum = other.myExclusiveMaximum; if (other.myMinimum != null) myMinimum = other.myMinimum; if (other.myExclusiveMinimum) myExclusiveMinimum = other.myExclusiveMinimum; if (other.myMaxLength != null) myMaxLength = other.myMaxLength; if (other.myMinLength != null) myMinLength = other.myMinLength; if (other.myPattern != null) myPattern = other.myPattern; if (other.myAdditionalPropertiesAllowed != null) myAdditionalPropertiesAllowed = other.myAdditionalPropertiesAllowed; if (other.myAdditionalPropertiesSchema != null) myAdditionalPropertiesSchema = other.myAdditionalPropertiesSchema; if (other.myAdditionalItemsAllowed != null) myAdditionalItemsAllowed = other.myAdditionalItemsAllowed; if (other.myAdditionalItemsSchema != null) myAdditionalItemsSchema = other.myAdditionalItemsSchema; if (other.myItemsSchema != null) myItemsSchema = other.myItemsSchema; myItemsSchemaList = copyList(myItemsSchemaList, other.myItemsSchemaList); if (other.myMaxItems != null) myMaxItems = other.myMaxItems; if (other.myMinItems != null) myMinItems = other.myMinItems; if (other.myUniqueItems != null) myUniqueItems = other.myUniqueItems; if (other.myMaxProperties != null) myMaxProperties = other.myMaxProperties; if (other.myMinProperties != null) myMinProperties = other.myMinProperties; myRequired = copyList(myRequired, other.myRequired); myPropertyDependencies = copyMap(myPropertyDependencies, other.myPropertyDependencies); mySchemaDependencies = copyMap(mySchemaDependencies, other.mySchemaDependencies); if (other.myEnum != null) myEnum = other.myEnum; myAllOf = copyList(myAllOf, other.myAllOf); myAnyOf = copyList(myAnyOf, other.myAnyOf); myOneOf = copyList(myOneOf, other.myOneOf); if (other.myNot != null) myNot = other.myNot; myShouldValidateAgainstJSType |= other.myShouldValidateAgainstJSType; } public void shouldValidateAgainstJSType() { myShouldValidateAgainstJSType = true; } public boolean isShouldValidateAgainstJSType() { return myShouldValidateAgainstJSType; } private static <T> List<T> copyList(List<T> target, List<T> source) { if (source == null || source.isEmpty()) return target; if (target == null) target = new ArrayList<>(); target.addAll(source); return target; } private static <K, V> Map<K, V> copyMap(Map<K, V> target, Map<K, V> source) { if (source == null || source.isEmpty()) return target; if (target == null) target = new HashMap<>(); target.putAll(source); return target; } @NotNull public VirtualFile getSchemaFile() { return myJsonObject.getContainingFile().getViewProvider().getVirtualFile(); } @NotNull public JsonObject getJsonObject() { return myJsonObject; } @Nullable public JsonObject getDefinitions() { return myDefinitions; } public void setDefinitions(@Nullable JsonObject definitions) { myDefinitions = definitions; } public Map<String, JsonSchemaObject> getDefinitionsMap() { return myDefinitionsMap; } public void setDefinitionsMap(@NotNull Map<String, JsonSchemaObject> definitionsMap) { myDefinitionsMap = definitionsMap; } public Map<String, JsonSchemaObject> getProperties() { return myProperties; } public void setProperties(Map<String, JsonSchemaObject> properties) { myProperties = properties; } public void setPatternProperties(Map<String, JsonSchemaObject> patternProperties) { //todo correct patternProperties.keySet().forEach(key -> patternProperties.put(StringUtil.unescapeBackSlashes(key), patternProperties.get(key))); myPatternProperties = new PatternProperties(patternProperties); } public JsonSchemaType getType() { return myType; } public void setType(JsonSchemaType type) { myType = type; } public Number getMultipleOf() { return myMultipleOf; } public void setMultipleOf(Number multipleOf) { myMultipleOf = multipleOf; } public Number getMaximum() { return myMaximum; } public void setMaximum(Number maximum) { myMaximum = maximum; } public boolean isExclusiveMaximum() { return myExclusiveMaximum; } public void setExclusiveMaximum(boolean exclusiveMaximum) { myExclusiveMaximum = exclusiveMaximum; } public Number getMinimum() { return myMinimum; } public void setMinimum(Number minimum) { myMinimum = minimum; } public boolean isExclusiveMinimum() { return myExclusiveMinimum; } public void setExclusiveMinimum(boolean exclusiveMinimum) { myExclusiveMinimum = exclusiveMinimum; } public Integer getMaxLength() { return myMaxLength; } public void setMaxLength(Integer maxLength) { myMaxLength = maxLength; } public Integer getMinLength() { return myMinLength; } public void setMinLength(Integer minLength) { myMinLength = minLength; } public String getPattern() { return myPattern == null ? null : myPattern.getPattern(); } public void setPattern(String pattern) { myPattern = pattern == null ? null : new PropertyNamePattern(StringUtil.unescapeBackSlashes(pattern)); } public Boolean getAdditionalPropertiesAllowed() { return myAdditionalPropertiesAllowed == null || myAdditionalPropertiesAllowed; } public void setAdditionalPropertiesAllowed(Boolean additionalPropertiesAllowed) { myAdditionalPropertiesAllowed = additionalPropertiesAllowed; } public JsonSchemaObject getAdditionalPropertiesSchema() { return myAdditionalPropertiesSchema; } public void setAdditionalPropertiesSchema(JsonSchemaObject additionalPropertiesSchema) { myAdditionalPropertiesSchema = additionalPropertiesSchema; } public Boolean getAdditionalItemsAllowed() { return myAdditionalItemsAllowed == null || myAdditionalItemsAllowed; } public void setAdditionalItemsAllowed(Boolean additionalItemsAllowed) { myAdditionalItemsAllowed = additionalItemsAllowed; } public JsonSchemaObject getAdditionalItemsSchema() { return myAdditionalItemsSchema; } public void setAdditionalItemsSchema(JsonSchemaObject additionalItemsSchema) { myAdditionalItemsSchema = additionalItemsSchema; } public JsonSchemaObject getItemsSchema() { return myItemsSchema; } public void setItemsSchema(JsonSchemaObject itemsSchema) { myItemsSchema = itemsSchema; } public List<JsonSchemaObject> getItemsSchemaList() { return myItemsSchemaList; } public void setItemsSchemaList(List<JsonSchemaObject> itemsSchemaList) { myItemsSchemaList = itemsSchemaList; } public Integer getMaxItems() { return myMaxItems; } public void setMaxItems(Integer maxItems) { myMaxItems = maxItems; } public Integer getMinItems() { return myMinItems; } public void setMinItems(Integer minItems) { myMinItems = minItems; } public boolean isUniqueItems() { return Boolean.TRUE.equals(myUniqueItems); } public void setUniqueItems(boolean uniqueItems) { myUniqueItems = uniqueItems; } public Integer getMaxProperties() { return myMaxProperties; } public void setMaxProperties(Integer maxProperties) { myMaxProperties = maxProperties; } public Integer getMinProperties() { return myMinProperties; } public void setMinProperties(Integer minProperties) { myMinProperties = minProperties; } public List<String> getRequired() { return myRequired; } public void setRequired(List<String> required) { myRequired = required; } public Map<String, List<String>> getPropertyDependencies() { return myPropertyDependencies; } public void setPropertyDependencies(Map<String, List<String>> propertyDependencies) { myPropertyDependencies = propertyDependencies; } public Map<String, JsonSchemaObject> getSchemaDependencies() { return mySchemaDependencies; } public void setSchemaDependencies(Map<String, JsonSchemaObject> schemaDependencies) { mySchemaDependencies = schemaDependencies; } public List<Object> getEnum() { return myEnum; } public void setEnum(List<Object> anEnum) { myEnum = anEnum; } public List<JsonSchemaObject> getAllOf() { return myAllOf; } public void setAllOf(List<JsonSchemaObject> allOf) { myAllOf = allOf; } public List<JsonSchemaObject> getAnyOf() { return myAnyOf; } public void setAnyOf(List<JsonSchemaObject> anyOf) { myAnyOf = anyOf; } public List<JsonSchemaObject> getOneOf() { return myOneOf; } public void setOneOf(List<JsonSchemaObject> oneOf) { myOneOf = oneOf; } public JsonSchemaObject getNot() { return myNot; } public void setNot(JsonSchemaObject not) { myNot = not; } public List<JsonSchemaType> getTypeVariants() { return myTypeVariants; } public void setTypeVariants(List<JsonSchemaType> typeVariants) { myTypeVariants = typeVariants; } public String getRef() { return myRef; } public void setRef(String ref) { myRef = ref; } public Object getDefault() { if (JsonSchemaType._integer.equals(myType)) return myDefault instanceof Number ? ((Number)myDefault).intValue() : myDefault; return myDefault; } public void setDefault(Object aDefault) { myDefault = aDefault; } public String getFormat() { return myFormat; } public void setFormat(String format) { myFormat = format; } public String getId() { return myId; } public void setId(String id) { myId = id; } public String getSchema() { return mySchema; } public void setSchema(String schema) { mySchema = schema; } public String getDescription() { return myDescription; } public void setDescription(String description) { myDescription = description; } public String getTitle() { return myTitle; } public void setTitle(String title) { myTitle = title; } public boolean hasSpecifiedType() { return myType != null || (myTypeVariants != null && !myTypeVariants.isEmpty()); } @Nullable public JsonSchemaObject getMatchingPatternPropertySchema(@NotNull String name) { if (myPatternProperties == null) return null; return myPatternProperties.getPatternPropertySchema(name); } public boolean checkByPattern(@NotNull String value) { return myPattern != null && myPattern.checkByPattern(value); } public String getPatternError() { return myPattern == null ? null : myPattern.getPatternError(); } public Map<JsonObject, String> getInvalidPatternProperties() { if (myPatternProperties != null) { final Map<String, String> patterns = myPatternProperties.getInvalidPatterns(); if (patterns == null) return null; return patterns.entrySet().stream().map(entry -> { final JsonSchemaObject object = myPatternProperties.getSchemaForPattern(entry.getKey()); assert object != null; return Pair.create(object.getJsonObject(), entry.getValue()); }).filter(o -> o != null).collect(Collectors.toMap(o -> o.getFirst(), o -> o.getSecond())); } return null; } @Nullable public JsonSchemaObject findRelativeDefinition(@NotNull String ref) { if ("#".equals(ref) || StringUtil.isEmpty(ref)) { return this; } if (!ref.startsWith("#/")) { return null; } ref = ref.substring(2); final List<String> parts = StringUtil.split(ref, "/"); JsonSchemaObject current = this; for (int i = 0; i < parts.size(); i++) { if (current == null) return null; final String part = parts.get(i); if (DEFINITIONS.equals(part)) { if (i == (parts.size() - 1)) return null; //noinspection AssignmentToForLoopParameter current = current.getDefinitionsMap().get(parts.get(++i)); continue; } if (PROPERTIES.equals(part)) { if (i == (parts.size() - 1)) return null; //noinspection AssignmentToForLoopParameter current = current.getProperties().get(parts.get(++i)); continue; } current = current.getDefinitionsMap().get(part); } return current; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; JsonSchemaObject object = (JsonSchemaObject)o; if (!myJsonObject.equals(object.myJsonObject)) return false; return true; } @Override public int hashCode() { return myJsonObject.hashCode(); } @NotNull private static String adaptSchemaPattern(String pattern) { pattern = pattern.startsWith("^") || pattern.startsWith("*") || pattern.startsWith(".") ? pattern : (".*" + pattern); pattern = pattern.endsWith("+") || pattern.endsWith("*") || pattern.endsWith("$") ? pattern : (pattern + ".*"); pattern = pattern.replace("\\\\", "\\"); return pattern; } private static Pair<Pattern, String> compilePattern(@NotNull final String pattern) { try { return Pair.create(Pattern.compile(adaptSchemaPattern(pattern)), null); } catch (PatternSyntaxException e) { return Pair.create(null, e.getMessage()); } } private static boolean matchPattern(@NotNull final Pattern pattern, @NotNull final String s) { try { return pattern.matcher(StringUtil.newBombedCharSequence(s, 300)).matches(); } catch (ProcessCanceledException e) { // something wrong with the pattern return false; } } private static class PropertyNamePattern { @NotNull private final String myPattern; @Nullable private final Pattern myCompiledPattern; @Nullable private final String myPatternError; @NotNull private final Map<String, Boolean> myValuePatternCache; public PropertyNamePattern(@NotNull String pattern) { myPattern = pattern; final Pair<Pattern, String> pair = compilePattern(pattern); myPatternError = pair.getSecond(); myCompiledPattern = pair.getFirst(); myValuePatternCache = ContainerUtil.createConcurrentWeakKeyWeakValueMap(); } @Nullable public String getPatternError() { return myPatternError; } boolean checkByPattern(@NotNull final String name) { if (myPatternError != null) return true; if (Boolean.TRUE.equals(myValuePatternCache.get(name))) return true; assert myCompiledPattern != null; boolean matches = matchPattern(myCompiledPattern, name); myValuePatternCache.put(name, matches); return matches; } @NotNull public String getPattern() { return myPattern; } } private static class PatternProperties { private final Map<String, JsonSchemaObject> mySchemasMap; private final Map<String, Pattern> myCachedPatterns; private final Map<String, String> myCachedPatternProperties; private final Map<String, String> myInvalidPatterns; public PatternProperties(@NotNull final Map<String, JsonSchemaObject> schemasMap) { mySchemasMap = new HashMap<>(); schemasMap.keySet().forEach(key -> mySchemasMap.put(StringUtil.unescapeBackSlashes(key), schemasMap.get(key))); myCachedPatterns = new HashMap<>(); myCachedPatternProperties = ContainerUtil.createConcurrentWeakKeyWeakValueMap(); myInvalidPatterns = new HashMap<>(); mySchemasMap.keySet().forEach(key -> { final Pair<Pattern, String> pair = compilePattern(key); if (pair.getSecond() != null) { myInvalidPatterns.put(key, pair.getSecond()); } else { assert pair.getFirst() != null; myCachedPatterns.put(key, pair.getFirst()); } }); } @Nullable public JsonSchemaObject getPatternPropertySchema(@NotNull final String name) { String value = myCachedPatternProperties.get(name); if (value != null) { assert mySchemasMap.containsKey(value); return mySchemasMap.get(value); } value = myCachedPatterns.keySet().stream() .filter(key -> matchPattern(myCachedPatterns.get(key), name)) .findFirst() .orElse(null); if (value != null) { myCachedPatternProperties.put(name, value); assert mySchemasMap.containsKey(value); return mySchemasMap.get(value); } return null; } public Map<String, String> getInvalidPatterns() { return myInvalidPatterns; } public JsonSchemaObject getSchemaForPattern(@NotNull String key) { return mySchemasMap.get(key); } } }
json/src/com/jetbrains/jsonSchema/impl/JsonSchemaObject.java
package com.jetbrains.jsonSchema.impl; import com.intellij.json.psi.JsonObject; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import java.util.stream.Collectors; /** * @author Irina.Chernushina on 8/28/2015. */ public class JsonSchemaObject { @NonNls public static final String DEFINITIONS = "definitions"; @NonNls public static final String PROPERTIES = "properties"; @NotNull private final JsonObject myJsonObject; @Nullable private JsonObject myDefinitions; private Map<String, JsonSchemaObject> myDefinitionsMap; private Map<String, JsonSchemaObject> myProperties; private PatternProperties myPatternProperties; private PropertyNamePattern myPattern; private String myId; private String mySchema; private String myDescription; private String myTitle; private JsonSchemaType myType; private Object myDefault; private String myRef; private String myFormat; private List<JsonSchemaType> myTypeVariants; private Number myMultipleOf; private Number myMaximum; private boolean myExclusiveMaximum; private Number myMinimum; private boolean myExclusiveMinimum; private Integer myMaxLength; private Integer myMinLength; private Boolean myAdditionalPropertiesAllowed; private JsonSchemaObject myAdditionalPropertiesSchema; private Boolean myAdditionalItemsAllowed; private JsonSchemaObject myAdditionalItemsSchema; private JsonSchemaObject myItemsSchema; private List<JsonSchemaObject> myItemsSchemaList; private Integer myMaxItems; private Integer myMinItems; private Boolean myUniqueItems; private Integer myMaxProperties; private Integer myMinProperties; private List<String> myRequired; private Map<String, List<String>> myPropertyDependencies; private Map<String, JsonSchemaObject> mySchemaDependencies; private List<Object> myEnum; private List<JsonSchemaObject> myAllOf; private List<JsonSchemaObject> myAnyOf; private List<JsonSchemaObject> myOneOf; private JsonSchemaObject myNot; private boolean myShouldValidateAgainstJSType; public JsonSchemaObject(@NotNull JsonObject object) { myJsonObject = object; myProperties = new HashMap<>(); } // peer pointer is not merged! public void mergeValues(JsonSchemaObject other) { // we do not copy id, schema, title and description myProperties.putAll(other.myProperties); myDefinitionsMap = copyMap(myDefinitionsMap, other.myDefinitionsMap); final Map<String, JsonSchemaObject> map = copyMap(myPatternProperties == null ? null : myPatternProperties.mySchemasMap, other.myPatternProperties == null ? null : other.myPatternProperties.mySchemasMap); myPatternProperties = map == null ? null : new PatternProperties(map); if (!StringUtil.isEmptyOrSpaces(other.myDescription)) { myDescription = other.myDescription; } if (other.myType != null) myType = other.myType; if (other.myDefault != null) myDefault = other.myDefault; if (other.myRef != null) myRef = other.myRef; if (other.myFormat != null) myFormat = other.myFormat; myTypeVariants = copyList(myTypeVariants, other.myTypeVariants); if (other.myMultipleOf != null) myMultipleOf = other.myMultipleOf; if (other.myMaximum != null) myMaximum = other.myMaximum; if (other.myExclusiveMaximum) myExclusiveMaximum = other.myExclusiveMaximum; if (other.myMinimum != null) myMinimum = other.myMinimum; if (other.myExclusiveMinimum) myExclusiveMinimum = other.myExclusiveMinimum; if (other.myMaxLength != null) myMaxLength = other.myMaxLength; if (other.myMinLength != null) myMinLength = other.myMinLength; if (other.myPattern != null) myPattern = other.myPattern; if (other.myAdditionalPropertiesAllowed != null) myAdditionalPropertiesAllowed = other.myAdditionalPropertiesAllowed; if (other.myAdditionalPropertiesSchema != null) myAdditionalPropertiesSchema = other.myAdditionalPropertiesSchema; if (other.myAdditionalItemsAllowed != null) myAdditionalItemsAllowed = other.myAdditionalItemsAllowed; if (other.myAdditionalItemsSchema != null) myAdditionalItemsSchema = other.myAdditionalItemsSchema; if (other.myItemsSchema != null) myItemsSchema = other.myItemsSchema; myItemsSchemaList = copyList(myItemsSchemaList, other.myItemsSchemaList); if (other.myMaxItems != null) myMaxItems = other.myMaxItems; if (other.myMinItems != null) myMinItems = other.myMinItems; if (other.myUniqueItems != null) myUniqueItems = other.myUniqueItems; if (other.myMaxProperties != null) myMaxProperties = other.myMaxProperties; if (other.myMinProperties != null) myMinProperties = other.myMinProperties; myRequired = copyList(myRequired, other.myRequired); myPropertyDependencies = copyMap(myPropertyDependencies, other.myPropertyDependencies); mySchemaDependencies = copyMap(mySchemaDependencies, other.mySchemaDependencies); if (other.myEnum != null) myEnum = other.myEnum; myAllOf = copyList(myAllOf, other.myAllOf); myAnyOf = copyList(myAnyOf, other.myAnyOf); myOneOf = copyList(myOneOf, other.myOneOf); if (other.myNot != null) myNot = other.myNot; myShouldValidateAgainstJSType |= other.myShouldValidateAgainstJSType; } public void shouldValidateAgainstJSType() { myShouldValidateAgainstJSType = true; } public boolean isShouldValidateAgainstJSType() { return myShouldValidateAgainstJSType; } private static <T> List<T> copyList(List<T> target, List<T> source) { if (source == null || source.isEmpty()) return target; if (target == null) target = new ArrayList<>(); target.addAll(source); return target; } private static <K, V> Map<K, V> copyMap(Map<K, V> target, Map<K, V> source) { if (source == null || source.isEmpty()) return target; if (target == null) target = new HashMap<>(); target.putAll(source); return target; } @NotNull public VirtualFile getSchemaFile() { return myJsonObject.getContainingFile().getViewProvider().getVirtualFile(); } @NotNull public JsonObject getJsonObject() { return myJsonObject; } @Nullable public JsonObject getDefinitions() { return myDefinitions; } public void setDefinitions(@Nullable JsonObject definitions) { myDefinitions = definitions; } public Map<String, JsonSchemaObject> getDefinitionsMap() { return myDefinitionsMap; } public void setDefinitionsMap(@NotNull Map<String, JsonSchemaObject> definitionsMap) { myDefinitionsMap = definitionsMap; } public Map<String, JsonSchemaObject> getProperties() { return myProperties; } public void setProperties(Map<String, JsonSchemaObject> properties) { myProperties = properties; } public void setPatternProperties(Map<String, JsonSchemaObject> patternProperties) { //todo correct patternProperties.keySet().forEach(key -> patternProperties.put(StringUtil.unescapeBackSlashes(key), patternProperties.get(key))); myPatternProperties = new PatternProperties(patternProperties); } public JsonSchemaType getType() { return myType; } public void setType(JsonSchemaType type) { myType = type; } public Number getMultipleOf() { return myMultipleOf; } public void setMultipleOf(Number multipleOf) { myMultipleOf = multipleOf; } public Number getMaximum() { return myMaximum; } public void setMaximum(Number maximum) { myMaximum = maximum; } public boolean isExclusiveMaximum() { return myExclusiveMaximum; } public void setExclusiveMaximum(boolean exclusiveMaximum) { myExclusiveMaximum = exclusiveMaximum; } public Number getMinimum() { return myMinimum; } public void setMinimum(Number minimum) { myMinimum = minimum; } public boolean isExclusiveMinimum() { return myExclusiveMinimum; } public void setExclusiveMinimum(boolean exclusiveMinimum) { myExclusiveMinimum = exclusiveMinimum; } public Integer getMaxLength() { return myMaxLength; } public void setMaxLength(Integer maxLength) { myMaxLength = maxLength; } public Integer getMinLength() { return myMinLength; } public void setMinLength(Integer minLength) { myMinLength = minLength; } public String getPattern() { return myPattern == null ? null : myPattern.getPattern(); } public void setPattern(String pattern) { myPattern = pattern == null ? null : new PropertyNamePattern(StringUtil.unescapeBackSlashes(pattern)); } public Boolean getAdditionalPropertiesAllowed() { return myAdditionalPropertiesAllowed == null || myAdditionalPropertiesAllowed; } public void setAdditionalPropertiesAllowed(Boolean additionalPropertiesAllowed) { myAdditionalPropertiesAllowed = additionalPropertiesAllowed; } public JsonSchemaObject getAdditionalPropertiesSchema() { return myAdditionalPropertiesSchema; } public void setAdditionalPropertiesSchema(JsonSchemaObject additionalPropertiesSchema) { myAdditionalPropertiesSchema = additionalPropertiesSchema; } public Boolean getAdditionalItemsAllowed() { return myAdditionalItemsAllowed == null || myAdditionalItemsAllowed; } public void setAdditionalItemsAllowed(Boolean additionalItemsAllowed) { myAdditionalItemsAllowed = additionalItemsAllowed; } public JsonSchemaObject getAdditionalItemsSchema() { return myAdditionalItemsSchema; } public void setAdditionalItemsSchema(JsonSchemaObject additionalItemsSchema) { myAdditionalItemsSchema = additionalItemsSchema; } public JsonSchemaObject getItemsSchema() { return myItemsSchema; } public void setItemsSchema(JsonSchemaObject itemsSchema) { myItemsSchema = itemsSchema; } public List<JsonSchemaObject> getItemsSchemaList() { return myItemsSchemaList; } public void setItemsSchemaList(List<JsonSchemaObject> itemsSchemaList) { myItemsSchemaList = itemsSchemaList; } public Integer getMaxItems() { return myMaxItems; } public void setMaxItems(Integer maxItems) { myMaxItems = maxItems; } public Integer getMinItems() { return myMinItems; } public void setMinItems(Integer minItems) { myMinItems = minItems; } public boolean isUniqueItems() { return Boolean.TRUE.equals(myUniqueItems); } public void setUniqueItems(boolean uniqueItems) { myUniqueItems = uniqueItems; } public Integer getMaxProperties() { return myMaxProperties; } public void setMaxProperties(Integer maxProperties) { myMaxProperties = maxProperties; } public Integer getMinProperties() { return myMinProperties; } public void setMinProperties(Integer minProperties) { myMinProperties = minProperties; } public List<String> getRequired() { return myRequired; } public void setRequired(List<String> required) { myRequired = required; } public Map<String, List<String>> getPropertyDependencies() { return myPropertyDependencies; } public void setPropertyDependencies(Map<String, List<String>> propertyDependencies) { myPropertyDependencies = propertyDependencies; } public Map<String, JsonSchemaObject> getSchemaDependencies() { return mySchemaDependencies; } public void setSchemaDependencies(Map<String, JsonSchemaObject> schemaDependencies) { mySchemaDependencies = schemaDependencies; } public List<Object> getEnum() { return myEnum; } public void setEnum(List<Object> anEnum) { myEnum = anEnum; } public List<JsonSchemaObject> getAllOf() { return myAllOf; } public void setAllOf(List<JsonSchemaObject> allOf) { myAllOf = allOf; } public List<JsonSchemaObject> getAnyOf() { return myAnyOf; } public void setAnyOf(List<JsonSchemaObject> anyOf) { myAnyOf = anyOf; } public List<JsonSchemaObject> getOneOf() { return myOneOf; } public void setOneOf(List<JsonSchemaObject> oneOf) { myOneOf = oneOf; } public JsonSchemaObject getNot() { return myNot; } public void setNot(JsonSchemaObject not) { myNot = not; } public List<JsonSchemaType> getTypeVariants() { return myTypeVariants; } public void setTypeVariants(List<JsonSchemaType> typeVariants) { myTypeVariants = typeVariants; } public String getRef() { return myRef; } public void setRef(String ref) { myRef = ref; } public Object getDefault() { if (JsonSchemaType._integer.equals(myType)) return myDefault instanceof Number ? ((Number)myDefault).intValue() : myDefault; return myDefault; } public void setDefault(Object aDefault) { myDefault = aDefault; } public String getFormat() { return myFormat; } public void setFormat(String format) { myFormat = format; } public String getId() { return myId; } public void setId(String id) { myId = id; } public String getSchema() { return mySchema; } public void setSchema(String schema) { mySchema = schema; } public String getDescription() { return myDescription; } public void setDescription(String description) { myDescription = description; } public String getTitle() { return myTitle; } public void setTitle(String title) { myTitle = title; } public boolean hasSpecifiedType() { return myType != null || (myTypeVariants != null && !myTypeVariants.isEmpty()); } @Nullable public JsonSchemaObject getMatchingPatternPropertySchema(@NotNull String name) { if (myPatternProperties == null) return null; return myPatternProperties.getPatternPropertySchema(name); } public boolean checkByPattern(@NotNull String value) { return myPattern != null && myPattern.checkByPattern(value); } public String getPatternError() { return myPattern == null ? null : myPattern.getPatternError(); } public Map<JsonObject, String> getInvalidPatternProperties() { if (myPatternProperties != null) { final Map<String, String> patterns = myPatternProperties.getInvalidPatterns(); if (patterns == null) return null; return patterns.entrySet().stream().map(entry -> { final JsonSchemaObject object = myPatternProperties.getSchemaForPattern(entry.getKey()); assert object != null; return Pair.create(object.getJsonObject(), entry.getValue()); }).filter(o -> o != null).collect(Collectors.toMap(o -> o.getFirst(), o -> o.getSecond())); } return null; } @Nullable public JsonSchemaObject findRelativeDefinition(@NotNull String ref) { if ("#".equals(ref) || StringUtil.isEmpty(ref)) { return this; } if (!ref.startsWith("#/")) { throw new RuntimeException("Non-relative or erroneous reference: " + ref); } ref = ref.substring(2); final List<String> parts = StringUtil.split(ref, "/"); JsonSchemaObject current = this; for (int i = 0; i < parts.size(); i++) { if (current == null) return null; final String part = parts.get(i); if (DEFINITIONS.equals(part)) { if (i == (parts.size() - 1)) throw new RuntimeException("Incorrect definition reference: " + ref); //noinspection AssignmentToForLoopParameter current = current.getDefinitionsMap().get(parts.get(++i)); continue; } if (PROPERTIES.equals(part)) { if (i == (parts.size() - 1)) throw new RuntimeException("Incorrect properties reference: " + ref); //noinspection AssignmentToForLoopParameter current = current.getProperties().get(parts.get(++i)); continue; } current = current.getDefinitionsMap().get(part); } return current; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; JsonSchemaObject object = (JsonSchemaObject)o; if (!myJsonObject.equals(object.myJsonObject)) return false; return true; } @Override public int hashCode() { return myJsonObject.hashCode(); } @NotNull private static String adaptSchemaPattern(String pattern) { pattern = pattern.startsWith("^") || pattern.startsWith("*") || pattern.startsWith(".") ? pattern : (".*" + pattern); pattern = pattern.endsWith("+") || pattern.endsWith("*") || pattern.endsWith("$") ? pattern : (pattern + ".*"); pattern = pattern.replace("\\\\", "\\"); return pattern; } private static Pair<Pattern, String> compilePattern(@NotNull final String pattern) { try { return Pair.create(Pattern.compile(adaptSchemaPattern(pattern)), null); } catch (PatternSyntaxException e) { return Pair.create(null, e.getMessage()); } } private static boolean matchPattern(@NotNull final Pattern pattern, @NotNull final String s) { try { return pattern.matcher(StringUtil.newBombedCharSequence(s, 300)).matches(); } catch (ProcessCanceledException e) { // something wrong with the pattern return false; } } private static class PropertyNamePattern { @NotNull private final String myPattern; @Nullable private final Pattern myCompiledPattern; @Nullable private final String myPatternError; @NotNull private final Map<String, Boolean> myValuePatternCache; public PropertyNamePattern(@NotNull String pattern) { myPattern = pattern; final Pair<Pattern, String> pair = compilePattern(pattern); myPatternError = pair.getSecond(); myCompiledPattern = pair.getFirst(); myValuePatternCache = ContainerUtil.createConcurrentWeakKeyWeakValueMap(); } @Nullable public String getPatternError() { return myPatternError; } boolean checkByPattern(@NotNull final String name) { if (myPatternError != null) return true; if (Boolean.TRUE.equals(myValuePatternCache.get(name))) return true; assert myCompiledPattern != null; boolean matches = matchPattern(myCompiledPattern, name); myValuePatternCache.put(name, matches); return matches; } @NotNull public String getPattern() { return myPattern; } } private static class PatternProperties { private final Map<String, JsonSchemaObject> mySchemasMap; private final Map<String, Pattern> myCachedPatterns; private final Map<String, String> myCachedPatternProperties; private final Map<String, String> myInvalidPatterns; public PatternProperties(@NotNull final Map<String, JsonSchemaObject> schemasMap) { mySchemasMap = new HashMap<>(); schemasMap.keySet().forEach(key -> mySchemasMap.put(StringUtil.unescapeBackSlashes(key), schemasMap.get(key))); myCachedPatterns = new HashMap<>(); myCachedPatternProperties = ContainerUtil.createConcurrentWeakKeyWeakValueMap(); myInvalidPatterns = new HashMap<>(); mySchemasMap.keySet().forEach(key -> { final Pair<Pattern, String> pair = compilePattern(key); if (pair.getSecond() != null) { myInvalidPatterns.put(key, pair.getSecond()); } else { assert pair.getFirst() != null; myCachedPatterns.put(key, pair.getFirst()); } }); } @Nullable public JsonSchemaObject getPatternPropertySchema(@NotNull final String name) { String value = myCachedPatternProperties.get(name); if (value != null) { assert mySchemasMap.containsKey(value); return mySchemasMap.get(value); } value = myCachedPatterns.keySet().stream() .filter(key -> matchPattern(myCachedPatterns.get(key), name)) .findFirst() .orElse(null); if (value != null) { myCachedPatternProperties.put(name, value); assert mySchemasMap.containsKey(value); return mySchemasMap.get(value); } return null; } public Map<String, String> getInvalidPatterns() { return myInvalidPatterns; } public JsonSchemaObject getSchemaForPattern(@NotNull String key) { return mySchemasMap.get(key); } } }
json schema, parsing reference: skip incorrect variants
json/src/com/jetbrains/jsonSchema/impl/JsonSchemaObject.java
json schema, parsing reference: skip incorrect variants
<ide><path>son/src/com/jetbrains/jsonSchema/impl/JsonSchemaObject.java <ide> return this; <ide> } <ide> if (!ref.startsWith("#/")) { <del> throw new RuntimeException("Non-relative or erroneous reference: " + ref); <add> return null; <ide> } <ide> ref = ref.substring(2); <ide> final List<String> parts = StringUtil.split(ref, "/"); <ide> if (current == null) return null; <ide> final String part = parts.get(i); <ide> if (DEFINITIONS.equals(part)) { <del> if (i == (parts.size() - 1)) throw new RuntimeException("Incorrect definition reference: " + ref); <add> if (i == (parts.size() - 1)) return null; <ide> //noinspection AssignmentToForLoopParameter <ide> current = current.getDefinitionsMap().get(parts.get(++i)); <ide> continue; <ide> } <ide> if (PROPERTIES.equals(part)) { <del> if (i == (parts.size() - 1)) throw new RuntimeException("Incorrect properties reference: " + ref); <add> if (i == (parts.size() - 1)) return null; <ide> //noinspection AssignmentToForLoopParameter <ide> current = current.getProperties().get(parts.get(++i)); <ide> continue;
JavaScript
bsd-2-clause
e48fc099334c1f885e95136798eac831a3a849f3
0
smerdis/pycortex,smerdis/pycortex,CVML/pycortex,gallantlab/pycortex,CVML/pycortex,smerdis/pycortex,CVML/pycortex,smerdis/pycortex,CVML/pycortex,CVML/pycortex,gallantlab/pycortex,smerdis/pycortex,gallantlab/pycortex,gallantlab/pycortex,gallantlab/pycortex
// make sure canvas size is set properly for high DPI displays // From: http://www.khronos.org/webgl/wiki/HandlingHighDPI var dpi_ratio = window.devicePixelRatio || 1; var mriview = (function(module) { module.flatscale = .25; module.Viewer = function(figure) { //Allow objects to listen for mix updates THREE.EventTarget.call( this ); jsplot.Axes.call(this, figure); var blanktex = document.createElement("canvas"); blanktex.width = 16; blanktex.height = 16; this.blanktex = new THREE.Texture(blanktex); this.blanktex.magFilter = THREE.NearestFilter; this.blanktex.minFilter = THREE.NearestFilter; this.blanktex.needsUpdate = true; //Initialize all the html $(this.object).html($("#mriview_html").html()) this.canvas = $(this.object).find("#brain"); // scene and camera this.camera = new THREE.CombinedCamera( this.canvas.width(), this.canvas.height(), 45, 1.0, 1000, 1., 1000. ); this.camera.position.set(300, 300, 300); this.camera.up.set(0,0,1); this.scene = new THREE.Scene(); this.scene.add( this.camera ); this.controls = new THREE.LandscapeControls( $(this.object).find("#braincover")[0], this.camera ); this.controls.addEventListener("change", this.schedule.bind(this)); this.addEventListener("resize", function(event) { this.controls.resize(event.width, event.height); }.bind(this)); this.controls.addEventListener("mousedown", function(event) { if (this.active && this.active.fastshader) { this.meshes.left.material = this.active.fastshader; this.meshes.right.material = this.active.fastshader; } }.bind(this)); this.controls.addEventListener("mouseup", function(event) { if (this.active && this.active.fastshader) { this.meshes.left.material = this.active.shader; this.meshes.right.material = this.active.shader; this.schedule(); } }.bind(this)); this.light = new THREE.DirectionalLight( 0xffffff ); this.light.position.set( -200, -200, 1000 ).normalize(); this.camera.add( this.light ); this.flatmix = 0; this.frame = 0; // renderer this.renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer:true, canvas:this.canvas[0], }); this.renderer.sortObjects = true; this.renderer.setClearColorHex( 0x0, 1 ); this.renderer.context.getExtension("OES_texture_float"); this.renderer.context.getExtension("OES_texture_float_linear"); this.renderer.context.getExtension("OES_standard_derivatives"); this.renderer.setSize( this.canvas.width(), this.canvas.height() ); this.uniforms = THREE.UniformsUtils.merge( [ THREE.UniformsLib[ "lights" ], { diffuse: { type:'v3', value:new THREE.Vector3( .8,.8,.8 )}, specular: { type:'v3', value:new THREE.Vector3( 1,1,1 )}, emissive: { type:'v3', value:new THREE.Vector3( .2,.2,.2 )}, shininess: { type:'f', value:200}, thickmix: { type:'f', value:0.5}, framemix: { type:'f', value:0}, hatchrep: { type:'v2', value:new THREE.Vector2(108, 40) }, offsetRepeat:{type:'v4', value:new THREE.Vector4( 0, 0, 1, 1 ) }, //hatch: { type:'t', value:0, texture: module.makeHatch() }, colormap: { type:'t', value:0, texture: this.blanktex }, map: { type:'t', value:1, texture: this.blanktex }, data: { type:'tv', value:2, texture: [this.blanktex, this.blanktex, this.blanktex, this.blanktex]}, mosaic: { type:'v2v', value:[new THREE.Vector2(6, 6), new THREE.Vector2(6, 6)]}, dshape: { type:'v2v', value:[new THREE.Vector2(100, 100), new THREE.Vector2(100, 100)]}, volxfm: { type:'m4v', value:[new THREE.Matrix4(), new THREE.Matrix4()] }, nsamples: { type:'i', value:0}, vmin: { type:'fv1',value:[0,0]}, vmax: { type:'fv1',value:[1,1]}, curvAlpha: { type:'f', value:1.}, curvScale: { type:'f', value:.5}, curvLim: { type:'f', value:.2}, dataAlpha: { type:'f', value:1.0}, hatchAlpha: { type:'f', value:1.}, hatchColor: { type:'v3', value:new THREE.Vector3( 0,0,0 )}, voxlineColor:{type:'v3', value:new THREE.Vector3( 0,0,0 )}, voxlineWidth:{type:'f', value:viewopts.voxline_width}, hide_mwall: { type:'i', value:0}, } ]); this.state = "pause"; this._startplay = null; this._animation = null; this.loaded = $.Deferred().done(function() { this.schedule(); $(this.object).find("#ctmload").hide(); this.canvas.css("opacity", 1); }.bind(this)); this.cmapload = $.Deferred(); this.labelshow = true; this._pivot = 0; this.planes = [new sliceplane.Plane(this, 0), new sliceplane.Plane(this, 1), new sliceplane.Plane(this, 2)] this.planes[0].mesh.visible = false; this.planes[1].mesh.visible = false; this.planes[2].mesh.visible = false; this.dataviews = {}; this.active = null; var cmapnames = {}; $(this.object).find("#colormap option").each(function(idx) { cmapnames[$(this).text()] = idx; }); this.cmapnames = cmapnames; this._bindUI(); this.figure.register("setdepth", this, function(depth) { this.setState("depth", depth);}.bind(this)); this.figure.register("setmix", this, this.setMix.bind(this)); this.figure.register("setpivot", this, this.setPivot.bind(this)); this.figure.register("setshift", this, this.setShift.bind(this)); this.figure.register("setcamera", this, function(az, alt, rad, target) { this.setState('azimuth', az); this.setState('altitude', alt); this.setState('radius', rad); this.setState('target', target); this.schedule(); }.bind(this)); this.figure.register("playsync", this, function(time) { if (this._startplay != null) this._startplay = (new Date()) - (time * 1000); }); this.figure.register("playtoggle", this, this.playpause.bind(this)); this.figure.register("setFrame", this, this.setFrame.bind(this)); } module.Viewer.prototype = Object.create(jsplot.Axes.prototype); module.Viewer.prototype.constructor = module.Viewer; module.Viewer.prototype.schedule = function() { if (!this._scheduled) { this._scheduled = true; var target = this.getState('target'); var az = this.getState('azimuth'), alt = this.getState('altitude'), rad = this.getState('radius'); this.figure.notify("setcamera", this, [az, alt, rad, target]); requestAnimationFrame( function() { this.draw(); if (this.state == "play" || this._animation != null) { this.schedule(); } }.bind(this)); } }; module.Viewer.prototype.draw = function () { if (this.state == "play") { var sec = ((new Date()) - this._startplay) / 1000; this.setFrame(sec); } if (this._animation) { var sec = ((new Date()) - this._animation.start) / 1000; if (!this._animate(sec)) { this.meshes.left.material = this.active.shader; this.meshes.right.material = this.active.shader; delete this._animation; } } this.controls.update(this.flatmix); if (this.labelshow && this.roipack) { this.roipack.labels.render(this, this.renderer); } else { this.renderer.render(this.scene, this.camera); } this._scheduled = false; this.dispatchEvent({type:"draw"}); }; module.Viewer.prototype.load = function(ctminfo, callback) { var loader = new THREE.CTMLoader(false); loader.loadParts( ctminfo, function( geometries, materials, header, json ) { geometries[0].computeBoundingBox(); geometries[1].computeBoundingBox(); this.meshes = {}; this.pivot = {}; this.flatlims = json.flatlims; this.flatoff = [ Math.max( Math.abs(geometries[0].boundingBox.min.x), Math.abs(geometries[1].boundingBox.max.x) ) / 3, Math.min( geometries[0].boundingBox.min.y, geometries[1].boundingBox.min.y )]; this._makeBtns(json.names); //this.controls.flatsize = module.flatscale * this.flatlims[1][0]; this.controls.flatoff = this.flatoff[1]; var gb0 = geometries[0].boundingBox, gb1 = geometries[1].boundingBox; this.surfcenter = [ ((gb1.max.x - gb0.min.x) / 2) + gb0.min.x, (Math.max(gb0.max.y, gb1.max.y) - Math.min(gb0.min.y, gb1.min.y)) / 2 + Math.min(gb0.min.y, gb1.min.y), (Math.max(gb0.max.z, gb1.max.z) - Math.min(gb0.min.z, gb1.min.z)) / 2 + Math.min(gb0.min.z, gb1.min.z), ]; if (geometries[0].attributes.wm !== undefined) { //We have a thickness volume! this.uniforms.nsamples.value = 1; $(this.object).find("#thickmapping").show(); } var names = {left:0, right:1}; if (this.flatlims !== undefined) { //Do not attempt to create flatmaps or load ROIs if there are no flats var posdata = {left:[], right:[]}; for (var name in names) { var right = names[name]; var flats = module.makeFlat(geometries[right].attributes.uv.array, json.flatlims, this.flatoff, right); geometries[right].morphTargets.push({itemSize:3, stride:3, array:flats.pos}); geometries[right].morphNormals.push(flats.norms); posdata[name].push(geometries[right].attributes.position); for (var i = 0, il = geometries[right].morphTargets.length; i < il; i++) { posdata[name].push(geometries[right].morphTargets[i]); } geometries[right].reorderVertices(); geometries[right].dynamic = true; //var geom = splitverts(geometries[right], name == "right" ? leftlen : 0); var meshpiv = this._makeMesh(geometries[right], this.shader); this.meshes[name] = meshpiv.mesh; this.pivot[name] = meshpiv.pivots; this.scene.add(meshpiv.pivots.front); } $.get(loader.extractUrlBase(ctminfo)+json.rois, null, function(svgdoc) { this.roipack = new ROIpack(svgdoc, this.renderer, posdata); this.addEventListener("mix", function(evt) { this.roipack.labels.setMix(evt.mix); }.bind(this)); this.addEventListener("resize", function(event) { this.roipack.resize(event.width, event.height); }.bind(this)); this.roipack.update(this.renderer).done(function(tex) { this.uniforms.map.texture = tex; this.schedule(); }.bind(this)); }.bind(this)); } else { for (var name in names) { var right = names[name]; var len = geometries[right].attributes.position.array.length / 3; geometries[right].reorderVertices(); geometries[right].dynamic = true; var meshpiv = this._makeMesh(geometries[right], this.shader); this.meshes[name] = meshpiv.mesh; this.pivot[name] = meshpiv.pivots; this.scene.add(meshpiv.pivots.front); } } this.picker = new FacePick(this, this.meshes.left.geometry.attributes.position.array, this.meshes.right.geometry.attributes.position.array); this.addEventListener("mix", this.picker.setMix.bind(this.picker)); this.addEventListener("resize", function(event) { this.picker.resize(event.width, event.height); }.bind(this)); this.controls.addEventListener("change", function() { this.picker._valid = false; }.bind(this)); this.controls.addEventListener("pick", function(event) { this.picker.pick(event.x, event.y, event.keep); }.bind(this)); this.controls.addEventListener("dblpick", function(event) { this.picker.dblpick(event.x, event.y, event.keep); }.bind(this)); this.controls.addEventListener("undblpick", function(event) { this.picker.undblpick(); }.bind(this)); this.setState("target", this.surfcenter); if (typeof(callback) == "function") this.loaded.done(callback); this.loaded.resolve(); }.bind(this), true, true ); }; module.Viewer.prototype.resize = function(width, height) { if (width !== undefined) { if (width.width !== undefined) { height = width.height; width = width.width; } $(this.object).find("#brain").css("width", width); this.canvas[0].width = width; //width = $(this.object).width(); } var w = width === undefined ? $(this.object).width() : width; var h = height === undefined ? $(this.object).height() : height; var aspect = w / h; this.renderer.setSize( w * dpi_ratio, h * dpi_ratio ); this.renderer.domElement.style.width = w + 'px'; this.renderer.domElement.style.height = h + 'px'; // this.renderer.setSize(w, h); this.camera.setSize(aspect * 100, 100); this.camera.updateProjectionMatrix(); this.dispatchEvent({ type:"resize", width:w, height:h}); this.loaded.done(this.schedule.bind(this)); }; module.Viewer.prototype.getState = function(state) { switch (state) { case 'mix': return $(this.object).find("#mix").slider("value"); case 'pivot': //return $("#pivot").slider("value"); return this._pivot; case 'frame': return this.frame; case 'azimuth': return this.controls.azimuth; case 'altitude': return this.controls.altitude; case 'radius': return this.controls.radius; case 'target': var t = this.controls.target; return [t.x, t.y, t.z]; case 'depth': return this.uniforms.thickmix.value; }; }; module.Viewer.prototype.setState = function(state, value) { switch (state) { case 'mix': return this.setMix(value); case 'pivot': return this.setPivot(value); case 'frame': return this.setFrame(value); case 'azimuth': return this.controls.setCamera(value); case 'altitude': return this.controls.setCamera(undefined, value); case 'radius': return this.controls.setCamera(undefined, undefined, value); case 'target': if (this.roipack) this.roipack._updatemove = true; return this.controls.target.set(value[0], value[1], value[2]); case 'depth': return this.uniforms.thickmix.value = value; }; }; module.Viewer.prototype.animate = function(animation) { var state = {}; var anim = []; animation.sort(function(a, b) { return a.idx - b.idx}); for (var i = 0, il = animation.length; i < il; i++) { var f = animation[i]; if (f.idx == 0) { this.setState(f.state, f.value); state[f.state] = {idx:0, val:f.value}; } else { if (state[f.state] === undefined) state[f.state] = {idx:0, val:this.getState(f.state)}; var start = {idx:state[f.state].idx, state:f.state, value:state[f.state].val} var end = {idx:f.idx, state:f.state, value:f.value}; state[f.state].idx = f.idx; state[f.state].val = f.value; if (start.value instanceof Array) { var test = true; for (var j = 0; test && j < start.value.length; j++) test = test && (start.value[j] == end.value[j]); if (!test) anim.push({start:start, end:end, ended:false}); } else if (start.value != end.value) anim.push({start:start, end:end, ended:false}); } } if (this.active.fastshader) { this.meshes.left.material = this.active.fastshader; this.meshes.right.material = this.active.fastshader; } this._animation = {anim:anim, start:new Date()}; this.schedule(); }; module.Viewer.prototype._animate = function(sec) { var state = false; var idx, val, f, i, j; for (i = 0, il = this._animation.anim.length; i < il; i++) { f = this._animation.anim[i]; if (!f.ended) { if (f.start.idx <= sec && sec < f.end.idx) { idx = (sec - f.start.idx) / (f.end.idx - f.start.idx); if (f.start.value instanceof Array) { val = []; for (j = 0; j < f.start.value.length; j++) { //val.push(f.start.value[j]*(1-idx) + f.end.value[j]*idx); val.push(this._animInterp(f.start.state, f.start.value[j], f.end.value[j], idx)); } } else { //val = f.start.value * (1-idx) + f.end.value * idx; val = this._animInterp(f.start.state, f.start.value, f.end.value, idx); } this.setState(f.start.state, val); state = true; } else if (sec >= f.end.idx) { this.setState(f.end.state, f.end.value); f.ended = true; } else if (sec < f.start.idx) { state = true; } } } return state; }; module.Viewer.prototype._animInterp = function(state, startval, endval, idx) { switch (state) { case 'azimuth': // Azimuth is an angle, so we need to choose which direction to interpolate if (Math.abs(endval - startval) >= 180) { // wrap if (startval > endval) { return (startval * (1-idx) + (endval+360) * idx + 360) % 360; } else { return (startval * (1-idx) + (endval-360) * idx + 360) % 360; } } else { return (startval * (1-idx) + endval * idx); } default: // Everything else can be linearly interpolated return startval * (1-idx) + endval * idx; } }; module.Viewer.prototype.reset_view = function(center, height) { var asp = this.flatlims[1][0] / this.flatlims[1][1]; var camasp = height !== undefined ? asp : this.camera.cameraP.aspect; var size = [module.flatscale*this.flatlims[1][0], module.flatscale*this.flatlims[1][1]]; var min = [module.flatscale*this.flatlims[0][0], module.flatscale*this.flatlims[0][1]]; var xoff = center ? 0 : size[0] / 2 - min[0]; var zoff = center ? 0 : size[1] / 2 - min[1]; var h = size[0] / 2 / camasp; h /= Math.tan(this.camera.fov / 2 * Math.PI / 180); this.controls.target.set(xoff, this.flatoff[1], zoff); this.controls.setCamera(180, 90, h); this.setMix(1); this.setShift(0); }; module.Viewer.prototype.toggle_view = function() { this.meshes.left.visible = !this.meshes.left.visible; this.meshes.right.visible = !this.meshes.right.visible; for (var i = 0; i < 3; i++) { this.planes[i].update(); this.planes[i].mesh.visible = !this.planes[i].mesh.visible; } this.schedule(); }; // module.Viewer.prototype.saveflat = function(height, posturl) { // var width = height * this.flatlims[1][0] / this.flatlims[1][1];; // var roistate = $(this.object).find("#roishow").attr("checked"); // this.screenshot(width, height, function() { // this.reset_view(false, height); // $(this.object).find("#roishow").attr("checked", false); // $(this.object).find("#roishow").change(); // }.bind(this), function(png) { // $(this.object).find("#roishow").attr("checked", roistate); // $(this.object).find("#roishow").change(); // this.controls.target.set(0,0,0); // this.roipack.saveSVG(png, posturl); // }.bind(this)); // }; module.Viewer.prototype.setMix = function(val) { var num = this.meshes.left.geometry.morphTargets.length; var flat = num - 1; var n1 = Math.floor(val * num)-1; var n2 = Math.ceil(val * num)-1; for (var h in this.meshes) { var hemi = this.meshes[h]; if (hemi !== undefined) { for (var i=0; i < num; i++) { hemi.morphTargetInfluences[i] = 0; } if (this.flatlims !== undefined) this.uniforms.hide_mwall.value = (n2 == flat); hemi.morphTargetInfluences[n2] = (val * num)%1; if (n1 >= 0) hemi.morphTargetInfluences[n1] = 1 - (val * num)%1; } } if (this.flatlims !== undefined) { this.flatmix = n2 == flat ? (val*num-.000001)%1 : 0; this.setPivot(this.flatmix*180); this.uniforms.specular.value.set(1-this.flatmix, 1-this.flatmix, 1-this.flatmix); } $(this.object).find("#mix").slider("value", val); this.dispatchEvent({type:"mix", flat:this.flatmix, mix:val}); this.figure.notify("setmix", this, [val]); this.schedule(); }; module.Viewer.prototype.setPivot = function (val) { $(this.object).find("#pivot").slider("option", "value", val); this._pivot = val; var names = {left:1, right:-1} if (val > 0) { for (var name in names) { this.pivot[name].front.rotation.z = 0; this.pivot[name].back.rotation.z = val*Math.PI/180 * names[name]/ 2; } } else { for (var name in names) { this.pivot[name].back.rotation.z = 0; this.pivot[name].front.rotation.z = val*Math.PI/180 * names[name] / 2; } } this.figure.notify("setpivot", this, [val]); this.schedule(); }; module.Viewer.prototype.setShift = function(val) { this.pivot.left.front.position.x = -val; this.pivot.right.front.position.x = val; this.figure.notify('setshift', this, [val]); this.schedule(); }; module.Viewer.prototype.addData = function(data) { if (!(data instanceof Array)) data = [data]; var name, view; var handle = "<div class='handle'><span class='ui-icon ui-icon-carat-2-n-s'></span></div>"; for (var i = 0; i < data.length; i++) { view = data[i]; name = view.name; this.dataviews[name] = view; var found = false; $(this.object).find("#datasets li").each(function() { found = found || ($(this).text() == name); }) if (!found) $(this.object).find("#datasets").append("<li class='ui-corner-all'>"+handle+name+"</li>"); } this.setData(data[0].name); }; module.Viewer.prototype.setData = function(name) { if (this.state == "play") this.playpause(); if (name instanceof Array) { if (name.length == 1) { name = name[0]; } else if (name.length == 2) { var dv1 = this.dataviews[name[0]]; var dv2 = this.dataviews[name[1]]; //Can't create 2D data view when the view is already 2D! if (dv1.data.length > 1 || dv2.data.length > 1) return false; return this.addData(dataset.makeFrom(dv1, dv2)); } else { return false; } } this.active = this.dataviews[name]; this.dispatchEvent({type:"setData", data:this.active}); if (this.active.data[0].raw) { $("#color_fieldset").fadeTo(0.15, 0); } else { if (this.active.cmap !== undefined) this.setColormap(this.active.cmap); $("#color_fieldset").fadeTo(0.15, 1); } $.when(this.cmapload, this.loaded).done(function() { this.setVoxView(this.active.filter, viewopts.voxlines); //this.active.init(this.uniforms, this.meshes); $(this.object).find("#vrange").slider("option", {min: this.active.data[0].min, max:this.active.data[0].max}); this.setVminmax(this.active.vmin[0][0], this.active.vmax[0][0], 0); if (this.active.data.length > 1) { $(this.object).find("#vrange2").slider("option", {min: this.active.data[1].min, max:this.active.data[1].max}); this.setVminmax(this.active.vmin[0][1], this.active.vmax[0][1], 1); $(this.object).find("#vminmax2").show(); } else { $(this.object).find("#vminmax2").hide(); } if (this.active.data[0].movie) { $(this.object).find("#moviecontrols").show(); $(this.object).find("#bottombar").addClass("bbar_controls"); $(this.object).find("#movieprogress>div").slider("option", {min:0, max:this.active.length}); this.active.data[0].loaded.progress(function(idx) { var pct = idx / this.active.frames * 100; $(this.object).find("#movieprogress div.ui-slider-range").width(pct+"%"); }.bind(this)).done(function() { $(this.object).find("#movieprogress div.ui-slider-range").width("100%"); }.bind(this)); this.active.loaded.done(function() { this.setFrame(0); }.bind(this)); if (this.active.stim && figure) { figure.setSize("right", "30%"); this.movie = figure.add(jsplot.MovieAxes, "right", false, this.active.stim); this.movie.setFrame(0); } } else { $(this.object).find("#moviecontrols").hide(); $(this.object).find("#bottombar").removeClass("bbar_controls"); } $(this.object).find("#datasets li").each(function() { if ($(this).text() == name) $(this).addClass("ui-selected"); else $(this).removeClass("ui-selected"); }) $(this.object).find("#datasets").val(name); if (typeof(this.active.description) == "string") { var html = name+"<div class='datadesc'>"+this.active.description+"</div>"; $(this.object).find("#dataname").html(html).show(); } else { $(this.object).find("#dataname").text(name).show(); } this.schedule(); }.bind(this)); }; module.Viewer.prototype.nextData = function(dir) { var i = 0, found = false; var datasets = []; $(this.object).find("#datasets li").each(function() { if (!found) { if (this.className.indexOf("ui-selected") > 0) found = true; else i++; } datasets.push($(this).text()) }); if (dir === undefined) dir = 1 if (this.colormap.image.height > 8) { var idx = (i + dir * 2).mod(datasets.length); this.setData(datasets.slice(idx, idx+2)); } else { this.setData([datasets[(i+dir).mod(datasets.length)]]); } }; module.Viewer.prototype.rmData = function(name) { delete this.datasets[name]; $(this.object).find("#datasets li").each(function() { if ($(this).text() == name) $(this).remove(); }) }; module.Viewer.prototype.setColormap = function(cmap) { if (typeof(cmap) == 'string') { if (this.cmapnames[cmap] !== undefined) $(this.object).find("#colormap").ddslick('select', {index:this.cmapnames[cmap]}); return; } else if (cmap instanceof Image || cmap instanceof Element) { this.colormap = new THREE.Texture(cmap); } else if (cmap instanceof NParray) { var ncolors = cmap.shape[cmap.shape.length-1]; if (ncolors != 3 && ncolors != 4) throw "Invalid colormap shape" var height = cmap.shape.length > 2 ? cmap.shape[1] : 1; var fmt = ncolors == 3 ? THREE.RGBFormat : THREE.RGBAFormat; this.colormap = new THREE.DataTexture(cmap.data, cmap.shape[0], height, fmt); } if (this.active !== null) this.active.cmap = $(this.object).find("#colormap .dd-selected label").text(); this.cmapload = $.Deferred(); this.cmapload.done(function() { this.colormap.needsUpdate = true; this.colormap.premultiplyAlpha = true; this.colormap.flipY = true; this.colormap.minFilter = THREE.LinearFilter; this.colormap.magFilter = THREE.LinearFilter; this.uniforms.colormap.texture = this.colormap; this.loaded.done(this.schedule.bind(this)); if (this.colormap.image.height > 8) { $(this.object).find(".vcolorbar").show(); } else { $(this.object).find(".vcolorbar").hide(); } }.bind(this)); if ((cmap instanceof Image || cmap instanceof Element) && !cmap.complete) { cmap.addEventListener("load", function() { this.cmapload.resolve(); }.bind(this)); } else { this.cmapload.resolve(); } }; module.Viewer.prototype.setVminmax = function(vmin, vmax, dim) { if (dim === undefined) dim = 0; this.uniforms.vmin.value[dim] = vmin; this.uniforms.vmax.value[dim] = vmax; var range, min, max; if (dim == 0) { range = "#vrange"; min = "#vmin"; max = "#vmax"; } else { range = "#vrange2"; min = "#vmin2"; max = "#vmax2"; } if (vmax > $(this.object).find(range).slider("option", "max")) { $(this.object).find(range).slider("option", "max", vmax); this.active.data[dim].max = vmax; } else if (vmin < $(this.object).find(range).slider("option", "min")) { $(this.object).find(range).slider("option", "min", vmin); this.active.data[dim].min = vmin; } $(this.object).find(range).slider("values", [vmin, vmax]); $(this.object).find(min).val(vmin); $(this.object).find(max).val(vmax); this.active.vmin[0][dim] = vmin; this.active.vmax[0][dim] = vmax; this.schedule(); }; module.Viewer.prototype.setFrame = function(frame) { if (frame > this.active.length) { frame -= this.active.length; this._startplay += this.active.length; } this.frame = frame; this.active.set(this.uniforms, frame); $(this.object).find("#movieprogress div").slider("value", frame); $(this.object).find("#movieframe").attr("value", frame); this.schedule(); }; module.Viewer.prototype.setVoxView = function(interp, lines) { viewopts.voxlines = lines; if (this.active.filter != interp) { this.active.setFilter(interp); } this.active.init(this.uniforms, this.meshes, this.flatlims !== undefined); $(this.object).find("#datainterp option").attr("selected", null); $(this.object).find("#datainterp option[value="+interp+"]").attr("selected", "selected"); }; module.Viewer.prototype.playpause = function() { if (this.state == "pause") { //Start playing this._startplay = (new Date()) - (this.frame * this.active.rate) * 1000; this.state = "play"; this.schedule(); $(this.object).find("#moviecontrols img").attr("src", "resources/images/control-pause.png"); } else { this.state = "pause"; $(this.object).find("#moviecontrols img").attr("src", "resources/images/control-play.png"); } this.figure.notify("playtoggle", this); }; module.Viewer.prototype.getImage = function(width, height, post) { if (width === undefined) width = this.canvas.width(); if (height === undefined) height = width * this.canvas.height() / this.canvas.width(); console.log(width, height); var renderbuf = new THREE.WebGLRenderTarget(width, height, { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format:THREE.RGBAFormat, stencilBuffer:false, }); var clearAlpha = this.renderer.getClearAlpha(); var clearColor = this.renderer.getClearColor(); var oldw = this.canvas.width(), oldh = this.canvas.height(); this.camera.setSize(width, height); this.camera.updateProjectionMatrix(); //this.renderer.setSize(width, height); this.renderer.setClearColorHex(0x0, 0); this.renderer.render(this.scene, this.camera, renderbuf); //this.renderer.setSize(oldw, oldh); this.renderer.setClearColorHex(clearColor, clearAlpha); this.camera.setSize(oldw, oldh); this.camera.updateProjectionMatrix(); var img = mriview.getTexture(this.renderer.context, renderbuf) if (post !== undefined) $.post(post, {png:img.toDataURL()}); return img; }; var _bound = false; module.Viewer.prototype._bindUI = function() { $(window).scrollTop(0); $(window).resize(function() { this.resize(); }.bind(this)); this.canvas.resize(function() { this.resize(); }.bind(this)); //These are events that should only happen once, regardless of multiple views if (!_bound) { _bound = true; window.addEventListener( 'keydown', function(e) { btnspeed = 0.5; if (e.keyCode == 32) { //space if (this.active.data[0].movie) this.playpause(); e.preventDefault(); e.stopPropagation(); } else if (e.keyCode == 82) { //r this.animate([{idx:btnspeed, state:"target", value:this.surfcenter}, {idx:btnspeed, state:"mix", value:0.0}]); } else if (e.keyCode == 73) { //i this.animate([{idx:btnspeed, state:"mix", value:0.5}]); } else if (e.keyCode == 70) { //f this.animate([{idx:btnspeed, state:"target", value:[0,0,0]}, {idx:btnspeed, state:"mix", value:1.0}]); } }.bind(this)); } window.addEventListener( 'keydown', function(e) { if (e.target.tagName == "INPUT") return; if (e.keyCode == 107 || e.keyCode == 187) { //+ this.nextData(1); } else if (e.keyCode == 109 || e.keyCode == 189) { //- this.nextData(-1); } else if (e.keyCode == 76) { //l var box = $(this.object).find("#labelshow"); box.attr("checked", box.attr("checked") == "checked" ? null : "checked"); this.labelshow = !this.labelshow; this.schedule(); e.stopPropagation(); e.preventDefault(); } else if (e.keyCode == 81) { //q this.planes[0].next(); } else if (e.keyCode == 87) { //w this.planes[0].prev(); } else if (e.keyCode == 65) { //a this.planes[1].next(); } else if (e.keyCode == 83) { //s this.planes[1].prev(); } else if (e.keyCode == 90) { //z this.planes[2].next(); } else if (e.keyCode == 88) { //x this.planes[2].prev(); } }.bind(this)); var _this = this; $(this.object).find("#mix").slider({ min:0, max:1, step:.001, slide: function(event, ui) { this.setMix(ui.value); }.bind(this) }); $(this.object).find("#pivot").slider({ min:-180, max:180, step:.01, slide: function(event, ui) { this.setPivot(ui.value); }.bind(this) }); $(this.object).find("#shifthemis").slider({ min:0, max:100, step:.01, slide: function(event, ui) { this.setShift(ui.value); }.bind(this) }); if ($(this.object).find("#color_fieldset").length > 0) { $(this.object).find("#colormap").ddslick({ width:296, height:350, onSelected: function() { this.setColormap($(this.object).find("#colormap .dd-selected-image")[0]); }.bind(this) }); $(this.object).find("#vrange").slider({ range:true, width:200, min:0, max:1, step:.001, values:[0,1], slide: function(event, ui) { this.setVminmax(ui.values[0], ui.values[1]); }.bind(this) }); $(this.object).find("#vmin").change(function() { this.setVminmax( parseFloat($(this.object).find("#vmin").val()), parseFloat($(this.object).find("#vmax").val()) ); }.bind(this)); $(this.object).find("#vmax").change(function() { this.setVminmax( parseFloat($(this.object).find("#vmin").val()), parseFloat($(this.object).find("#vmax").val()) ); }.bind(this)); $(this.object).find("#vrange2").slider({ range:true, width:200, min:0, max:1, step:.001, values:[0,1], orientation:"vertical", slide: function(event, ui) { this.setVminmax(ui.values[0], ui.values[1], 1); }.bind(this) }); $(this.object).find("#vmin2").change(function() { this.setVminmax( parseFloat($(this.object).find("#vmin2").val()), parseFloat($(this.object).find("#vmax2").val()), 1); }.bind(this)); $(this.object).find("#vmax2").change(function() { this.setVminmax( parseFloat($(this.object).find("#vmin2").val()), parseFloat($(this.object).find("#vmax2").val()), 1); }.bind(this)); } var updateROIs = function() { this.roipack.update(this.renderer).done(function(tex){ this.uniforms.map.texture = tex; this.schedule(); }.bind(this)); }.bind(this); $(this.object).find("#roi_linewidth").slider({ min:.5, max:10, step:.1, value:3, change: updateROIs, }); $(this.object).find("#roi_linealpha").slider({ min:0, max:1, step:.001, value:1, change: updateROIs, }); $(this.object).find("#roi_fillalpha").slider({ min:0, max:1, step:.001, value:0, change: updateROIs, }); $(this.object).find("#roi_shadowalpha").slider({ min:0, max:20, step:1, value:4, change: updateROIs, }); $(this.object).find("#volview").change(this.toggle_view.bind(this)); $(this.object).find("#roi_linecolor").miniColors({close: updateROIs}); $(this.object).find("#roi_fillcolor").miniColors({close: updateROIs}); $(this.object).find("#roi_shadowcolor").miniColors({close: updateROIs}); var _this = this; $(this.object).find("#roishow").change(function() { if (this.checked) updateROIs(); else { _this.uniforms.map.texture = _this.blanktex; _this.schedule(); } }); $(this.object).find("#labelshow").change(function() { this.labelshow = !this.labelshow; this.schedule(); }.bind(this)); $(this.object).find("#layer_curvalpha").slider({ min:0, max:1, step:.001, value:1, slide:function(event, ui) { this.uniforms.curvAlpha.value = ui.value; this.schedule(); }.bind(this)}) $(this.object).find("#layer_curvmult").slider({ min:.001, max:2, step:.001, value:1, slide:function(event, ui) { this.uniforms.curvScale.value = ui.value; this.schedule(); }.bind(this)}) $(this.object).find("#layer_curvlim").slider({ min:0, max:.5, step:.001, value:.2, slide:function(event, ui) { this.uniforms.curvLim.value = ui.value; this.schedule(); }.bind(this)}) $(this.object).find("#layer_dataalpha").slider({ min:0, max:1, step:.001, value:1.0, slide:function(event, ui) { this.uniforms.dataAlpha.value = ui.value; this.schedule(); }.bind(this)}) $(this.object).find("#layer_hatchalpha").slider({ min:0, max:1, step:.001, value:1, slide:function(event, ui) { this.uniforms.hatchAlpha.value = ui.value; this.schedule(); }.bind(this)}) $(this.object).find("#layer_hatchcolor").miniColors({close: function(hex, rgb) { this.uniforms.hatchColor.value.set(rgb.r / 255, rgb.g / 255, rgb.b / 255); this.schedule(); }.bind(this)}); $(this.object).find("#voxline_show").change(function() { viewopts.voxlines = $(this.object).find("#voxline_show")[0].checked; this.setVoxView(this.active.filter, viewopts.voxlines); this.schedule(); }.bind(this)); $(this.object).find("#voxline_color").miniColors({ close: function(hex, rgb) { this.uniforms.voxlineColor.value.set(rgb.r / 255, rgb.g / 255, rgb.b/255); this.schedule(); }.bind(this)}); $(this.object).find("#voxline_width").slider({ min:.001, max:.1, step:.001, value:viewopts.voxline_width, slide:function(event, ui) { this.uniforms.voxlineWidth.value = ui.value; this.schedule(); }.bind(this)}); $(this.object).find("#datainterp").change(function() { this.setVoxView($(this.object).find("#datainterp").val(), viewopts.voxlines); this.schedule(); }.bind(this)); $(this.object).find("#thicklayers").slider({ min:1, max:32, step:1, value:1, slide:function(event, ui) { if (ui.value == 1) $(this.object).find("#thickmix_row").show(); else $(this.object).find("#thickmix_row").hide(); this.uniforms.nsamples.value = ui.value; this.active.init(this.uniforms, this.meshes, this.flatlims !== undefined, this.frames); this.schedule(); }.bind(this)}); $(this.object).find("#thickmix").slider({ min:0, max:1, step:.001, value:0.5, slide:function(event, ui) { this.figure.notify("setdepth", this, [ui.value]); this.uniforms.thickmix.value = ui.value; this.schedule(); }.bind(this)}) $(this.object).find("#resetflat").click(function() { this.reset_view(); }.bind(this)); //Dataset box var setdat = function(event, ui) { var names = []; $(this.object).find("#datasets li.ui-selected").each(function() { names.push($(this).text()); }); this.setData(names); }.bind(this) $(this.object).find("#datasets") .sortable({ handle: ".handle", stop: setdat, }) .selectable({ selecting: function(event, ui) { var selected = $(this.object).find("#datasets li.ui-selected, #datasets li.ui-selecting"); if (selected.length > 2) { $(ui.selecting).removeClass("ui-selecting"); } }.bind(this), unselected: function(event, ui) { var selected = $(this.object).find("#datasets li.ui-selected, #datasets li.ui-selecting"); if (selected.length < 1) { $(ui.unselected).addClass("ui-selected"); } }.bind(this), stop: setdat, }); $(this.object).find("#moviecontrol").click(this.playpause.bind(this)); $(this.object).find("#movieprogress>div").slider({min:0, max:1, step:.001, slide: function(event, ui) { this.setFrame(ui.value); this.figure.notify("setFrame", this, [ui.value]); }.bind(this) }); $(this.object).find("#movieprogress>div").append("<div class='ui-slider-range ui-widget-header'></div>"); $(this.object).find("#movieframe").change(function() { _this.setFrame(this.value); _this.figure.notify("setFrame", _this, [this.value]); }); }; module.Viewer.prototype._makeBtns = function(names) { var btnspeed = 0.5; // How long should folding/unfolding animations take? var td, btn, name; td = document.createElement("td"); btn = document.createElement("button"); btn.setAttribute("title", "Reset to fiducial view of the brain"); btn.innerHTML = "Fiducial"; td.setAttribute("style", "text-align:left;width:150px;"); btn.addEventListener("click", function() { this.animate([{idx:btnspeed, state:"target", value:[0,0,0]}, {idx:btnspeed, state:"mix", value:0.0}]); }.bind(this)); td.appendChild(btn); $(this.object).find("#mixbtns").append(td); var nameoff = this.flatlims === undefined ? 0 : 1; for (var i = 0; i < names.length; i++) { name = names[i][0].toUpperCase() + names[i].slice(1); td = document.createElement("td"); btn = document.createElement("button"); btn.innerHTML = name; btn.setAttribute("title", "Switch to the "+name+" view of the brain"); btn.addEventListener("click", function(j) { this.animate([{idx:btnspeed, state:"mix", value: (j+1) / (names.length+nameoff)}]); }.bind(this, i)); td.appendChild(btn); $(this.object).find("#mixbtns").append(td); } if (this.flatlims !== undefined) { td = document.createElement("td"); btn = document.createElement("button"); btn.innerHTML = "Flat"; btn.setAttribute("title", "Switch to the flattened view of the brain"); td.setAttribute("style", "text-align:right;width:150px;"); btn.addEventListener("click", function() { this.animate([{idx:btnspeed, state:"mix", value:1.0}]); }.bind(this)); td.appendChild(btn); $(this.object).find("#mixbtns").append(td); } $(this.object).find("#mix, #pivot, #shifthemis").parent().attr("colspan", names.length+2); }; module.Viewer.prototype._makeMesh = function(geom, shader) { //Creates the pivots and the mesh object given the geometry and shader var mesh = new THREE.Mesh(geom, shader); mesh.doubleSided = true; mesh.position.y = -this.flatoff[1]; mesh.updateMatrix(); var pivots = {back:new THREE.Object3D(), front:new THREE.Object3D()}; pivots.back.add(mesh); pivots.front.add(pivots.back); pivots.back.position.y = geom.boundingBox.min.y - geom.boundingBox.max.y; pivots.front.position.y = geom.boundingBox.max.y - geom.boundingBox.min.y + this.flatoff[1]; return {mesh:mesh, pivots:pivots}; }; return module; }(mriview || {}));
cortex/webgl/resources/js/mriview.js
// make sure canvas size is set properly for high DPI displays // From: http://www.khronos.org/webgl/wiki/HandlingHighDPI var dpi_ratio = window.devicePixelRatio || 1; var mriview = (function(module) { module.flatscale = .25; module.Viewer = function(figure) { //Allow objects to listen for mix updates THREE.EventTarget.call( this ); jsplot.Axes.call(this, figure); var blanktex = document.createElement("canvas"); blanktex.width = 16; blanktex.height = 16; this.blanktex = new THREE.Texture(blanktex); this.blanktex.magFilter = THREE.NearestFilter; this.blanktex.minFilter = THREE.NearestFilter; this.blanktex.needsUpdate = true; //Initialize all the html $(this.object).html($("#mriview_html").html()) this.canvas = $(this.object).find("#brain"); // scene and camera this.camera = new THREE.CombinedCamera( this.canvas.width(), this.canvas.height(), 45, 1.0, 1000, 1., 1000. ); this.camera.position.set(300, 300, 300); this.camera.up.set(0,0,1); this.scene = new THREE.Scene(); this.scene.add( this.camera ); this.controls = new THREE.LandscapeControls( $(this.object).find("#braincover")[0], this.camera ); this.controls.addEventListener("change", this.schedule.bind(this)); this.addEventListener("resize", function(event) { this.controls.resize(event.width, event.height); }.bind(this)); this.controls.addEventListener("mousedown", function(event) { if (this.active && this.active.fastshader) { this.meshes.left.material = this.active.fastshader; this.meshes.right.material = this.active.fastshader; } }.bind(this)); this.controls.addEventListener("mouseup", function(event) { if (this.active && this.active.fastshader) { this.meshes.left.material = this.active.shader; this.meshes.right.material = this.active.shader; this.schedule(); } }.bind(this)); this.light = new THREE.DirectionalLight( 0xffffff ); this.light.position.set( -200, -200, 1000 ).normalize(); this.camera.add( this.light ); this.flatmix = 0; this.frame = 0; // renderer this.renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer:true, canvas:this.canvas[0], }); this.renderer.sortObjects = true; this.renderer.setClearColorHex( 0x0, 1 ); this.renderer.context.getExtension("OES_texture_float"); this.renderer.context.getExtension("OES_texture_float_linear"); this.renderer.context.getExtension("OES_standard_derivatives"); this.renderer.setSize( this.canvas.width(), this.canvas.height() ); this.uniforms = THREE.UniformsUtils.merge( [ THREE.UniformsLib[ "lights" ], { diffuse: { type:'v3', value:new THREE.Vector3( .8,.8,.8 )}, specular: { type:'v3', value:new THREE.Vector3( 1,1,1 )}, emissive: { type:'v3', value:new THREE.Vector3( .2,.2,.2 )}, shininess: { type:'f', value:200}, thickmix: { type:'f', value:0.5}, framemix: { type:'f', value:0}, hatchrep: { type:'v2', value:new THREE.Vector2(108, 40) }, offsetRepeat:{type:'v4', value:new THREE.Vector4( 0, 0, 1, 1 ) }, //hatch: { type:'t', value:0, texture: module.makeHatch() }, colormap: { type:'t', value:0, texture: this.blanktex }, map: { type:'t', value:1, texture: this.blanktex }, data: { type:'tv', value:2, texture: [this.blanktex, this.blanktex, this.blanktex, this.blanktex]}, mosaic: { type:'v2v', value:[new THREE.Vector2(6, 6), new THREE.Vector2(6, 6)]}, dshape: { type:'v2v', value:[new THREE.Vector2(100, 100), new THREE.Vector2(100, 100)]}, volxfm: { type:'m4v', value:[new THREE.Matrix4(), new THREE.Matrix4()] }, nsamples: { type:'i', value:0}, vmin: { type:'fv1',value:[0,0]}, vmax: { type:'fv1',value:[1,1]}, curvAlpha: { type:'f', value:1.}, curvScale: { type:'f', value:.5}, curvLim: { type:'f', value:.2}, dataAlpha: { type:'f', value:1.0}, hatchAlpha: { type:'f', value:1.}, hatchColor: { type:'v3', value:new THREE.Vector3( 0,0,0 )}, voxlineColor:{type:'v3', value:new THREE.Vector3( 0,0,0 )}, voxlineWidth:{type:'f', value:viewopts.voxline_width}, hide_mwall: { type:'i', value:0}, } ]); this.state = "pause"; this._startplay = null; this._animation = null; this.loaded = $.Deferred().done(function() { this.schedule(); $(this.object).find("#ctmload").hide(); this.canvas.css("opacity", 1); }.bind(this)); this.cmapload = $.Deferred(); this.labelshow = true; this._pivot = 0; this.planes = [new sliceplane.Plane(this, 0), new sliceplane.Plane(this, 1), new sliceplane.Plane(this, 2)] this.planes[0].mesh.visible = false; this.planes[1].mesh.visible = false; this.planes[2].mesh.visible = false; this.dataviews = {}; this.active = null; var cmapnames = {}; $(this.object).find("#colormap option").each(function(idx) { cmapnames[$(this).text()] = idx; }); this.cmapnames = cmapnames; this._bindUI(); this.figure.register("setdepth", this, function(depth) { this.setState("depth", depth);}.bind(this)); this.figure.register("setmix", this, this.setMix.bind(this)); this.figure.register("setpivot", this, this.setPivot.bind(this)); this.figure.register("setshift", this, this.setShift.bind(this)); this.figure.register("setcamera", this, function(az, alt, rad, target) { this.setState('azimuth', az); this.setState('altitude', alt); this.setState('radius', rad); this.setState('target', target); this.schedule(); }.bind(this)); this.figure.register("playsync", this, function(time) { if (this._startplay != null) this._startplay = (new Date()) - (time * 1000); }); this.figure.register("playtoggle", this, this.playpause.bind(this)); this.figure.register("setFrame", this, this.setFrame.bind(this)); } module.Viewer.prototype = Object.create(jsplot.Axes.prototype); module.Viewer.prototype.constructor = module.Viewer; module.Viewer.prototype.schedule = function() { if (!this._scheduled) { this._scheduled = true; var target = this.getState('target'); var az = this.getState('azimuth'), alt = this.getState('altitude'), rad = this.getState('radius'); this.figure.notify("setcamera", this, [az, alt, rad, target]); requestAnimationFrame( function() { this.draw(); if (this.state == "play" || this._animation != null) { this.schedule(); } }.bind(this)); } }; module.Viewer.prototype.draw = function () { if (this.state == "play") { var sec = ((new Date()) - this._startplay) / 1000; this.setFrame(sec); } if (this._animation) { var sec = ((new Date()) - this._animation.start) / 1000; if (!this._animate(sec)) { this.meshes.left.material = this.active.shader; this.meshes.right.material = this.active.shader; delete this._animation; } } this.controls.update(this.flatmix); if (this.labelshow && this.roipack) { this.roipack.labels.render(this, this.renderer); } else { this.renderer.render(this.scene, this.camera); } this._scheduled = false; this.dispatchEvent({type:"draw"}); }; module.Viewer.prototype.load = function(ctminfo, callback) { var loader = new THREE.CTMLoader(false); loader.loadParts( ctminfo, function( geometries, materials, header, json ) { geometries[0].computeBoundingBox(); geometries[1].computeBoundingBox(); this.meshes = {}; this.pivot = {}; this.flatlims = json.flatlims; this.flatoff = [ Math.max( Math.abs(geometries[0].boundingBox.min.x), Math.abs(geometries[1].boundingBox.max.x) ) / 3, Math.min( geometries[0].boundingBox.min.y, geometries[1].boundingBox.min.y )]; this._makeBtns(json.names); //this.controls.flatsize = module.flatscale * this.flatlims[1][0]; this.controls.flatoff = this.flatoff[1]; var gb0 = geometries[0].boundingBox, gb1 = geometries[1].boundingBox; this.surfcenter = [ ((gb1.max.x - gb0.min.x) / 2) + gb0.min.x, (Math.max(gb0.max.y, gb1.max.y) - Math.min(gb0.min.y, gb1.min.y)) / 2 + Math.min(gb0.min.y, gb1.min.y), (Math.max(gb0.max.z, gb1.max.z) - Math.min(gb0.min.z, gb1.min.z)) / 2 + Math.min(gb0.min.z, gb1.min.z), ]; if (geometries[0].attributes.wm !== undefined) { //We have a thickness volume! this.uniforms.nsamples.value = 1; $(this.object).find("#thickmapping").show(); } var names = {left:0, right:1}; if (this.flatlims !== undefined) { //Do not attempt to create flatmaps or load ROIs if there are no flats var posdata = {left:[], right:[]}; for (var name in names) { var right = names[name]; var flats = module.makeFlat(geometries[right].attributes.uv.array, json.flatlims, this.flatoff, right); geometries[right].morphTargets.push({itemSize:3, stride:3, array:flats.pos}); geometries[right].morphNormals.push(flats.norms); posdata[name].push(geometries[right].attributes.position); for (var i = 0, il = geometries[right].morphTargets.length; i < il; i++) { posdata[name].push(geometries[right].morphTargets[i]); } geometries[right].reorderVertices(); geometries[right].dynamic = true; //var geom = splitverts(geometries[right], name == "right" ? leftlen : 0); var meshpiv = this._makeMesh(geometries[right], this.shader); this.meshes[name] = meshpiv.mesh; this.pivot[name] = meshpiv.pivots; this.scene.add(meshpiv.pivots.front); } $.get(loader.extractUrlBase(ctminfo)+json.rois, null, function(svgdoc) { this.roipack = new ROIpack(svgdoc, this.renderer, posdata); this.addEventListener("mix", function(evt) { this.roipack.labels.setMix(evt.mix); }.bind(this)); this.addEventListener("resize", function(event) { this.roipack.resize(event.width, event.height); }.bind(this)); this.roipack.update(this.renderer).done(function(tex) { this.uniforms.map.texture = tex; this.schedule(); }.bind(this)); }.bind(this)); } else { for (var name in names) { var right = names[name]; var len = geometries[right].attributes.position.array.length / 3; geometries[right].reorderVertices(); geometries[right].dynamic = true; var meshpiv = this._makeMesh(geometries[right], this.shader); this.meshes[name] = meshpiv.mesh; this.pivot[name] = meshpiv.pivots; this.scene.add(meshpiv.pivots.front); } } this.picker = new FacePick(this, this.meshes.left.geometry.attributes.position.array, this.meshes.right.geometry.attributes.position.array); this.addEventListener("mix", this.picker.setMix.bind(this.picker)); this.addEventListener("resize", function(event) { this.picker.resize(event.width, event.height); }.bind(this)); this.controls.addEventListener("change", function() { this.picker._valid = false; }.bind(this)); this.controls.addEventListener("pick", function(event) { this.picker.pick(event.x, event.y, event.keep); }.bind(this)); this.controls.addEventListener("dblpick", function(event) { this.picker.dblpick(event.x, event.y, event.keep); }.bind(this)); this.controls.addEventListener("undblpick", function(event) { this.picker.undblpick(); }.bind(this)); this.setState("target", this.surfcenter); if (typeof(callback) == "function") this.loaded.done(callback); this.loaded.resolve(); }.bind(this), true, true ); }; module.Viewer.prototype.resize = function(width, height) { if (width !== undefined) { if (width.width !== undefined) { height = width.height; width = width.width; } $(this.object).find("#brain").css("width", width); this.canvas[0].width = width; //width = $(this.object).width(); } var w = width === undefined ? $(this.object).width() : width; var h = height === undefined ? $(this.object).height() : height; var aspect = w / h; this.renderer.setSize( w * dpi_ratio, h * dpi_ratio ); this.renderer.domElement.style.width = w + 'px'; this.renderer.domElement.style.height = h + 'px'; // this.renderer.setSize(w, h); this.camera.setSize(aspect * 100, 100); this.camera.updateProjectionMatrix(); this.dispatchEvent({ type:"resize", width:w, height:h}); this.loaded.done(this.schedule.bind(this)); }; module.Viewer.prototype.getState = function(state) { switch (state) { case 'mix': return $(this.object).find("#mix").slider("value"); case 'pivot': //return $("#pivot").slider("value"); return this._pivot; case 'frame': return this.frame; case 'azimuth': return this.controls.azimuth; case 'altitude': return this.controls.altitude; case 'radius': return this.controls.radius; case 'target': var t = this.controls.target; return [t.x, t.y, t.z]; case 'depth': return this.uniforms.thickmix.value; }; }; module.Viewer.prototype.setState = function(state, value) { switch (state) { case 'mix': return this.setMix(value); case 'pivot': return this.setPivot(value); case 'frame': return this.setFrame(value); case 'azimuth': return this.controls.setCamera(value); case 'altitude': return this.controls.setCamera(undefined, value); case 'radius': return this.controls.setCamera(undefined, undefined, value); case 'target': if (this.roipack) this.roipack._updatemove = true; return this.controls.target.set(value[0], value[1], value[2]); case 'depth': return this.uniforms.thickmix.value = value; }; }; module.Viewer.prototype.animate = function(animation) { var state = {}; var anim = []; animation.sort(function(a, b) { return a.idx - b.idx}); for (var i = 0, il = animation.length; i < il; i++) { var f = animation[i]; if (f.idx == 0) { this.setState(f.state, f.value); state[f.state] = {idx:0, val:f.value}; } else { if (state[f.state] === undefined) state[f.state] = {idx:0, val:this.getState(f.state)}; var start = {idx:state[f.state].idx, state:f.state, value:state[f.state].val} var end = {idx:f.idx, state:f.state, value:f.value}; state[f.state].idx = f.idx; state[f.state].val = f.value; if (start.value instanceof Array) { var test = true; for (var j = 0; test && j < start.value.length; j++) test = test && (start.value[j] == end.value[j]); if (!test) anim.push({start:start, end:end, ended:false}); } else if (start.value != end.value) anim.push({start:start, end:end, ended:false}); } } if (this.active.fastshader) { this.meshes.left.material = this.active.fastshader; this.meshes.right.material = this.active.fastshader; } this._animation = {anim:anim, start:new Date()}; this.schedule(); }; module.Viewer.prototype._animate = function(sec) { var state = false; var idx, val, f, i, j; for (i = 0, il = this._animation.anim.length; i < il; i++) { f = this._animation.anim[i]; if (!f.ended) { if (f.start.idx <= sec && sec < f.end.idx) { idx = (sec - f.start.idx) / (f.end.idx - f.start.idx); if (f.start.value instanceof Array) { val = []; for (j = 0; j < f.start.value.length; j++) { //val.push(f.start.value[j]*(1-idx) + f.end.value[j]*idx); val.push(this._animInterp(f.start.state, f.start.value[j], f.end.value[j], idx)); } } else { //val = f.start.value * (1-idx) + f.end.value * idx; val = this._animInterp(f.start.state, f.start.value, f.end.value, idx); } this.setState(f.start.state, val); state = true; } else if (sec >= f.end.idx) { this.setState(f.end.state, f.end.value); f.ended = true; } else if (sec < f.start.idx) { state = true; } } } return state; }; module.Viewer.prototype._animInterp = function(state, startval, endval, idx) { switch (state) { case 'azimuth': // Azimuth is an angle, so we need to choose which direction to interpolate if (Math.abs(endval - startval) >= 180) { // wrap if (startval > endval) { return (startval * (1-idx) + (endval+360) * idx + 360) % 360; } else { return (startval * (1-idx) + (endval-360) * idx + 360) % 360; } } else { return (startval * (1-idx) + endval * idx); } default: // Everything else can be linearly interpolated return startval * (1-idx) + endval * idx; } }; module.Viewer.prototype.reset_view = function(center, height) { var asp = this.flatlims[1][0] / this.flatlims[1][1]; var camasp = height !== undefined ? asp : this.camera.cameraP.aspect; var size = [module.flatscale*this.flatlims[1][0], module.flatscale*this.flatlims[1][1]]; var min = [module.flatscale*this.flatlims[0][0], module.flatscale*this.flatlims[0][1]]; var xoff = center ? 0 : size[0] / 2 - min[0]; var zoff = center ? 0 : size[1] / 2 - min[1]; var h = size[0] / 2 / camasp; h /= Math.tan(this.camera.fov / 2 * Math.PI / 180); this.controls.target.set(xoff, this.flatoff[1], zoff); this.controls.setCamera(180, 90, h); this.setMix(1); this.setShift(0); }; module.Viewer.prototype.toggle_view = function() { this.meshes.left.visible = !this.meshes.left.visible; this.meshes.right.visible = !this.meshes.right.visible; for (var i = 0; i < 3; i++) { this.planes[i].update(); this.planes[i].mesh.visible = !this.planes[i].mesh.visible; } this.schedule(); }; // module.Viewer.prototype.saveflat = function(height, posturl) { // var width = height * this.flatlims[1][0] / this.flatlims[1][1];; // var roistate = $(this.object).find("#roishow").attr("checked"); // this.screenshot(width, height, function() { // this.reset_view(false, height); // $(this.object).find("#roishow").attr("checked", false); // $(this.object).find("#roishow").change(); // }.bind(this), function(png) { // $(this.object).find("#roishow").attr("checked", roistate); // $(this.object).find("#roishow").change(); // this.controls.target.set(0,0,0); // this.roipack.saveSVG(png, posturl); // }.bind(this)); // }; module.Viewer.prototype.setMix = function(val) { var num = this.meshes.left.geometry.morphTargets.length; var flat = num - 1; var n1 = Math.floor(val * num)-1; var n2 = Math.ceil(val * num)-1; for (var h in this.meshes) { var hemi = this.meshes[h]; if (hemi !== undefined) { for (var i=0; i < num; i++) { hemi.morphTargetInfluences[i] = 0; } if (this.flatlims !== undefined) this.uniforms.hide_mwall.value = (n2 == flat); hemi.morphTargetInfluences[n2] = (val * num)%1; if (n1 >= 0) hemi.morphTargetInfluences[n1] = 1 - (val * num)%1; } } if (this.flatlims !== undefined) { this.flatmix = n2 == flat ? (val*num-.000001)%1 : 0; this.setPivot(this.flatmix*180); this.uniforms.specular.value.set(1-this.flatmix, 1-this.flatmix, 1-this.flatmix); } $(this.object).find("#mix").slider("value", val); this.dispatchEvent({type:"mix", flat:this.flatmix, mix:val}); this.figure.notify("setmix", this, [val]); this.schedule(); }; module.Viewer.prototype.setPivot = function (val) { $(this.object).find("#pivot").slider("option", "value", val); this._pivot = val; var names = {left:1, right:-1} if (val > 0) { for (var name in names) { this.pivot[name].front.rotation.z = 0; this.pivot[name].back.rotation.z = val*Math.PI/180 * names[name]/ 2; } } else { for (var name in names) { this.pivot[name].back.rotation.z = 0; this.pivot[name].front.rotation.z = val*Math.PI/180 * names[name] / 2; } } this.figure.notify("setpivot", this, [val]); this.schedule(); }; module.Viewer.prototype.setShift = function(val) { this.pivot.left.front.position.x = -val; this.pivot.right.front.position.x = val; this.figure.notify('setshift', this, [val]); this.schedule(); }; module.Viewer.prototype.addData = function(data) { if (!(data instanceof Array)) data = [data]; var name, view; var handle = "<div class='handle'><span class='ui-icon ui-icon-carat-2-n-s'></span></div>"; for (var i = 0; i < data.length; i++) { view = data[i]; name = view.name; this.dataviews[name] = view; var found = false; $(this.object).find("#datasets li").each(function() { found = found || ($(this).text() == name); }) if (!found) $(this.object).find("#datasets").append("<li class='ui-corner-all'>"+handle+name+"</li>"); } this.setData(data[0].name); }; module.Viewer.prototype.setData = function(name) { if (this.state == "play") this.playpause(); if (name instanceof Array) { if (name.length == 1) { name = name[0]; } else if (name.length == 2) { var dv1 = this.dataviews[name[0]]; var dv2 = this.dataviews[name[1]]; //Can't create 2D data view when the view is already 2D! if (dv1.data.length > 1 || dv2.data.length > 1) return false; return this.addData(dataset.makeFrom(dv1, dv2)); } else { return false; } } this.active = this.dataviews[name]; this.dispatchEvent({type:"setData", data:this.active}); if (this.active.data[0].raw) { $("#color_fieldset").fadeTo(0.15, 0); } else { if (this.active.cmap !== undefined) this.setColormap(this.active.cmap); $("#color_fieldset").fadeTo(0.15, 1); } $.when(this.cmapload, this.loaded).done(function() { this.setVoxView(this.active.filter, viewopts.voxlines); //this.active.init(this.uniforms, this.meshes); $(this.object).find("#vrange").slider("option", {min: this.active.data[0].min, max:this.active.data[0].max}); this.setVminmax(this.active.vmin[0][0], this.active.vmax[0][0], 0); if (this.active.data.length > 1) { $(this.object).find("#vrange2").slider("option", {min: this.active.data[1].min, max:this.active.data[1].max}); this.setVminmax(this.active.vmin[0][1], this.active.vmax[0][1], 1); $(this.object).find("#vminmax2").show(); } else { $(this.object).find("#vminmax2").hide(); } if (this.active.data[0].movie) { $(this.object).find("#moviecontrols").show(); $(this.object).find("#bottombar").addClass("bbar_controls"); $(this.object).find("#movieprogress>div").slider("option", {min:0, max:this.active.length}); this.active.data[0].loaded.progress(function(idx) { var pct = idx / this.active.frames * 100; $(this.object).find("#movieprogress div.ui-slider-range").width(pct+"%"); }.bind(this)).done(function() { $(this.object).find("#movieprogress div.ui-slider-range").width("100%"); }.bind(this)); this.active.loaded.done(function() { this.setFrame(0); }.bind(this)); if (this.active.stim && figure) { figure.setSize("right", "30%"); this.movie = figure.add(jsplot.MovieAxes, "right", false, this.active.stim); this.movie.setFrame(0); } } else { $(this.object).find("#moviecontrols").hide(); $(this.object).find("#bottombar").removeClass("bbar_controls"); } $(this.object).find("#datasets li").each(function() { if ($(this).text() == name) $(this).addClass("ui-selected"); else $(this).removeClass("ui-selected"); }) $(this.object).find("#datasets").val(name); if (typeof(this.active.description) == "string") { var html = name+"<div class='datadesc'>"+this.active.description+"</div>"; $(this.object).find("#dataname").html(html).show(); } else { $(this.object).find("#dataname").text(name).show(); } this.schedule(); }.bind(this)); }; module.Viewer.prototype.nextData = function(dir) { var i = 0, found = false; var datasets = []; $(this.object).find("#datasets li").each(function() { if (!found) { if (this.className.indexOf("ui-selected") > 0) found = true; else i++; } datasets.push($(this).text()) }); if (dir === undefined) dir = 1 if (this.colormap.image.height > 8) { var idx = (i + dir * 2).mod(datasets.length); this.setData(datasets.slice(idx, idx+2)); } else { this.setData([datasets[(i+dir).mod(datasets.length)]]); } }; module.Viewer.prototype.rmData = function(name) { delete this.datasets[name]; $(this.object).find("#datasets li").each(function() { if ($(this).text() == name) $(this).remove(); }) }; module.Viewer.prototype.setColormap = function(cmap) { if (typeof(cmap) == 'string') { if (this.cmapnames[cmap] !== undefined) $(this.object).find("#colormap").ddslick('select', {index:this.cmapnames[cmap]}); return; } else if (cmap instanceof Image || cmap instanceof Element) { this.colormap = new THREE.Texture(cmap); } else if (cmap instanceof NParray) { var ncolors = cmap.shape[cmap.shape.length-1]; if (ncolors != 3 && ncolors != 4) throw "Invalid colormap shape" var height = cmap.shape.length > 2 ? cmap.shape[1] : 1; var fmt = ncolors == 3 ? THREE.RGBFormat : THREE.RGBAFormat; this.colormap = new THREE.DataTexture(cmap.data, cmap.shape[0], height, fmt); } if (this.active !== null) this.active.cmap = $(this.object).find("#colormap .dd-selected label").text(); this.cmapload = $.Deferred(); this.cmapload.done(function() { this.colormap.needsUpdate = true; this.colormap.premultiplyAlpha = true; this.colormap.flipY = true; this.colormap.minFilter = THREE.LinearFilter; this.colormap.magFilter = THREE.LinearFilter; this.uniforms.colormap.texture = this.colormap; this.loaded.done(this.schedule.bind(this)); if (this.colormap.image.height > 8) { $(this.object).find(".vcolorbar").show(); } else { $(this.object).find(".vcolorbar").hide(); } }.bind(this)); if ((cmap instanceof Image || cmap instanceof Element) && !cmap.complete) { cmap.addEventListener("load", function() { this.cmapload.resolve(); }.bind(this)); } else { this.cmapload.resolve(); } }; module.Viewer.prototype.setVminmax = function(vmin, vmax, dim) { if (dim === undefined) dim = 0; this.uniforms.vmin.value[dim] = vmin; this.uniforms.vmax.value[dim] = vmax; var range, min, max; if (dim == 0) { range = "#vrange"; min = "#vmin"; max = "#vmax"; } else { range = "#vrange2"; min = "#vmin2"; max = "#vmax2"; } if (vmax > $(this.object).find(range).slider("option", "max")) { $(this.object).find(range).slider("option", "max", vmax); this.active.data[dim].max = vmax; } else if (vmin < $(this.object).find(range).slider("option", "min")) { $(this.object).find(range).slider("option", "min", vmin); this.active.data[dim].min = vmin; } $(this.object).find(range).slider("values", [vmin, vmax]); $(this.object).find(min).val(vmin); $(this.object).find(max).val(vmax); this.active.vmin[0][dim] = vmin; this.active.vmax[0][dim] = vmax; this.schedule(); }; module.Viewer.prototype.setFrame = function(frame) { if (frame > this.active.length) { frame -= this.active.length; this._startplay += this.active.length; } this.frame = frame; this.active.set(this.uniforms, frame); $(this.object).find("#movieprogress div").slider("value", frame); $(this.object).find("#movieframe").attr("value", frame); this.schedule(); }; module.Viewer.prototype.setVoxView = function(interp, lines) { viewopts.voxlines = lines; if (this.active.filter != interp) { this.active.setFilter(interp); } this.active.init(this.uniforms, this.meshes, this.flatlims !== undefined); $(this.object).find("#datainterp option").attr("selected", null); $(this.object).find("#datainterp option[value="+interp+"]").attr("selected", "selected"); }; module.Viewer.prototype.playpause = function() { if (this.state == "pause") { //Start playing this._startplay = (new Date()) - (this.frame * this.active.rate) * 1000; this.state = "play"; this.schedule(); $(this.object).find("#moviecontrols img").attr("src", "resources/images/control-pause.png"); } else { this.state = "pause"; $(this.object).find("#moviecontrols img").attr("src", "resources/images/control-play.png"); } this.figure.notify("playtoggle", this); }; module.Viewer.prototype.getImage = function(width, height, post) { if (width === undefined) width = this.canvas.width(); if (height === undefined) height = width * this.canvas.height() / this.canvas.width(); console.log(width, height); var renderbuf = new THREE.WebGLRenderTarget(width, height, { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format:THREE.RGBAFormat, stencilBuffer:false, }); var clearAlpha = this.renderer.getClearAlpha(); var clearColor = this.renderer.getClearColor(); var oldw = this.canvas.width(), oldh = this.canvas.height(); this.camera.setSize(width, height); this.camera.updateProjectionMatrix(); //this.renderer.setSize(width, height); this.renderer.setClearColorHex(0x0, 0); this.renderer.render(this.scene, this.camera, renderbuf); //this.renderer.setSize(oldw, oldh); this.renderer.setClearColorHex(clearColor, clearAlpha); this.camera.setSize(oldw, oldh); this.camera.updateProjectionMatrix(); var img = mriview.getTexture(this.renderer.context, renderbuf) if (post !== undefined) $.post(post, {png:img.toDataURL()}); return img; }; var _bound = false; module.Viewer.prototype._bindUI = function() { $(window).scrollTop(0); $(window).resize(function() { this.resize(); }.bind(this)); this.canvas.resize(function() { this.resize(); }.bind(this)); //These are events that should only happen once, regardless of multiple views if (!_bound) { _bound = true; window.addEventListener( 'keydown', function(e) { btnspeed = 0.5; if (e.keyCode == 32) { //space if (this.active.data[0].movie) this.playpause(); e.preventDefault(); e.stopPropagation(); } else if (e.keyCode == 82) { //r this.animate([{idx:btnspeed, state:"target", value:this.surfcenter}, {idx:btnspeed, state:"mix", value:0.0}]); } else if (e.keyCode == 73) { //i this.animate([{idx:btnspeed, state:"mix", value:0.5}]); } else if (e.keyCode == 70) { //f this.animate([{idx:btnspeed, state:"target", value:[0,0,0]}, {idx:btnspeed, state:"mix", value:1.0}]); } }.bind(this)); } window.addEventListener( 'keydown', function(e) { if (e.target.tagName == "INPUT") return; if (e.keyCode == 107 || e.keyCode == 187) { //+ this.nextData(1); } else if (e.keyCode == 109 || e.keyCode == 189) { //- this.nextData(-1); } else if (e.keyCode == 76) { //l this.labelshow = !this.labelshow; this.schedule(); e.stopPropagation(); e.preventDefault(); } else if (e.keyCode == 81) { //q this.planes[0].next(); } else if (e.keyCode == 87) { //w this.planes[0].prev(); } else if (e.keyCode == 65) { //a this.planes[1].next(); } else if (e.keyCode == 83) { //s this.planes[1].prev(); } else if (e.keyCode == 90) { //z this.planes[2].next(); } else if (e.keyCode == 88) { //x this.planes[2].prev(); } }.bind(this)); var _this = this; $(this.object).find("#mix").slider({ min:0, max:1, step:.001, slide: function(event, ui) { this.setMix(ui.value); }.bind(this) }); $(this.object).find("#pivot").slider({ min:-180, max:180, step:.01, slide: function(event, ui) { this.setPivot(ui.value); }.bind(this) }); $(this.object).find("#shifthemis").slider({ min:0, max:100, step:.01, slide: function(event, ui) { this.setShift(ui.value); }.bind(this) }); if ($(this.object).find("#color_fieldset").length > 0) { $(this.object).find("#colormap").ddslick({ width:296, height:350, onSelected: function() { this.setColormap($(this.object).find("#colormap .dd-selected-image")[0]); }.bind(this) }); $(this.object).find("#vrange").slider({ range:true, width:200, min:0, max:1, step:.001, values:[0,1], slide: function(event, ui) { this.setVminmax(ui.values[0], ui.values[1]); }.bind(this) }); $(this.object).find("#vmin").change(function() { this.setVminmax( parseFloat($(this.object).find("#vmin").val()), parseFloat($(this.object).find("#vmax").val()) ); }.bind(this)); $(this.object).find("#vmax").change(function() { this.setVminmax( parseFloat($(this.object).find("#vmin").val()), parseFloat($(this.object).find("#vmax").val()) ); }.bind(this)); $(this.object).find("#vrange2").slider({ range:true, width:200, min:0, max:1, step:.001, values:[0,1], orientation:"vertical", slide: function(event, ui) { this.setVminmax(ui.values[0], ui.values[1], 1); }.bind(this) }); $(this.object).find("#vmin2").change(function() { this.setVminmax( parseFloat($(this.object).find("#vmin2").val()), parseFloat($(this.object).find("#vmax2").val()), 1); }.bind(this)); $(this.object).find("#vmax2").change(function() { this.setVminmax( parseFloat($(this.object).find("#vmin2").val()), parseFloat($(this.object).find("#vmax2").val()), 1); }.bind(this)); } var updateROIs = function() { this.roipack.update(this.renderer).done(function(tex){ this.uniforms.map.texture = tex; this.schedule(); }.bind(this)); }.bind(this); $(this.object).find("#roi_linewidth").slider({ min:.5, max:10, step:.1, value:3, change: updateROIs, }); $(this.object).find("#roi_linealpha").slider({ min:0, max:1, step:.001, value:1, change: updateROIs, }); $(this.object).find("#roi_fillalpha").slider({ min:0, max:1, step:.001, value:0, change: updateROIs, }); $(this.object).find("#roi_shadowalpha").slider({ min:0, max:20, step:1, value:4, change: updateROIs, }); $(this.object).find("#volview").change(this.toggle_view.bind(this)); $(this.object).find("#roi_linecolor").miniColors({close: updateROIs}); $(this.object).find("#roi_fillcolor").miniColors({close: updateROIs}); $(this.object).find("#roi_shadowcolor").miniColors({close: updateROIs}); var _this = this; $(this.object).find("#roishow").change(function() { if (this.checked) updateROIs(); else { _this.uniforms.map.texture = this.blanktex; _this.schedule(); } }); $(this.object).find("#labelshow").change(function() { this.labelshow = !this.labelshow; this.schedule(); }.bind(this)); $(this.object).find("#layer_curvalpha").slider({ min:0, max:1, step:.001, value:1, slide:function(event, ui) { this.uniforms.curvAlpha.value = ui.value; this.schedule(); }.bind(this)}) $(this.object).find("#layer_curvmult").slider({ min:.001, max:2, step:.001, value:1, slide:function(event, ui) { this.uniforms.curvScale.value = ui.value; this.schedule(); }.bind(this)}) $(this.object).find("#layer_curvlim").slider({ min:0, max:.5, step:.001, value:.2, slide:function(event, ui) { this.uniforms.curvLim.value = ui.value; this.schedule(); }.bind(this)}) $(this.object).find("#layer_dataalpha").slider({ min:0, max:1, step:.001, value:1.0, slide:function(event, ui) { this.uniforms.dataAlpha.value = ui.value; this.schedule(); }.bind(this)}) $(this.object).find("#layer_hatchalpha").slider({ min:0, max:1, step:.001, value:1, slide:function(event, ui) { this.uniforms.hatchAlpha.value = ui.value; this.schedule(); }.bind(this)}) $(this.object).find("#layer_hatchcolor").miniColors({close: function(hex, rgb) { this.uniforms.hatchColor.value.set(rgb.r / 255, rgb.g / 255, rgb.b / 255); this.schedule(); }.bind(this)}); $(this.object).find("#voxline_show").change(function() { viewopts.voxlines = $(this.object).find("#voxline_show")[0].checked; this.setVoxView(this.active.filter, viewopts.voxlines); this.schedule(); }.bind(this)); $(this.object).find("#voxline_color").miniColors({ close: function(hex, rgb) { this.uniforms.voxlineColor.value.set(rgb.r / 255, rgb.g / 255, rgb.b/255); this.schedule(); }.bind(this)}); $(this.object).find("#voxline_width").slider({ min:.001, max:.1, step:.001, value:viewopts.voxline_width, slide:function(event, ui) { this.uniforms.voxlineWidth.value = ui.value; this.schedule(); }.bind(this)}); $(this.object).find("#datainterp").change(function() { this.setVoxView($(this.object).find("#datainterp").val(), viewopts.voxlines); this.schedule(); }.bind(this)); $(this.object).find("#thicklayers").slider({ min:1, max:32, step:1, value:1, slide:function(event, ui) { if (ui.value == 1) $(this.object).find("#thickmix_row").show(); else $(this.object).find("#thickmix_row").hide(); this.uniforms.nsamples.value = ui.value; this.active.init(this.uniforms, this.meshes, this.flatlims !== undefined, this.frames); this.schedule(); }.bind(this)}); $(this.object).find("#thickmix").slider({ min:0, max:1, step:.001, value:0.5, slide:function(event, ui) { this.figure.notify("setdepth", this, [ui.value]); this.uniforms.thickmix.value = ui.value; this.schedule(); }.bind(this)}) $(this.object).find("#resetflat").click(function() { this.reset_view(); }.bind(this)); //Dataset box var setdat = function(event, ui) { var names = []; $(this.object).find("#datasets li.ui-selected").each(function() { names.push($(this).text()); }); this.setData(names); }.bind(this) $(this.object).find("#datasets") .sortable({ handle: ".handle", stop: setdat, }) .selectable({ selecting: function(event, ui) { var selected = $(this.object).find("#datasets li.ui-selected, #datasets li.ui-selecting"); if (selected.length > 2) { $(ui.selecting).removeClass("ui-selecting"); } }.bind(this), unselected: function(event, ui) { var selected = $(this.object).find("#datasets li.ui-selected, #datasets li.ui-selecting"); if (selected.length < 1) { $(ui.unselected).addClass("ui-selected"); } }.bind(this), stop: setdat, }); $(this.object).find("#moviecontrol").click(this.playpause.bind(this)); $(this.object).find("#movieprogress>div").slider({min:0, max:1, step:.001, slide: function(event, ui) { this.setFrame(ui.value); this.figure.notify("setFrame", this, [ui.value]); }.bind(this) }); $(this.object).find("#movieprogress>div").append("<div class='ui-slider-range ui-widget-header'></div>"); $(this.object).find("#movieframe").change(function() { _this.setFrame(this.value); _this.figure.notify("setFrame", _this, [this.value]); }); }; module.Viewer.prototype._makeBtns = function(names) { var btnspeed = 0.5; // How long should folding/unfolding animations take? var td, btn, name; td = document.createElement("td"); btn = document.createElement("button"); btn.setAttribute("title", "Reset to fiducial view of the brain"); btn.innerHTML = "Fiducial"; td.setAttribute("style", "text-align:left;width:150px;"); btn.addEventListener("click", function() { this.animate([{idx:btnspeed, state:"target", value:[0,0,0]}, {idx:btnspeed, state:"mix", value:0.0}]); }.bind(this)); td.appendChild(btn); $(this.object).find("#mixbtns").append(td); var nameoff = this.flatlims === undefined ? 0 : 1; for (var i = 0; i < names.length; i++) { name = names[i][0].toUpperCase() + names[i].slice(1); td = document.createElement("td"); btn = document.createElement("button"); btn.innerHTML = name; btn.setAttribute("title", "Switch to the "+name+" view of the brain"); btn.addEventListener("click", function(j) { this.animate([{idx:btnspeed, state:"mix", value: (j+1) / (names.length+nameoff)}]); }.bind(this, i)); td.appendChild(btn); $(this.object).find("#mixbtns").append(td); } if (this.flatlims !== undefined) { td = document.createElement("td"); btn = document.createElement("button"); btn.innerHTML = "Flat"; btn.setAttribute("title", "Switch to the flattened view of the brain"); td.setAttribute("style", "text-align:right;width:150px;"); btn.addEventListener("click", function() { this.animate([{idx:btnspeed, state:"mix", value:1.0}]); }.bind(this)); td.appendChild(btn); $(this.object).find("#mixbtns").append(td); } $(this.object).find("#mix, #pivot, #shifthemis").parent().attr("colspan", names.length+2); }; module.Viewer.prototype._makeMesh = function(geom, shader) { //Creates the pivots and the mesh object given the geometry and shader var mesh = new THREE.Mesh(geom, shader); mesh.doubleSided = true; mesh.position.y = -this.flatoff[1]; mesh.updateMatrix(); var pivots = {back:new THREE.Object3D(), front:new THREE.Object3D()}; pivots.back.add(mesh); pivots.front.add(pivots.back); pivots.back.position.y = geom.boundingBox.min.y - geom.boundingBox.max.y; pivots.front.position.y = geom.boundingBox.max.y - geom.boundingBox.min.y + this.flatoff[1]; return {mesh:mesh, pivots:pivots}; }; return module; }(mriview || {}));
Fix issues #69 and #70
cortex/webgl/resources/js/mriview.js
Fix issues #69 and #70
<ide><path>ortex/webgl/resources/js/mriview.js <ide> } else if (e.keyCode == 109 || e.keyCode == 189) { //- <ide> this.nextData(-1); <ide> } else if (e.keyCode == 76) { //l <add> var box = $(this.object).find("#labelshow"); <add> box.attr("checked", box.attr("checked") == "checked" ? null : "checked"); <ide> this.labelshow = !this.labelshow; <ide> this.schedule(); <ide> e.stopPropagation(); <ide> if (this.checked) <ide> updateROIs(); <ide> else { <del> _this.uniforms.map.texture = this.blanktex; <add> _this.uniforms.map.texture = _this.blanktex; <ide> _this.schedule(); <ide> } <ide> });
Java
apache-2.0
7e4d6228902abec1575c4bda43de1c75f184f16e
0
matthewtckr/pentaho-kettle,graimundo/pentaho-kettle,pedrofvteixeira/pentaho-kettle,aminmkhan/pentaho-kettle,ddiroma/pentaho-kettle,Advent51/pentaho-kettle,dkincade/pentaho-kettle,cjsonger/pentaho-kettle,pedrofvteixeira/pentaho-kettle,matrix-stone/pentaho-kettle,wseyler/pentaho-kettle,jbrant/pentaho-kettle,matthewtckr/pentaho-kettle,andrei-viaryshka/pentaho-kettle,MikhailHubanau/pentaho-kettle,skofra0/pentaho-kettle,tmcsantos/pentaho-kettle,graimundo/pentaho-kettle,wseyler/pentaho-kettle,nanata1115/pentaho-kettle,CapeSepias/pentaho-kettle,yshakhau/pentaho-kettle,SergeyTravin/pentaho-kettle,ddiroma/pentaho-kettle,drndos/pentaho-kettle,brosander/pentaho-kettle,nanata1115/pentaho-kettle,flbrino/pentaho-kettle,akhayrutdinov/pentaho-kettle,nicoben/pentaho-kettle,ma459006574/pentaho-kettle,ccaspanello/pentaho-kettle,jbrant/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,sajeetharan/pentaho-kettle,roboguy/pentaho-kettle,SergeyTravin/pentaho-kettle,hudak/pentaho-kettle,lgrill-pentaho/pentaho-kettle,yshakhau/pentaho-kettle,ivanpogodin/pentaho-kettle,YuryBY/pentaho-kettle,hudak/pentaho-kettle,MikhailHubanau/pentaho-kettle,kurtwalker/pentaho-kettle,mdamour1976/pentaho-kettle,brosander/pentaho-kettle,drndos/pentaho-kettle,akhayrutdinov/pentaho-kettle,roboguy/pentaho-kettle,wseyler/pentaho-kettle,nicoben/pentaho-kettle,stepanovdg/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,emartin-pentaho/pentaho-kettle,bmorrise/pentaho-kettle,flbrino/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,ccaspanello/pentaho-kettle,mbatchelor/pentaho-kettle,ccaspanello/pentaho-kettle,mattyb149/pentaho-kettle,gretchiemoran/pentaho-kettle,Advent51/pentaho-kettle,codek/pentaho-kettle,nantunes/pentaho-kettle,sajeetharan/pentaho-kettle,YuryBY/pentaho-kettle,DFieldFL/pentaho-kettle,pentaho/pentaho-kettle,codek/pentaho-kettle,DFieldFL/pentaho-kettle,denisprotopopov/pentaho-kettle,skofra0/pentaho-kettle,rmansoor/pentaho-kettle,dkincade/pentaho-kettle,jbrant/pentaho-kettle,mbatchelor/pentaho-kettle,e-cuellar/pentaho-kettle,rmansoor/pentaho-kettle,matrix-stone/pentaho-kettle,ddiroma/pentaho-kettle,airy-ict/pentaho-kettle,ivanpogodin/pentaho-kettle,codek/pentaho-kettle,mkambol/pentaho-kettle,tkafalas/pentaho-kettle,HiromuHota/pentaho-kettle,brosander/pentaho-kettle,DFieldFL/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,cjsonger/pentaho-kettle,denisprotopopov/pentaho-kettle,rfellows/pentaho-kettle,ViswesvarSekar/pentaho-kettle,eayoungs/pentaho-kettle,mattyb149/pentaho-kettle,pymjer/pentaho-kettle,pavel-sakun/pentaho-kettle,cjsonger/pentaho-kettle,cjsonger/pentaho-kettle,marcoslarsen/pentaho-kettle,lgrill-pentaho/pentaho-kettle,airy-ict/pentaho-kettle,marcoslarsen/pentaho-kettle,mkambol/pentaho-kettle,akhayrutdinov/pentaho-kettle,EcoleKeine/pentaho-kettle,mdamour1976/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,pentaho/pentaho-kettle,tmcsantos/pentaho-kettle,e-cuellar/pentaho-kettle,yshakhau/pentaho-kettle,zlcnju/kettle,alina-ipatina/pentaho-kettle,lgrill-pentaho/pentaho-kettle,ccaspanello/pentaho-kettle,drndos/pentaho-kettle,Advent51/pentaho-kettle,mbatchelor/pentaho-kettle,denisprotopopov/pentaho-kettle,pavel-sakun/pentaho-kettle,zlcnju/kettle,mattyb149/pentaho-kettle,pentaho/pentaho-kettle,ViswesvarSekar/pentaho-kettle,CapeSepias/pentaho-kettle,ddiroma/pentaho-kettle,pymjer/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,EcoleKeine/pentaho-kettle,DFieldFL/pentaho-kettle,graimundo/pentaho-kettle,mdamour1976/pentaho-kettle,andrei-viaryshka/pentaho-kettle,yshakhau/pentaho-kettle,HiromuHota/pentaho-kettle,stevewillcock/pentaho-kettle,pedrofvteixeira/pentaho-kettle,pminutillo/pentaho-kettle,lgrill-pentaho/pentaho-kettle,SergeyTravin/pentaho-kettle,eayoungs/pentaho-kettle,pminutillo/pentaho-kettle,GauravAshara/pentaho-kettle,MikhailHubanau/pentaho-kettle,skofra0/pentaho-kettle,kurtwalker/pentaho-kettle,HiromuHota/pentaho-kettle,pentaho/pentaho-kettle,skofra0/pentaho-kettle,ma459006574/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,akhayrutdinov/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,stevewillcock/pentaho-kettle,aminmkhan/pentaho-kettle,nicoben/pentaho-kettle,airy-ict/pentaho-kettle,ViswesvarSekar/pentaho-kettle,roboguy/pentaho-kettle,bmorrise/pentaho-kettle,pymjer/pentaho-kettle,jbrant/pentaho-kettle,pminutillo/pentaho-kettle,stepanovdg/pentaho-kettle,matrix-stone/pentaho-kettle,marcoslarsen/pentaho-kettle,ivanpogodin/pentaho-kettle,dkincade/pentaho-kettle,nanata1115/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,CapeSepias/pentaho-kettle,nanata1115/pentaho-kettle,stepanovdg/pentaho-kettle,nantunes/pentaho-kettle,ivanpogodin/pentaho-kettle,zlcnju/kettle,bmorrise/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,stepanovdg/pentaho-kettle,dkincade/pentaho-kettle,tkafalas/pentaho-kettle,matthewtckr/pentaho-kettle,rmansoor/pentaho-kettle,nantunes/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,airy-ict/pentaho-kettle,kurtwalker/pentaho-kettle,pedrofvteixeira/pentaho-kettle,sajeetharan/pentaho-kettle,GauravAshara/pentaho-kettle,gretchiemoran/pentaho-kettle,wseyler/pentaho-kettle,YuryBY/pentaho-kettle,mkambol/pentaho-kettle,aminmkhan/pentaho-kettle,tmcsantos/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,brosander/pentaho-kettle,aminmkhan/pentaho-kettle,gretchiemoran/pentaho-kettle,tkafalas/pentaho-kettle,HiromuHota/pentaho-kettle,roboguy/pentaho-kettle,flbrino/pentaho-kettle,denisprotopopov/pentaho-kettle,nicoben/pentaho-kettle,birdtsai/pentaho-kettle,EcoleKeine/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,ma459006574/pentaho-kettle,EcoleKeine/pentaho-kettle,rfellows/pentaho-kettle,graimundo/pentaho-kettle,zlcnju/kettle,rmansoor/pentaho-kettle,e-cuellar/pentaho-kettle,pavel-sakun/pentaho-kettle,eayoungs/pentaho-kettle,flbrino/pentaho-kettle,rfellows/pentaho-kettle,e-cuellar/pentaho-kettle,stevewillcock/pentaho-kettle,SergeyTravin/pentaho-kettle,hudak/pentaho-kettle,matthewtckr/pentaho-kettle,pymjer/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,ma459006574/pentaho-kettle,kurtwalker/pentaho-kettle,GauravAshara/pentaho-kettle,sajeetharan/pentaho-kettle,drndos/pentaho-kettle,emartin-pentaho/pentaho-kettle,mdamour1976/pentaho-kettle,alina-ipatina/pentaho-kettle,emartin-pentaho/pentaho-kettle,eayoungs/pentaho-kettle,stevewillcock/pentaho-kettle,CapeSepias/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,GauravAshara/pentaho-kettle,mattyb149/pentaho-kettle,nantunes/pentaho-kettle,Advent51/pentaho-kettle,alina-ipatina/pentaho-kettle,matrix-stone/pentaho-kettle,birdtsai/pentaho-kettle,andrei-viaryshka/pentaho-kettle,pminutillo/pentaho-kettle,pavel-sakun/pentaho-kettle,bmorrise/pentaho-kettle,tkafalas/pentaho-kettle,YuryBY/pentaho-kettle,tmcsantos/pentaho-kettle,ViswesvarSekar/pentaho-kettle,mkambol/pentaho-kettle,birdtsai/pentaho-kettle,alina-ipatina/pentaho-kettle,mbatchelor/pentaho-kettle,birdtsai/pentaho-kettle,marcoslarsen/pentaho-kettle,gretchiemoran/pentaho-kettle,codek/pentaho-kettle,hudak/pentaho-kettle,emartin-pentaho/pentaho-kettle
/*************************************************************************************** * Copyright (C) 2007 Samatar All rights reserved. * This software was developed by Samatar and is provided under the terms * of the GNU Lesser General Public License, Version 2.1. You may not use * this file except in compliance with the license. A copy of the license, * is included with the binaries and source code. The Original Code is Samatar. * The Initial Developer is Samatar. * * Software distributed under the GNU Lesser Public License is distributed on an * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * Please refer to the license for the specific language governing your rights * and limitations. ***************************************************************************************/ package org.pentaho.di.job.entries.mssqlbulkload; import static org.pentaho.di.job.entry.validator.AbstractFileValidator.putVariableSpace; import static org.pentaho.di.job.entry.validator.AndValidator.putValidators; import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.andValidator; import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.fileExistsValidator; import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.notBlankValidator; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import org.apache.commons.vfs.FileObject; import org.apache.commons.vfs.provider.local.LocalFile; import org.pentaho.di.cluster.SlaveServer; import org.pentaho.di.core.CheckResultInterface; import org.pentaho.di.core.Const; import org.pentaho.di.core.Result; import org.pentaho.di.core.ResultFile; import org.pentaho.di.core.database.Database; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.exception.KettleDatabaseException; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleFileException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.logging.LogWriter; import org.pentaho.di.core.vfs.KettleVFS; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.job.JobMeta; import org.pentaho.di.job.entry.JobEntryBase; import org.pentaho.di.job.entry.JobEntryInterface; import org.pentaho.di.job.entry.validator.ValidatorContext; import org.pentaho.di.repository.ObjectId; import org.pentaho.di.repository.Repository; import org.pentaho.di.resource.ResourceEntry; import org.pentaho.di.resource.ResourceReference; import org.pentaho.di.resource.ResourceEntry.ResourceType; import org.w3c.dom.Node; /** * This defines a MSSQL Bulk job entry. * * @author Samatar Hassan * @since Jan-2007 */ public class JobEntryMssqlBulkLoad extends JobEntryBase implements Cloneable, JobEntryInterface { private static Class<?> PKG = JobEntryMssqlBulkLoad.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$ private String schemaname; private String tablename; private String filename; private String datafiletype; private String fieldterminator; private String lineterminated; private String codepage; private String specificcodepage; private int startfile; private int endfile; private String orderby; private boolean addfiletoresult; private String formatfilename; private boolean firetriggers; private boolean checkconstraints; private boolean keepnulls; private boolean tablock; private String errorfilename; private boolean adddatetime; private String orderdirection; private int maxerrors; private int batchsize; private int rowsperbatch; private boolean keepidentity; private boolean truncate; private DatabaseMeta connection; public JobEntryMssqlBulkLoad(String n) { super(n, ""); tablename=null; schemaname=null; filename=null; datafiletype="char"; fieldterminator=null; lineterminated=null; codepage="OEM"; specificcodepage=null; checkconstraints=false; keepnulls=false; tablock=false; startfile = 0; endfile= 0; orderby=null; errorfilename=null; adddatetime=false; orderdirection="Asc"; maxerrors=0; batchsize=0; rowsperbatch=0; connection=null; addfiletoresult = false; formatfilename=null; firetriggers=false; keepidentity=false; truncate=false; setID(-1L); } public JobEntryMssqlBulkLoad() { this(""); } public Object clone() { JobEntryMssqlBulkLoad je = (JobEntryMssqlBulkLoad) super.clone(); return je; } public String getXML() { StringBuffer retval = new StringBuffer(200); retval.append(super.getXML()); retval.append(" ").append(XMLHandler.addTagValue("schemaname", schemaname)); retval.append(" ").append(XMLHandler.addTagValue("tablename", tablename)); retval.append(" ").append(XMLHandler.addTagValue("filename", filename)); retval.append(" ").append(XMLHandler.addTagValue("datafiletype", datafiletype)); retval.append(" ").append(XMLHandler.addTagValue("fieldterminator", fieldterminator)); retval.append(" ").append(XMLHandler.addTagValue("lineterminated", lineterminated)); retval.append(" ").append(XMLHandler.addTagValue("codepage", codepage)); retval.append(" ").append(XMLHandler.addTagValue("specificcodepage", specificcodepage)); retval.append(" ").append(XMLHandler.addTagValue("formatfilename", formatfilename)); retval.append(" ").append(XMLHandler.addTagValue("firetriggers", firetriggers)); retval.append(" ").append(XMLHandler.addTagValue("checkconstraints", checkconstraints)); retval.append(" ").append(XMLHandler.addTagValue("keepnulls", keepnulls)); retval.append(" ").append(XMLHandler.addTagValue("keepidentity", keepidentity)); retval.append(" ").append(XMLHandler.addTagValue("tablock", tablock)); retval.append(" ").append(XMLHandler.addTagValue("startfile", startfile)); retval.append(" ").append(XMLHandler.addTagValue("endfile", endfile)); retval.append(" ").append(XMLHandler.addTagValue("orderby", orderby)); retval.append(" ").append(XMLHandler.addTagValue("orderdirection", orderdirection)); retval.append(" ").append(XMLHandler.addTagValue("maxerrors", maxerrors)); retval.append(" ").append(XMLHandler.addTagValue("batchsize", batchsize)); retval.append(" ").append(XMLHandler.addTagValue("rowsperbatch", rowsperbatch)); retval.append(" ").append(XMLHandler.addTagValue("errorfilename", errorfilename)); retval.append(" ").append(XMLHandler.addTagValue("adddatetime", adddatetime)); retval.append(" ").append(XMLHandler.addTagValue("addfiletoresult", addfiletoresult)); retval.append(" ").append(XMLHandler.addTagValue("truncate", truncate)); retval.append(" ").append(XMLHandler.addTagValue("connection", connection==null?null:connection.getName())); return retval.toString(); } public void loadXML(Node entrynode, List<DatabaseMeta> databases, List<SlaveServer> slaveServers, Repository rep) throws KettleXMLException { try { super.loadXML(entrynode, databases, slaveServers); schemaname = XMLHandler.getTagValue(entrynode, "schemaname"); tablename = XMLHandler.getTagValue(entrynode, "tablename"); filename = XMLHandler.getTagValue(entrynode, "filename"); datafiletype = XMLHandler.getTagValue(entrynode, "datafiletype"); fieldterminator = XMLHandler.getTagValue(entrynode, "fieldterminator"); lineterminated = XMLHandler.getTagValue(entrynode, "lineterminated"); codepage = XMLHandler.getTagValue(entrynode, "codepage"); specificcodepage = XMLHandler.getTagValue(entrynode, "specificcodepage"); formatfilename = XMLHandler.getTagValue(entrynode, "formatfilename"); firetriggers = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "firetriggers")); checkconstraints = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "checkconstraints")); keepnulls = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "keepnulls")); keepidentity = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "keepidentity")); tablock = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "tablock")); startfile = Const.toInt(XMLHandler.getTagValue(entrynode, "startfile"), 0); endfile = Const.toInt(XMLHandler.getTagValue(entrynode, "endfile"), 0); orderby = XMLHandler.getTagValue(entrynode, "orderby"); orderdirection = XMLHandler.getTagValue(entrynode, "orderdirection"); errorfilename = XMLHandler.getTagValue(entrynode, "errorfilename"); maxerrors = Const.toInt(XMLHandler.getTagValue(entrynode, "maxerrors"), 0); batchsize = Const.toInt(XMLHandler.getTagValue(entrynode, "batchsize"), 0); rowsperbatch = Const.toInt(XMLHandler.getTagValue(entrynode, "rowsperbatch"), 0); adddatetime = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "adddatetime")); String dbname = XMLHandler.getTagValue(entrynode, "connection"); addfiletoresult = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "addfiletoresult")); truncate = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "truncate")); connection = DatabaseMeta.findDatabase(databases, dbname); } catch(KettleException e) { throw new KettleXMLException("Unable to load job entry of type 'MSsql bulk load' from XML node", e); } } public void loadRep(Repository rep, ObjectId id_jobentry, List<DatabaseMeta> databases, List<SlaveServer> slaveServers) throws KettleException { try { schemaname = rep.getJobEntryAttributeString(id_jobentry, "schemaname"); tablename = rep.getJobEntryAttributeString(id_jobentry, "tablename"); filename = rep.getJobEntryAttributeString(id_jobentry, "filename"); datafiletype = rep.getJobEntryAttributeString(id_jobentry, "datafiletype"); fieldterminator = rep.getJobEntryAttributeString(id_jobentry, "fieldterminator"); lineterminated = rep.getJobEntryAttributeString(id_jobentry, "lineterminated"); codepage = rep.getJobEntryAttributeString(id_jobentry, "codepage"); specificcodepage = rep.getJobEntryAttributeString(id_jobentry, "specificcodepage"); formatfilename = rep.getJobEntryAttributeString(id_jobentry, "formatfilename"); firetriggers=rep.getJobEntryAttributeBoolean(id_jobentry, "firetriggers"); checkconstraints=rep.getJobEntryAttributeBoolean(id_jobentry, "checkconstraints"); keepnulls=rep.getJobEntryAttributeBoolean(id_jobentry, "keepnulls"); keepidentity=rep.getJobEntryAttributeBoolean(id_jobentry, "keepidentity"); tablock=rep.getJobEntryAttributeBoolean(id_jobentry, "tablock"); startfile = (int)rep.getJobEntryAttributeInteger(id_jobentry, "startfile"); endfile = (int)rep.getJobEntryAttributeInteger(id_jobentry, "endfile"); orderby = rep.getJobEntryAttributeString(id_jobentry, "orderby"); orderdirection = rep.getJobEntryAttributeString(id_jobentry, "orderdirection"); errorfilename = rep.getJobEntryAttributeString(id_jobentry, "errorfilename"); maxerrors = (int)rep.getJobEntryAttributeInteger(id_jobentry, "maxerrors"); batchsize = (int)rep.getJobEntryAttributeInteger(id_jobentry, "batchsize"); rowsperbatch = (int)rep.getJobEntryAttributeInteger(id_jobentry, "rowsperbatch"); adddatetime=rep.getJobEntryAttributeBoolean(id_jobentry, "adddatetime"); addfiletoresult=rep.getJobEntryAttributeBoolean(id_jobentry, "addfiletoresult"); truncate=rep.getJobEntryAttributeBoolean(id_jobentry, "truncate"); connection = rep.loadDatabaseMetaFromJobEntryAttribute(id_jobentry, "connection", "id_database", databases); } catch(KettleDatabaseException dbe) { throw new KettleException("Unable to load job entry of type 'MSsql bulk load' from the repository for id_jobentry="+id_jobentry, dbe); } } public void saveRep(Repository rep, ObjectId id_job) throws KettleException { try { rep.saveJobEntryAttribute(id_job, getObjectId(), "schemaname", schemaname); rep.saveJobEntryAttribute(id_job, getObjectId(), "tablename", tablename); rep.saveJobEntryAttribute(id_job, getObjectId(), "filename", filename); rep.saveJobEntryAttribute(id_job, getObjectId(), "datafiletype", datafiletype); rep.saveJobEntryAttribute(id_job, getObjectId(), "fieldterminator", fieldterminator); rep.saveJobEntryAttribute(id_job, getObjectId(), "lineterminated", lineterminated); rep.saveJobEntryAttribute(id_job, getObjectId(), "codepage", codepage); rep.saveJobEntryAttribute(id_job, getObjectId(), "specificcodepage", specificcodepage); rep.saveJobEntryAttribute(id_job, getObjectId(), "formatfilename", formatfilename); rep.saveJobEntryAttribute(id_job, getObjectId(), "firetriggers", firetriggers); rep.saveJobEntryAttribute(id_job, getObjectId(), "checkconstraints", checkconstraints); rep.saveJobEntryAttribute(id_job, getObjectId(), "keepnulls", keepnulls); rep.saveJobEntryAttribute(id_job, getObjectId(), "keepidentity", keepidentity); rep.saveJobEntryAttribute(id_job, getObjectId(), "tablock", tablock); rep.saveJobEntryAttribute(id_job, getObjectId(), "startfile", startfile); rep.saveJobEntryAttribute(id_job, getObjectId(), "endfile", endfile); rep.saveJobEntryAttribute(id_job, getObjectId(), "orderby", orderby); rep.saveJobEntryAttribute(id_job, getObjectId(), "orderdirection", orderdirection); rep.saveJobEntryAttribute(id_job, getObjectId(), "errorfilename", errorfilename); rep.saveJobEntryAttribute(id_job, getObjectId(), "maxerrors", maxerrors); rep.saveJobEntryAttribute(id_job, getObjectId(), "batchsize", batchsize); rep.saveJobEntryAttribute(id_job, getObjectId(), "rowsperbatch", rowsperbatch); rep.saveJobEntryAttribute(id_job, getObjectId(), "adddatetime", adddatetime); rep.saveJobEntryAttribute(id_job, getObjectId(), "addfiletoresult", addfiletoresult); rep.saveJobEntryAttribute(id_job, getObjectId(), "truncate", truncate); rep.saveDatabaseMetaJobEntryAttribute(id_job, getObjectId(), "connection", "id_database", connection); } catch(KettleDatabaseException dbe) { throw new KettleException("Unable to load job entry of type 'MSsql Bulk Load' to the repository for id_job="+id_job, dbe); } } public void setTablename(String tablename) { this.tablename = tablename; } public void setSchemaname(String schemaname) { this.schemaname = schemaname; } public String getSchemaname() { return schemaname; } public String getTablename() { return tablename; } public void setMaxErrors(int maxerrors) { this.maxerrors=maxerrors; } public int getMaxErrors() { return maxerrors; } public int getBatchSize() { return batchsize; } public void setBatchSize(int batchsize) { this.batchsize=batchsize; } public int getRowsPerBatch() { return rowsperbatch; } public void setRowsPerBatch(int rowsperbatch) { this.rowsperbatch=rowsperbatch; } public void setDatabase(DatabaseMeta database) { this.connection = database; } public DatabaseMeta getDatabase() { return connection; } public boolean evaluates() { return true; } public boolean isUnconditional() { return false; } public Result execute(Result previousResult, int nr) { String TakeFirstNbrLines=""; String LineTerminatedby=""; String FieldTerminatedby=""; boolean useFieldSeparator=false; String UseCodepage=""; String ErrorfileName=""; LogWriter log = LogWriter.getInstance(); Result result = previousResult; result.setResult(false); String vfsFilename = environmentSubstitute(filename); FileObject fileObject = null; // Let's check the filename ... if (!Const.isEmpty(vfsFilename)) { try { // User has specified a file, We can continue ... // // This is running over VFS but we need a normal file. // As such, we're going to verify that it's a local file... // We're also going to convert VFS FileObject to File // fileObject = KettleVFS.getFileObject(vfsFilename, this); if (!(fileObject instanceof LocalFile)) { // MSSQL BUKL INSERT can only use local files, so that's what we limit ourselves to. // throw new KettleException(BaseMessages.getString(PKG, "JobMssqlBulkLoad.Error.OnlyLocalFileSupported",vfsFilename)); } // Convert it to a regular platform specific file name // String realFilename = KettleVFS.getFilename(fileObject); // Here we go... back to the regular scheduled program... // File file = new File(realFilename); if (file.exists() && file.canRead()) { // User has specified an existing file, We can continue ... if (log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "JobMssqlBulkLoad.FileExists.Label",realFilename)); if (connection!=null) { // User has specified a connection, We can continue ... Database db = new Database(this, connection); if(db.getDatabaseMeta().getDatabaseType() != DatabaseMeta.TYPE_DATABASE_MSSQL) { logError(BaseMessages.getString(PKG, "JobMssqlBulkLoad.Error.DbNotMSSQL",connection.getDatabaseName())); return result; } db.shareVariablesWith(this); try { db.connect(); // Get schemaname String realSchemaname = environmentSubstitute(schemaname); // Get tablename String realTablename = environmentSubstitute(tablename); if (db.checkTableExists(realTablename)) { // The table existe, We can continue ... if(log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "JobMssqlBulkLoad.TableExists.Label",realTablename)); // Add schemaname (Most the time Schemaname.Tablename) if (schemaname !=null) realTablename= realSchemaname + "." + realTablename; // FIELDTERMINATOR String Fieldterminator=getRealFieldTerminator(); if(Const.isEmpty(Fieldterminator) && (datafiletype.equals("char")||datafiletype.equals("widechar"))) { logError(BaseMessages.getString(PKG, "JobMssqlBulkLoad.Error.FieldTerminatorMissing")); return result; } else { if(datafiletype.equals("char")||datafiletype.equals("widechar")) { useFieldSeparator=true; FieldTerminatedby="FIELDTERMINATOR='"+Fieldterminator+"'"; } } // Check Specific Code page if(codepage.equals("Specific")) { if(specificcodepage.length()<0) { logError(BaseMessages.getString(PKG, "JobMssqlBulkLoad.Error.SpecificCodePageMissing")); return result; }else UseCodepage="CODEPAGE = '" + specificcodepage + "'"; }else { UseCodepage="CODEPAGE = '" + codepage + "'"; } // Check Error file if(errorfilename!=null) { File errorfile = new File(errorfilename); if(errorfile.exists() && !adddatetime) { // The error file is created when the command is executed. An error occurs if the file already exists. logError(BaseMessages.getString(PKG, "JobMssqlBulkLoad.Error.ErrorFileExists")); return result; } if(adddatetime) { // Add date time to filename... SimpleDateFormat daf = new SimpleDateFormat(); Date now = new Date(); daf.applyPattern("yyyMMdd_HHmmss"); String d = daf.format(now); ErrorfileName="ERRORFILE ='"+ errorfilename+"_"+d +"'"; }else ErrorfileName="ERRORFILE ='"+ errorfilename+"'"; } // ROWTERMINATOR String Rowterminator=getRealLineterminated(); if(!Const.isEmpty(Rowterminator)) LineTerminatedby="ROWTERMINATOR='"+Rowterminator+"'"; // Start file at if(startfile>0) TakeFirstNbrLines="FIRSTROW="+startfile; // End file at if(endfile>0) TakeFirstNbrLines="LASTROW="+endfile; // Truncate table? String SQLBULKLOAD=""; if(truncate) SQLBULKLOAD="TRUNCATE TABLE " + realTablename + ";"; // Build BULK Command SQLBULKLOAD=SQLBULKLOAD+"BULK INSERT " + realTablename + " FROM " + "'"+realFilename.replace('\\', '/')+"'" ; SQLBULKLOAD=SQLBULKLOAD+" WITH (" ; if(useFieldSeparator) SQLBULKLOAD=SQLBULKLOAD + FieldTerminatedby; else SQLBULKLOAD=SQLBULKLOAD + "DATAFILETYPE ='"+datafiletype+"'"; if(LineTerminatedby.length()>0) SQLBULKLOAD=SQLBULKLOAD+","+LineTerminatedby; if(TakeFirstNbrLines.length()>0) SQLBULKLOAD=SQLBULKLOAD+","+TakeFirstNbrLines; if(UseCodepage.length()>0) SQLBULKLOAD=SQLBULKLOAD+"," + UseCodepage; if(formatfilename!=null) SQLBULKLOAD=SQLBULKLOAD+", FORMATFILE='" + formatfilename + "'"; if(firetriggers) SQLBULKLOAD=SQLBULKLOAD + ",FIRE_TRIGGERS"; if(keepnulls) SQLBULKLOAD=SQLBULKLOAD + ",KEEPNULLS"; if(keepidentity) SQLBULKLOAD=SQLBULKLOAD + ",KEEPIDENTITY"; if(checkconstraints) SQLBULKLOAD=SQLBULKLOAD + ",CHECK_CONSTRAINTS"; if(tablock) SQLBULKLOAD=SQLBULKLOAD + ",TABLOCK"; if(orderby!=null) SQLBULKLOAD=SQLBULKLOAD + ",ORDER ( " + orderby + " " +orderdirection + ")"; if(ErrorfileName.length()>0) SQLBULKLOAD=SQLBULKLOAD + ", " + ErrorfileName; if(maxerrors>0) SQLBULKLOAD=SQLBULKLOAD + ", MAXERRORS="+ maxerrors; if(batchsize>0) SQLBULKLOAD=SQLBULKLOAD + ", BATCHSIZE="+ batchsize; if(rowsperbatch>0) SQLBULKLOAD=SQLBULKLOAD + ", ROWS_PER_BATCH="+ rowsperbatch; // End of Bulk command SQLBULKLOAD=SQLBULKLOAD+")"; try { // Run the SQL db.execStatements(SQLBULKLOAD); // Everything is OK...we can disconnect now db.disconnect(); if (isAddFileToResult()) { // Add filename to output files ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, KettleVFS.getFileObject(realFilename, this), parentJob.getJobname(), toString()); result.getResultFiles().put(resultFile.getFile().toString(), resultFile); } result.setResult(true); } catch(KettleDatabaseException je) { result.setNrErrors(1); logError("An error occurred executing this job entry : "+je.getMessage(), je); } catch (KettleFileException e) { logError("An error occurred executing this job entry : " + e.getMessage(), e); result.setNrErrors(1); } finally { if(db!=null) { db.disconnect(); db=null; } } } else { // Of course, the table should have been created already before the bulk load operation db.disconnect(); result.setNrErrors(1); if(log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "JobMssqlBulkLoad.Error.TableNotExists",realTablename)); } } catch(KettleDatabaseException dbe) { db.disconnect(); result.setNrErrors(1); logError("An error occurred executing this entry: "+dbe.getMessage()); } } else { // No database connection is defined result.setNrErrors(1); logError( BaseMessages.getString(PKG, "JobMssqlBulkLoad.Nodatabase.Label")); } } else { // the file doesn't exist result.setNrErrors(1); logError(BaseMessages.getString(PKG, "JobMssqlBulkLoad.Error.FileNotExists",realFilename)); } } catch(Exception e) { // An unexpected error occurred result.setNrErrors(1); logError(BaseMessages.getString(PKG, "JobMssqlBulkLoad.UnexpectedError.Label"), e); }finally{ try{ if(fileObject!=null) fileObject.close(); }catch (Exception e){} } } else { // No file was specified result.setNrErrors(1); logError(BaseMessages.getString(PKG, "JobMssqlBulkLoad.Nofilename.Label")); } return result; } public DatabaseMeta[] getUsedDatabaseConnections() { return new DatabaseMeta[] { connection, }; } public void setFilename(String filename) { this.filename = filename; } public String getFilename() { return filename; } public void setFieldTerminator(String fieldterminator) { this.fieldterminator = fieldterminator; } public void setLineterminated(String lineterminated) { this.lineterminated = lineterminated; } public void setCodePage(String codepage) { this.codepage = codepage; } public String getCodePage() { return codepage; } public void setSpecificCodePage(String specificcodepage) { this.specificcodepage =specificcodepage; } public String getSpecificCodePage() { return specificcodepage; } public void setFormatFilename(String formatfilename) { this.formatfilename =formatfilename; } public String getFormatFilename() { return formatfilename; } public String getFieldTerminator() { return fieldterminator; } public String getLineterminated() { return lineterminated; } public String getDataFileType() { return datafiletype; } public void setDataFileType(String datafiletype) { this.datafiletype = datafiletype; } public String getRealLineterminated() { return environmentSubstitute(getLineterminated()); } public String getRealFieldTerminator() { return environmentSubstitute(getFieldTerminator()); } public void setStartFile(int startfile) { this.startfile = startfile; } public int getStartFile() { return startfile; } public void setEndFile(int endfile) { this.endfile = endfile; } public int getEndFile() { return endfile; } public void setOrderBy(String orderby) { this.orderby = orderby; } public String getOrderBy() { return orderby; } public String getOrderDirection() { return orderdirection; } public void setOrderDirection(String orderdirection) { this.orderdirection = orderdirection; } public void setErrorFilename(String errorfilename) { this.errorfilename = errorfilename; } public String getErrorFilename() { return errorfilename; } public String getRealOrderBy() { return environmentSubstitute(getOrderBy()); } public void setAddFileToResult(boolean addfiletoresultin) { this.addfiletoresult = addfiletoresultin; } public boolean isAddFileToResult() { return addfiletoresult; } public void setTruncate(boolean truncate) { this.truncate = truncate; } public boolean isTruncate() { return truncate; } public void setAddDatetime(boolean adddatetime) { this.adddatetime = adddatetime; } public boolean isAddDatetime() { return adddatetime; } public void setFireTriggers(boolean firetriggers) { this.firetriggers= firetriggers; } public boolean isFireTriggers() { return firetriggers; } public void setCheckConstraints(boolean checkconstraints) { this.checkconstraints= checkconstraints; } public boolean isCheckConstraints() { return checkconstraints; } public void setKeepNulls(boolean keepnulls) { this.keepnulls= keepnulls; } public boolean isKeepNulls() { return keepnulls; } public void setKeepIdentity(boolean keepidentity) { this.keepidentity= keepidentity; } public boolean isKeepIdentity() { return keepidentity; } public void setTablock(boolean tablock) { this.tablock= tablock; } public boolean isTablock() { return tablock; } public List<ResourceReference> getResourceDependencies(JobMeta jobMeta) { List<ResourceReference> references = super.getResourceDependencies(jobMeta); ResourceReference reference = null; if (connection != null) { reference = new ResourceReference(this); references.add(reference); reference.getEntries().add( new ResourceEntry(connection.getHostname(), ResourceType.SERVER)); reference.getEntries().add( new ResourceEntry(connection.getDatabaseName(), ResourceType.DATABASENAME)); } if ( filename != null) { String realFilename = getRealFilename(); if (reference == null) { reference = new ResourceReference(this); references.add(reference); } reference.getEntries().add( new ResourceEntry(realFilename, ResourceType.FILE)); } return references; } @Override public void check(List<CheckResultInterface> remarks, JobMeta jobMeta) { ValidatorContext ctx = new ValidatorContext(); putVariableSpace(ctx, getVariables()); putValidators(ctx, notBlankValidator(), fileExistsValidator()); andValidator().validate(this, "filename", remarks, ctx);//$NON-NLS-1$ andValidator().validate(this, "tablename", remarks, putValidators(notBlankValidator())); //$NON-NLS-1$ } }
src/org/pentaho/di/job/entries/mssqlbulkload/JobEntryMssqlBulkLoad.java
/*************************************************************************************** * Copyright (C) 2007 Samatar All rights reserved. * This software was developed by Samatar and is provided under the terms * of the GNU Lesser General Public License, Version 2.1. You may not use * this file except in compliance with the license. A copy of the license, * is included with the binaries and source code. The Original Code is Samatar. * The Initial Developer is Samatar. * * Software distributed under the GNU Lesser Public License is distributed on an * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * Please refer to the license for the specific language governing your rights * and limitations. ***************************************************************************************/ package org.pentaho.di.job.entries.mssqlbulkload; import static org.pentaho.di.job.entry.validator.AbstractFileValidator.putVariableSpace; import static org.pentaho.di.job.entry.validator.AndValidator.putValidators; import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.andValidator; import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.fileExistsValidator; import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.notBlankValidator; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import org.apache.commons.vfs.FileObject; import org.apache.commons.vfs.provider.local.LocalFile; import org.pentaho.di.cluster.SlaveServer; import org.pentaho.di.core.CheckResultInterface; import org.pentaho.di.core.Const; import org.pentaho.di.core.Result; import org.pentaho.di.core.ResultFile; import org.pentaho.di.core.database.Database; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.exception.KettleDatabaseException; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleFileException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.logging.LogWriter; import org.pentaho.di.core.vfs.KettleVFS; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.job.JobMeta; import org.pentaho.di.job.entry.JobEntryBase; import org.pentaho.di.job.entry.JobEntryInterface; import org.pentaho.di.job.entry.validator.ValidatorContext; import org.pentaho.di.repository.ObjectId; import org.pentaho.di.repository.Repository; import org.pentaho.di.resource.ResourceEntry; import org.pentaho.di.resource.ResourceReference; import org.pentaho.di.resource.ResourceEntry.ResourceType; import org.w3c.dom.Node; /** * This defines a MSSQL Bulk job entry. * * @author Samatar Hassan * @since Jan-2007 */ public class JobEntryMssqlBulkLoad extends JobEntryBase implements Cloneable, JobEntryInterface { private static Class<?> PKG = JobEntryMssqlBulkLoad.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$ private String schemaname; private String tablename; private String filename; private String datafiletype; private String fieldterminator; private String lineterminated; private String codepage; private String specificcodepage; private int startfile; private int endfile; private String orderby; private boolean addfiletoresult; private String formatfilename; private boolean firetriggers; private boolean checkconstraints; private boolean keepnulls; private boolean tablock; private String errorfilename; private boolean adddatetime; private String orderdirection; private int maxerrors; private int batchsize; private int rowsperbatch; private boolean keepidentity; private boolean truncate; private DatabaseMeta connection; public JobEntryMssqlBulkLoad(String n) { super(n, ""); tablename=null; schemaname=null; filename=null; datafiletype="char"; fieldterminator=null; lineterminated=null; codepage="OEM"; specificcodepage=null; checkconstraints=false; keepnulls=false; tablock=false; startfile = 0; endfile= 0; orderby=null; errorfilename=null; adddatetime=false; orderdirection="Asc"; maxerrors=0; batchsize=0; rowsperbatch=0; connection=null; addfiletoresult = false; formatfilename=null; firetriggers=false; keepidentity=false; truncate=false; setID(-1L); } public JobEntryMssqlBulkLoad() { this(""); } public Object clone() { JobEntryMssqlBulkLoad je = (JobEntryMssqlBulkLoad) super.clone(); return je; } public String getXML() { StringBuffer retval = new StringBuffer(200); retval.append(super.getXML()); retval.append(" ").append(XMLHandler.addTagValue("schemaname", schemaname)); retval.append(" ").append(XMLHandler.addTagValue("tablename", tablename)); retval.append(" ").append(XMLHandler.addTagValue("filename", filename)); retval.append(" ").append(XMLHandler.addTagValue("datafiletype", datafiletype)); retval.append(" ").append(XMLHandler.addTagValue("fieldterminator", fieldterminator)); retval.append(" ").append(XMLHandler.addTagValue("lineterminated", lineterminated)); retval.append(" ").append(XMLHandler.addTagValue("codepage", codepage)); retval.append(" ").append(XMLHandler.addTagValue("specificcodepage", specificcodepage)); retval.append(" ").append(XMLHandler.addTagValue("formatfilename", formatfilename)); retval.append(" ").append(XMLHandler.addTagValue("firetriggers", firetriggers)); retval.append(" ").append(XMLHandler.addTagValue("checkconstraints", checkconstraints)); retval.append(" ").append(XMLHandler.addTagValue("keepnulls", keepnulls)); retval.append(" ").append(XMLHandler.addTagValue("keepidentity", keepidentity)); retval.append(" ").append(XMLHandler.addTagValue("tablock", tablock)); retval.append(" ").append(XMLHandler.addTagValue("startfile", startfile)); retval.append(" ").append(XMLHandler.addTagValue("endfile", endfile)); retval.append(" ").append(XMLHandler.addTagValue("orderby", orderby)); retval.append(" ").append(XMLHandler.addTagValue("orderdirection", orderdirection)); retval.append(" ").append(XMLHandler.addTagValue("maxerrors", maxerrors)); retval.append(" ").append(XMLHandler.addTagValue("batchsize", batchsize)); retval.append(" ").append(XMLHandler.addTagValue("rowsperbatch", rowsperbatch)); retval.append(" ").append(XMLHandler.addTagValue("errorfilename", errorfilename)); retval.append(" ").append(XMLHandler.addTagValue("adddatetime", adddatetime)); retval.append(" ").append(XMLHandler.addTagValue("addfiletoresult", addfiletoresult)); retval.append(" ").append(XMLHandler.addTagValue("truncate", truncate)); retval.append(" ").append(XMLHandler.addTagValue("connection", connection==null?null:connection.getName())); return retval.toString(); } public void loadXML(Node entrynode, List<DatabaseMeta> databases, List<SlaveServer> slaveServers, Repository rep) throws KettleXMLException { try { super.loadXML(entrynode, databases, slaveServers); schemaname = XMLHandler.getTagValue(entrynode, "schemaname"); tablename = XMLHandler.getTagValue(entrynode, "tablename"); filename = XMLHandler.getTagValue(entrynode, "filename"); datafiletype = XMLHandler.getTagValue(entrynode, "datafiletype"); fieldterminator = XMLHandler.getTagValue(entrynode, "fieldterminator"); lineterminated = XMLHandler.getTagValue(entrynode, "lineterminated"); codepage = XMLHandler.getTagValue(entrynode, "codepage"); specificcodepage = XMLHandler.getTagValue(entrynode, "specificcodepage"); formatfilename = XMLHandler.getTagValue(entrynode, "formatfilename"); firetriggers = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "firetriggers")); checkconstraints = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "checkconstraints")); keepnulls = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "keepnulls")); keepidentity = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "keepidentity")); tablock = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "tablock")); startfile = Const.toInt(XMLHandler.getTagValue(entrynode, "startfile"), 0); endfile = Const.toInt(XMLHandler.getTagValue(entrynode, "endfile"), 0); orderby = XMLHandler.getTagValue(entrynode, "orderby"); orderdirection = XMLHandler.getTagValue(entrynode, "orderdirection"); errorfilename = XMLHandler.getTagValue(entrynode, "errorfilename"); maxerrors = Const.toInt(XMLHandler.getTagValue(entrynode, "maxerrors"), 0); batchsize = Const.toInt(XMLHandler.getTagValue(entrynode, "batchsize"), 0); rowsperbatch = Const.toInt(XMLHandler.getTagValue(entrynode, "rowsperbatch"), 0); adddatetime = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "adddatetime")); String dbname = XMLHandler.getTagValue(entrynode, "connection"); addfiletoresult = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "addfiletoresult")); truncate = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "truncate")); connection = DatabaseMeta.findDatabase(databases, dbname); } catch(KettleException e) { throw new KettleXMLException("Unable to load job entry of type 'MSsql bulk load' from XML node", e); } } public void loadRep(Repository rep, ObjectId id_jobentry, List<DatabaseMeta> databases, List<SlaveServer> slaveServers) throws KettleException { try { schemaname = rep.getJobEntryAttributeString(id_jobentry, "schemaname"); tablename = rep.getJobEntryAttributeString(id_jobentry, "tablename"); filename = rep.getJobEntryAttributeString(id_jobentry, "filename"); datafiletype = rep.getJobEntryAttributeString(id_jobentry, "datafiletype"); fieldterminator = rep.getJobEntryAttributeString(id_jobentry, "fieldterminator"); lineterminated = rep.getJobEntryAttributeString(id_jobentry, "lineterminated"); codepage = rep.getJobEntryAttributeString(id_jobentry, "codepage"); specificcodepage = rep.getJobEntryAttributeString(id_jobentry, "specificcodepage"); formatfilename = rep.getJobEntryAttributeString(id_jobentry, "formatfilename"); firetriggers=rep.getJobEntryAttributeBoolean(id_jobentry, "firetriggers"); checkconstraints=rep.getJobEntryAttributeBoolean(id_jobentry, "checkconstraints"); keepnulls=rep.getJobEntryAttributeBoolean(id_jobentry, "keepnulls"); keepidentity=rep.getJobEntryAttributeBoolean(id_jobentry, "keepidentity"); tablock=rep.getJobEntryAttributeBoolean(id_jobentry, "tablock"); startfile = (int)rep.getJobEntryAttributeInteger(id_jobentry, "startfile"); endfile = (int)rep.getJobEntryAttributeInteger(id_jobentry, "endfile"); orderby = rep.getJobEntryAttributeString(id_jobentry, "orderby"); orderdirection = rep.getJobEntryAttributeString(id_jobentry, "orderdirection"); errorfilename = rep.getJobEntryAttributeString(id_jobentry, "errorfilename"); maxerrors = (int)rep.getJobEntryAttributeInteger(id_jobentry, "maxerrors"); batchsize = (int)rep.getJobEntryAttributeInteger(id_jobentry, "batchsize"); rowsperbatch = (int)rep.getJobEntryAttributeInteger(id_jobentry, "rowsperbatch"); adddatetime=rep.getJobEntryAttributeBoolean(id_jobentry, "adddatetime"); addfiletoresult=rep.getJobEntryAttributeBoolean(id_jobentry, "addfiletoresult"); truncate=rep.getJobEntryAttributeBoolean(id_jobentry, "truncate"); connection = rep.loadDatabaseMetaFromJobEntryAttribute(id_jobentry, "connection", "id_database", databases); } catch(KettleDatabaseException dbe) { throw new KettleException("Unable to load job entry of type 'MSsql bulk load' from the repository for id_jobentry="+id_jobentry, dbe); } } public void saveRep(Repository rep, ObjectId id_job) throws KettleException { try { rep.saveJobEntryAttribute(id_job, getObjectId(), "schemaname", schemaname); rep.saveJobEntryAttribute(id_job, getObjectId(), "tablename", tablename); rep.saveJobEntryAttribute(id_job, getObjectId(), "filename", filename); rep.saveJobEntryAttribute(id_job, getObjectId(), "datafiletype", datafiletype); rep.saveJobEntryAttribute(id_job, getObjectId(), "fieldterminator", fieldterminator); rep.saveJobEntryAttribute(id_job, getObjectId(), "lineterminated", lineterminated); rep.saveJobEntryAttribute(id_job, getObjectId(), "codepage", codepage); rep.saveJobEntryAttribute(id_job, getObjectId(), "specificcodepage", specificcodepage); rep.saveJobEntryAttribute(id_job, getObjectId(), "formatfilename", formatfilename); rep.saveJobEntryAttribute(id_job, getObjectId(), "firetriggers", firetriggers); rep.saveJobEntryAttribute(id_job, getObjectId(), "checkconstraints", checkconstraints); rep.saveJobEntryAttribute(id_job, getObjectId(), "keepnulls", keepnulls); rep.saveJobEntryAttribute(id_job, getObjectId(), "keepidentity", keepidentity); rep.saveJobEntryAttribute(id_job, getObjectId(), "tablock", tablock); rep.saveJobEntryAttribute(id_job, getObjectId(), "startfile", startfile); rep.saveJobEntryAttribute(id_job, getObjectId(), "endfile", endfile); rep.saveJobEntryAttribute(id_job, getObjectId(), "orderby", orderby); rep.saveJobEntryAttribute(id_job, getObjectId(), "orderdirection", orderdirection); rep.saveJobEntryAttribute(id_job, getObjectId(), "errorfilename", errorfilename); rep.saveJobEntryAttribute(id_job, getObjectId(), "maxerrors", maxerrors); rep.saveJobEntryAttribute(id_job, getObjectId(), "batchsize", batchsize); rep.saveJobEntryAttribute(id_job, getObjectId(), "rowsperbatch", rowsperbatch); rep.saveJobEntryAttribute(id_job, getObjectId(), "adddatetime", adddatetime); rep.saveJobEntryAttribute(id_job, getObjectId(), "addfiletoresult", addfiletoresult); rep.saveJobEntryAttribute(id_job, getObjectId(), "truncate", truncate); rep.saveDatabaseMetaJobEntryAttribute(id_job, getObjectId(), "connection", "id_database", connection); } catch(KettleDatabaseException dbe) { throw new KettleException("Unable to load job entry of type 'MSsql Bulk Load' to the repository for id_job="+id_job, dbe); } } public void setTablename(String tablename) { this.tablename = tablename; } public void setSchemaname(String schemaname) { this.schemaname = schemaname; } public String getSchemaname() { return schemaname; } public String getTablename() { return tablename; } public void setMaxErrors(int maxerrors) { this.maxerrors=maxerrors; } public int getMaxErrors() { return maxerrors; } public int getBatchSize() { return batchsize; } public void setBatchSize(int batchsize) { this.batchsize=batchsize; } public int getRowsPerBatch() { return rowsperbatch; } public void setRowsPerBatch(int rowsperbatch) { this.rowsperbatch=rowsperbatch; } public void setDatabase(DatabaseMeta database) { this.connection = database; } public DatabaseMeta getDatabase() { return connection; } public boolean evaluates() { return true; } public boolean isUnconditional() { return false; } public Result execute(Result previousResult, int nr) { String TakeFirstNbrLines=""; String LineTerminatedby=""; String FieldTerminatedby=""; boolean useFieldSeparator=false; String UseCodepage=""; String ErrorfileName=""; LogWriter log = LogWriter.getInstance(); Result result = previousResult; result.setResult(false); String vfsFilename = environmentSubstitute(filename); FileObject fileObject = null; // Let's check the filename ... if (!Const.isEmpty(vfsFilename)) { try { // User has specified a file, We can continue ... // // This is running over VFS but we need a normal file. // As such, we're going to verify that it's a local file... // We're also going to convert VFS FileObject to File // fileObject = KettleVFS.getFileObject(vfsFilename, this); if (!(fileObject instanceof LocalFile)) { // MSSQL BUKL INSERT can only use local files, so that's what we limit ourselves to. // throw new KettleException(BaseMessages.getString(PKG, "JobMssqlBulkLoad.Error.OnlyLocalFileSupported",vfsFilename)); } // Convert it to a regular platform specific file name // String realFilename = KettleVFS.getFilename(fileObject); // Here we go... back to the regular scheduled program... // File file = new File(realFilename); if (file.exists() && file.canRead()) { // User has specified an existing file, We can continue ... if (log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "JobMssqlBulkLoad.FileExists.Label",realFilename)); if (connection!=null) { // User has specified a connection, We can continue ... Database db = new Database(this, connection); if(db.getDatabaseMeta().getDatabaseType() != DatabaseMeta.TYPE_DATABASE_MSSQL) { logError(BaseMessages.getString(PKG, "JobMssqlBulkLoad.Error.DbNotMSSQL",connection.getDatabaseName())); return result; } db.shareVariablesWith(this); try { db.connect(); // Get schemaname String realSchemaname = environmentSubstitute(schemaname); // Get tablename String realTablename = environmentSubstitute(tablename); if (db.checkTableExists(realTablename)) { // The table existe, We can continue ... if(log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "JobMssqlBulkLoad.TableExists.Label",realTablename)); // Add schemaname (Most the time Schemaname.Tablename) if (schemaname !=null) realTablename= realSchemaname + "." + realTablename; // FIELDTERMINATOR String Fieldterminator=getRealFieldTerminator(); if(Const.isEmpty(Fieldterminator) && (datafiletype.equals("char")||datafiletype.equals("widechar"))) { logError(BaseMessages.getString(PKG, "JobMssqlBulkLoad.Error.FieldTerminatorMissing")); return result; } else { if(datafiletype.equals("char")||datafiletype.equals("widechar")) { useFieldSeparator=true; FieldTerminatedby="FIELDTERMINATOR='"+Fieldterminator+"'"; } } // Check Specific Code page if(codepage.equals("Specific")) { if(specificcodepage.length()<0) { logError(BaseMessages.getString(PKG, "JobMssqlBulkLoad.Error.SpecificCodePageMissing")); return result; }else UseCodepage="CODEPAGE = '" + specificcodepage + "'"; }else { UseCodepage="CODEPAGE = '" + codepage + "'"; } // Check Error file if(errorfilename!=null) { File errorfile = new File(errorfilename); if(errorfile.exists() && !adddatetime) { // The error file is created when the command is executed. An error occurs if the file already exists. logError(BaseMessages.getString(PKG, "JobMssqlBulkLoad.Error.ErrorFileExists")); return result; } if(adddatetime) { // Add date time to filename... SimpleDateFormat daf = new SimpleDateFormat(); Date now = new Date(); daf.applyPattern("yyyMMdd_HHmmss"); String d = daf.format(now); ErrorfileName="ERRORFILE ='"+ errorfilename+"_"+d +"'"; }else ErrorfileName="ERRORFILE ='"+ errorfilename+"'"; } // ROWTERMINATOR String Rowterminator=getRealLineterminated(); if(!Const.isEmpty(Rowterminator)) LineTerminatedby="ROWTERMINATOR='"+Rowterminator+"'"; // Start file at if(startfile>0) TakeFirstNbrLines="FIRSTROW="+startfile; // End file at if(endfile>0) TakeFirstNbrLines="LASTROW="+endfile; // Truncate table? String SQLBULKLOAD=""; if(truncate) SQLBULKLOAD="TRUNCATE " + realTablename + ";"; // Build BULK Command SQLBULKLOAD=SQLBULKLOAD+"BULK INSERT " + realTablename + " FROM " + "'"+realFilename.replace('\\', '/')+"'" ; SQLBULKLOAD=SQLBULKLOAD+" WITH (" ; if(useFieldSeparator) SQLBULKLOAD=SQLBULKLOAD + FieldTerminatedby; else SQLBULKLOAD=SQLBULKLOAD + "DATAFILETYPE ='"+datafiletype+"'"; if(LineTerminatedby.length()>0) SQLBULKLOAD=SQLBULKLOAD+","+LineTerminatedby; if(TakeFirstNbrLines.length()>0) SQLBULKLOAD=SQLBULKLOAD+","+TakeFirstNbrLines; if(UseCodepage.length()>0) SQLBULKLOAD=SQLBULKLOAD+"," + UseCodepage; if(formatfilename!=null) SQLBULKLOAD=SQLBULKLOAD+", FORMATFILE='" + formatfilename + "'"; if(firetriggers) SQLBULKLOAD=SQLBULKLOAD + ",FIRE_TRIGGERS"; if(keepnulls) SQLBULKLOAD=SQLBULKLOAD + ",KEEPNULLS"; if(keepidentity) SQLBULKLOAD=SQLBULKLOAD + ",KEEPIDENTITY"; if(checkconstraints) SQLBULKLOAD=SQLBULKLOAD + ",CHECK_CONSTRAINTS"; if(tablock) SQLBULKLOAD=SQLBULKLOAD + ",TABLOCK"; if(orderby!=null) SQLBULKLOAD=SQLBULKLOAD + ",ORDER ( " + orderby + " " +orderdirection + ")"; if(ErrorfileName.length()>0) SQLBULKLOAD=SQLBULKLOAD + ", " + ErrorfileName; if(maxerrors>0) SQLBULKLOAD=SQLBULKLOAD + ", MAXERRORS="+ maxerrors; if(batchsize>0) SQLBULKLOAD=SQLBULKLOAD + ", BATCHSIZE="+ batchsize; if(rowsperbatch>0) SQLBULKLOAD=SQLBULKLOAD + ", ROWS_PER_BATCH="+ rowsperbatch; // End of Bulk command SQLBULKLOAD=SQLBULKLOAD+")"; try { // Run the SQL db.execStatements(SQLBULKLOAD); // Everything is OK...we can disconnect now db.disconnect(); if (isAddFileToResult()) { // Add filename to output files ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, KettleVFS.getFileObject(realFilename, this), parentJob.getJobname(), toString()); result.getResultFiles().put(resultFile.getFile().toString(), resultFile); } result.setResult(true); } catch(KettleDatabaseException je) { result.setNrErrors(1); logError("An error occurred executing this job entry : "+je.getMessage(), je); } catch (KettleFileException e) { logError("An error occurred executing this job entry : " + e.getMessage(), e); result.setNrErrors(1); } finally { if(db!=null) { db.disconnect(); db=null; } } } else { // Of course, the table should have been created already before the bulk load operation db.disconnect(); result.setNrErrors(1); if(log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "JobMssqlBulkLoad.Error.TableNotExists",realTablename)); } } catch(KettleDatabaseException dbe) { db.disconnect(); result.setNrErrors(1); logError("An error occurred executing this entry: "+dbe.getMessage()); } } else { // No database connection is defined result.setNrErrors(1); logError( BaseMessages.getString(PKG, "JobMssqlBulkLoad.Nodatabase.Label")); } } else { // the file doesn't exist result.setNrErrors(1); logError(BaseMessages.getString(PKG, "JobMssqlBulkLoad.Error.FileNotExists",realFilename)); } } catch(Exception e) { // An unexpected error occurred result.setNrErrors(1); logError(BaseMessages.getString(PKG, "JobMssqlBulkLoad.UnexpectedError.Label"), e); }finally{ try{ if(fileObject!=null) fileObject.close(); }catch (Exception e){} } } else { // No file was specified result.setNrErrors(1); logError(BaseMessages.getString(PKG, "JobMssqlBulkLoad.Nofilename.Label")); } return result; } public DatabaseMeta[] getUsedDatabaseConnections() { return new DatabaseMeta[] { connection, }; } public void setFilename(String filename) { this.filename = filename; } public String getFilename() { return filename; } public void setFieldTerminator(String fieldterminator) { this.fieldterminator = fieldterminator; } public void setLineterminated(String lineterminated) { this.lineterminated = lineterminated; } public void setCodePage(String codepage) { this.codepage = codepage; } public String getCodePage() { return codepage; } public void setSpecificCodePage(String specificcodepage) { this.specificcodepage =specificcodepage; } public String getSpecificCodePage() { return specificcodepage; } public void setFormatFilename(String formatfilename) { this.formatfilename =formatfilename; } public String getFormatFilename() { return formatfilename; } public String getFieldTerminator() { return fieldterminator; } public String getLineterminated() { return lineterminated; } public String getDataFileType() { return datafiletype; } public void setDataFileType(String datafiletype) { this.datafiletype = datafiletype; } public String getRealLineterminated() { return environmentSubstitute(getLineterminated()); } public String getRealFieldTerminator() { return environmentSubstitute(getFieldTerminator()); } public void setStartFile(int startfile) { this.startfile = startfile; } public int getStartFile() { return startfile; } public void setEndFile(int endfile) { this.endfile = endfile; } public int getEndFile() { return endfile; } public void setOrderBy(String orderby) { this.orderby = orderby; } public String getOrderBy() { return orderby; } public String getOrderDirection() { return orderdirection; } public void setOrderDirection(String orderdirection) { this.orderdirection = orderdirection; } public void setErrorFilename(String errorfilename) { this.errorfilename = errorfilename; } public String getErrorFilename() { return errorfilename; } public String getRealOrderBy() { return environmentSubstitute(getOrderBy()); } public void setAddFileToResult(boolean addfiletoresultin) { this.addfiletoresult = addfiletoresultin; } public boolean isAddFileToResult() { return addfiletoresult; } public void setTruncate(boolean truncate) { this.truncate = truncate; } public boolean isTruncate() { return truncate; } public void setAddDatetime(boolean adddatetime) { this.adddatetime = adddatetime; } public boolean isAddDatetime() { return adddatetime; } public void setFireTriggers(boolean firetriggers) { this.firetriggers= firetriggers; } public boolean isFireTriggers() { return firetriggers; } public void setCheckConstraints(boolean checkconstraints) { this.checkconstraints= checkconstraints; } public boolean isCheckConstraints() { return checkconstraints; } public void setKeepNulls(boolean keepnulls) { this.keepnulls= keepnulls; } public boolean isKeepNulls() { return keepnulls; } public void setKeepIdentity(boolean keepidentity) { this.keepidentity= keepidentity; } public boolean isKeepIdentity() { return keepidentity; } public void setTablock(boolean tablock) { this.tablock= tablock; } public boolean isTablock() { return tablock; } public List<ResourceReference> getResourceDependencies(JobMeta jobMeta) { List<ResourceReference> references = super.getResourceDependencies(jobMeta); ResourceReference reference = null; if (connection != null) { reference = new ResourceReference(this); references.add(reference); reference.getEntries().add( new ResourceEntry(connection.getHostname(), ResourceType.SERVER)); reference.getEntries().add( new ResourceEntry(connection.getDatabaseName(), ResourceType.DATABASENAME)); } if ( filename != null) { String realFilename = getRealFilename(); if (reference == null) { reference = new ResourceReference(this); references.add(reference); } reference.getEntries().add( new ResourceEntry(realFilename, ResourceType.FILE)); } return references; } @Override public void check(List<CheckResultInterface> remarks, JobMeta jobMeta) { ValidatorContext ctx = new ValidatorContext(); putVariableSpace(ctx, getVariables()); putValidators(ctx, notBlankValidator(), fileExistsValidator()); andValidator().validate(this, "filename", remarks, ctx);//$NON-NLS-1$ andValidator().validate(this, "tablename", remarks, putValidators(notBlankValidator())); //$NON-NLS-1$ } }
Fixed command for table truncation git-svn-id: 51b39fcfd0d3a6ea7caa15377cad4af13b9d2664@11538 5fb7f6ec-07c1-534a-b4ca-9155e429e800
src/org/pentaho/di/job/entries/mssqlbulkload/JobEntryMssqlBulkLoad.java
Fixed command for table truncation
<ide><path>rc/org/pentaho/di/job/entries/mssqlbulkload/JobEntryMssqlBulkLoad.java <ide> <ide> // Truncate table? <ide> String SQLBULKLOAD=""; <del> if(truncate) SQLBULKLOAD="TRUNCATE " + realTablename + ";"; <add> if(truncate) SQLBULKLOAD="TRUNCATE TABLE " + realTablename + ";"; <ide> <ide> // Build BULK Command <ide> SQLBULKLOAD=SQLBULKLOAD+"BULK INSERT " + realTablename + " FROM " + "'"+realFilename.replace('\\', '/')+"'" ;
JavaScript
mit
cb587f3c22d0394ae81eccff1e9d15eae406f390
0
ethereumjs/testrpc
#!/usr/bin/env node // `yargs/yargs` required to work with webpack, see here. // https://github.com/yargs/yargs/issues/781 var yargs = require('yargs/yargs'); var Ganache = require("ganache-core"); var pkg = require("./package.json"); var corepkg = require("./node_modules/ganache-core/package.json"); var URL = require("url"); var Web3 = require("web3"); var web3 = new Web3(); // Used only for its BigNumber library. var parser = yargs() .option("unlock", { type: "string", alias: "u" }); var argv = parser.parse(process.argv); if (argv.help || argv['?']) { console.log(""); console.log("testrpc: Fast Ethereum RPC client for testing and development"); console.log(" Full docs: https://github.com/ethereumjs/testrpc"); console.log(""); console.log("Usage: testrpc [options]"); console.log(" options:"); console.log(" --port/-p <port to bind to, default 8545>"); console.log(" --host/-h <host to bind to, default 0.0.0.0>"); console.log(" --fork/-f <url> (Fork from another currently running Ethereum client at a given block)"); console.log(""); console.log(" --db <db path> (directory to save chain db)"); console.log(" --seed <seed value for PRNG, default random>"); console.log(" --deterministic/-d (uses fixed seed)"); console.log(" --mnemonic/-m <mnemonic>"); console.log(" --accounts/-a <number of accounts to generate at startup>"); console.log(" --secure/-s (Lock accounts by default)"); console.log(" --unlock <accounts> (Comma-separated list of accounts or indices to unlock)"); console.log(""); console.log(" --blocktime/-b <block time in seconds>"); console.log(" --networkId/-i <network id> (default current time)"); console.log(" --gasPrice/-g <gas price> (default 20000000000)"); console.log(" --gasLimit/-l <gas limit> (default 0x47E7C4)"); console.log(""); console.log(" --debug (Output VM opcodes for debugging)"); console.log(" --verbose/-v"); console.log(" --mem (Only show memory output, not tx history)"); console.log(""); console.log(" --help / -? (this output)"); console.log(""); process.exit(0); } function parseAccounts(accounts) { function splitAccount(account) { account = account.split(',') return { secretKey: account[0], balance: account[1] }; } if (typeof accounts === 'string') return [ splitAccount(accounts) ]; else if (!Array.isArray(accounts)) return; var ret = [] for (var i = 0; i < accounts.length; i++) { ret.push(splitAccount(accounts[i])); } return ret; } if (argv.d || argv.deterministic) { argv.s = "TestRPC is awesome!"; // Seed phrase; don't change to Ganache, maintain original determinism } if (typeof argv.unlock == "string") { argv.unlock = [argv.unlock]; } var logger = console; // If the mem argument is passed, only show memory output, // not transaction history. if (argv.mem === true) { logger = { log: function() {} }; setInterval(function() { console.log(process.memoryUsage()); }, 1000); } var options = { port: argv.p || argv.port || "8545", hostname: argv.h || argv.hostname, debug: argv.debug, seed: argv.s || argv.seed, mnemonic: argv.m || argv.mnemonic, total_accounts: argv.a || argv.accounts, blocktime: argv.b || argv.blocktime, gasPrice: argv.g || argv.gasPrice, gasLimit: argv.l || argv.gasLimit, accounts: parseAccounts(argv.account), unlocked_accounts: argv.unlock, fork: argv.f || argv.fork || false, network_id: argv.i || argv.networkId, verbose: argv.v || argv.verbose, secure: argv.n || argv.secure || false, db_path: argv.db || null, logger: logger } var fork_address; // If we're forking from another client, don't try to use the same port. if (options.fork) { var split = options.fork.split("@"); fork_address = split[0]; var block; if (split.length > 1) { block = split[1]; } if (URL.parse(fork_address).port == options.port) { options.port = (parseInt(options.port) + 1); } options.fork = fork_address + (block != null ? "@" + block : ""); } var server = Ganache.server(options); //console.log("Ganache CLI v" + pkg.version); console.log("EthereumJS TestRPC v" + pkg.version + " (ganache-core: " + corepkg.version + ")"); server.listen(options.port, options.hostname, function(err, state) { if (err) { console.log(err); return; } console.log(""); console.log("Available Accounts"); console.log("=================="); var accounts = state.accounts; var addresses = Object.keys(accounts); addresses.forEach(function(address, index) { var line = "(" + index + ") " + address; if (state.isUnlocked(address) == false) { line += " ��"; } console.log(line); }); console.log(""); console.log("Private Keys"); console.log("=================="); addresses.forEach(function(address, index) { console.log("(" + index + ") " + accounts[address].secretKey.toString("hex")); }); if (options.accounts == null) { console.log(""); console.log("HD Wallet"); console.log("=================="); console.log("Mnemonic: " + state.mnemonic); console.log("Base HD Path: " + state.wallet_hdpath + "{account_index}") } if (options.gasPrice) { console.log(""); console.log("Gas Price"); console.log("=================="); console.log(options.gasPrice); } if (options.gasLimit) { console.log(""); console.log("Gas Limit"); console.log("=================="); console.log(options.gasLimit); } if (options.fork) { console.log(""); console.log("Forked Chain"); console.log("=================="); console.log("Location: " + fork_address); console.log("Block: " + web3.toBigNumber(state.blockchain.fork_block_number).toString(10)); console.log("Network ID: " + state.net_version); console.log("Time: " + (state.blockchain.startTime || new Date()).toString()); } console.log(""); console.log("Listening on " + (options.hostname || "localhost") + ":" + options.port); }); process.on('uncaughtException', function(e) { console.log(e.stack); process.exit(1); }) // See http://stackoverflow.com/questions/10021373/what-is-the-windows-equivalent-of-process-onsigint-in-node-js if (process.platform === "win32") { require("readline").createInterface({ input: process.stdin, output: process.stdout }) .on("SIGINT", function () { process.emit("SIGINT"); }); } process.on("SIGINT", function () { // graceful shutdown server.close(function(err) { if (err) { console.log(err.stack || err); } process.exit(); }); });
cli.js
#!/usr/bin/env node // `yargs/yargs` required to work with webpack, see here. // https://github.com/yargs/yargs/issues/781 var yargs = require('yargs/yargs'); var Ganache = require("ganache-core"); var pkg = require("./package.json"); var corepkg = require("./node_modules/ganache-core/package.json"); var URL = require("url"); var Web3 = require("web3"); var web3 = new Web3(); // Used only for its BigNumber library. var parser = yargs() .option("unlock", { type: "string", alias: "u" }); var argv = parser.parse(process.argv); function parseAccounts(accounts) { function splitAccount(account) { account = account.split(',') return { secretKey: account[0], balance: account[1] }; } if (typeof accounts === 'string') return [ splitAccount(accounts) ]; else if (!Array.isArray(accounts)) return; var ret = [] for (var i = 0; i < accounts.length; i++) { ret.push(splitAccount(accounts[i])); } return ret; } if (argv.d || argv.deterministic) { argv.s = "TestRPC is awesome!"; // Seed phrase; don't change to Ganache, maintain original determinism } if (typeof argv.unlock == "string") { argv.unlock = [argv.unlock]; } var logger = console; // If the mem argument is passed, only show memory output, // not transaction history. if (argv.mem === true) { logger = { log: function() {} }; setInterval(function() { console.log(process.memoryUsage()); }, 1000); } var options = { port: argv.p || argv.port || "8545", hostname: argv.h || argv.hostname, debug: argv.debug, seed: argv.s || argv.seed, mnemonic: argv.m || argv.mnemonic, total_accounts: argv.a || argv.accounts, blocktime: argv.b || argv.blocktime, gasPrice: argv.g || argv.gasPrice, gasLimit: argv.l || argv.gasLimit, accounts: parseAccounts(argv.account), unlocked_accounts: argv.unlock, fork: argv.f || argv.fork || false, network_id: argv.i || argv.networkId, verbose: argv.v || argv.verbose, secure: argv.n || argv.secure || false, db_path: argv.db || null, logger: logger } var fork_address; // If we're forking from another client, don't try to use the same port. if (options.fork) { var split = options.fork.split("@"); fork_address = split[0]; var block; if (split.length > 1) { block = split[1]; } if (URL.parse(fork_address).port == options.port) { options.port = (parseInt(options.port) + 1); } options.fork = fork_address + (block != null ? "@" + block : ""); } var server = Ganache.server(options); //console.log("Ganache CLI v" + pkg.version); console.log("EthereumJS TestRPC v" + pkg.version + " (ganache-core: " + corepkg.version + ")"); server.listen(options.port, options.hostname, function(err, state) { if (err) { console.log(err); return; } console.log(""); console.log("Available Accounts"); console.log("=================="); var accounts = state.accounts; var addresses = Object.keys(accounts); addresses.forEach(function(address, index) { var line = "(" + index + ") " + address; if (state.isUnlocked(address) == false) { line += " ��"; } console.log(line); }); console.log(""); console.log("Private Keys"); console.log("=================="); addresses.forEach(function(address, index) { console.log("(" + index + ") " + accounts[address].secretKey.toString("hex")); }); if (options.accounts == null) { console.log(""); console.log("HD Wallet"); console.log("=================="); console.log("Mnemonic: " + state.mnemonic); console.log("Base HD Path: " + state.wallet_hdpath + "{account_index}") } if (options.gasPrice) { console.log(""); console.log("Gas Price"); console.log("=================="); console.log(options.gasPrice); } if (options.gasLimit) { console.log(""); console.log("Gas Limit"); console.log("=================="); console.log(options.gasLimit); } if (options.fork) { console.log(""); console.log("Forked Chain"); console.log("=================="); console.log("Location: " + fork_address); console.log("Block: " + web3.toBigNumber(state.blockchain.fork_block_number).toString(10)); console.log("Network ID: " + state.net_version); console.log("Time: " + (state.blockchain.startTime || new Date()).toString()); } console.log(""); console.log("Listening on " + (options.hostname || "localhost") + ":" + options.port); }); process.on('uncaughtException', function(e) { console.log(e.stack); process.exit(1); }) // See http://stackoverflow.com/questions/10021373/what-is-the-windows-equivalent-of-process-onsigint-in-node-js if (process.platform === "win32") { require("readline").createInterface({ input: process.stdin, output: process.stdout }) .on("SIGINT", function () { process.emit("SIGINT"); }); } process.on("SIGINT", function () { // graceful shutdown server.close(function(err) { if (err) { console.log(err.stack || err); } process.exit(); }); });
Add output for --help and -?
cli.js
Add output for --help and -?
<ide><path>li.js <ide> }); <ide> <ide> var argv = parser.parse(process.argv); <add> <add>if (argv.help || argv['?']) { <add> console.log(""); <add> console.log("testrpc: Fast Ethereum RPC client for testing and development"); <add> console.log(" Full docs: https://github.com/ethereumjs/testrpc"); <add> console.log(""); <add> console.log("Usage: testrpc [options]"); <add> console.log(" options:"); <add> console.log(" --port/-p <port to bind to, default 8545>"); <add> console.log(" --host/-h <host to bind to, default 0.0.0.0>"); <add> console.log(" --fork/-f <url> (Fork from another currently running Ethereum client at a given block)"); <add> console.log(""); <add> console.log(" --db <db path> (directory to save chain db)"); <add> console.log(" --seed <seed value for PRNG, default random>"); <add> console.log(" --deterministic/-d (uses fixed seed)"); <add> console.log(" --mnemonic/-m <mnemonic>"); <add> console.log(" --accounts/-a <number of accounts to generate at startup>"); <add> console.log(" --secure/-s (Lock accounts by default)"); <add> console.log(" --unlock <accounts> (Comma-separated list of accounts or indices to unlock)"); <add> console.log(""); <add> console.log(" --blocktime/-b <block time in seconds>"); <add> console.log(" --networkId/-i <network id> (default current time)"); <add> console.log(" --gasPrice/-g <gas price> (default 20000000000)"); <add> console.log(" --gasLimit/-l <gas limit> (default 0x47E7C4)"); <add> console.log(""); <add> console.log(" --debug (Output VM opcodes for debugging)"); <add> console.log(" --verbose/-v"); <add> console.log(" --mem (Only show memory output, not tx history)"); <add> console.log(""); <add> console.log(" --help / -? (this output)"); <add> console.log(""); <add> process.exit(0); <add>} <ide> <ide> function parseAccounts(accounts) { <ide> function splitAccount(account) {
Java
apache-2.0
e0a345b3f3a2ffbe5258e5f878594e8a76d4c51f
0
infraling/atomic,infraling/atomic
/** * */ package org.corpus_tools.atomic.tagset.impl; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.TreeSet; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.corpus_tools.atomic.models.AbstractBean; import org.corpus_tools.atomic.tagset.Tagset; import org.corpus_tools.atomic.tagset.TagsetValue; import org.corpus_tools.salt.SALT_TYPE; import org.corpus_tools.salt.common.SCorpus; import org.corpus_tools.salt.graph.Identifier; import org.eclipse.emf.common.util.URI; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; /** * A simple implementation of a {@link Tagset}. * * @author Stephan Druskat <[[email protected]](mailto:[email protected])> * */ @JsonDeserialize(as = JavaTagsetImpl.class) public class JavaTagsetImpl extends AbstractBean implements Tagset { /** * Default constructor, needed to adhere to Java Bean specs. */ public JavaTagsetImpl() { // Do nothing, needed for serialization/deserialization } private static final Logger log = LogManager.getLogger(JavaTagsetImpl.class); private String name; private List<TagsetValue> values; private String corpus; /** * Unique serial version identifier for version 1L. * @see Serializable */ private static final long serialVersionUID = 1L; /** * Constructor taking and setting the name of the tagset. * * @param corpusId The {@link Identifier} id of the {@link SCorpus} the tagset is for * @param name The name of the tagset */ public JavaTagsetImpl(String corpusId, String name) { setName(name); setCorpusId(corpusId); this.values = new ArrayList<>(); } /* (non-Javadoc) * @see org.corpus_tools.atomic.tagset.Tagset#save(org.eclipse.emf.common.util.URI) */ @Override public boolean save(URI uri) { ObjectMapper mapper = new ObjectMapper(); String path = uri.toFileString(); try { mapper.writeValue(new File(path), this); } catch (IOException e1) { log.error("Error writing JSON file from tagset {}!", getName(), e1); return false; } return true; } /* (non-Javadoc) * @see org.corpus_tools.atomic.tagset.Tagset#getName() */ @Override public String getName() { return name; } /* (non-Javadoc) * @see org.corpus_tools.atomic.tagset.Tagset#setName(java.lang.String) */ @Override public void setName(String name) { this.name = name; } /* (non-Javadoc) * @see org.corpus_tools.atomic.tagset.Tagset#setCorpus(org.corpus_tools.salt.common.SCorpus) */ @Override public void setCorpusId(String corpus) { this.corpus = corpus; } /* (non-Javadoc) * @see org.corpus_tools.atomic.tagset.Tagset#getCorpus() */ @Override public String getCorpusId() { return corpus; } /* (non-Javadoc) * @see org.corpus_tools.atomic.tagset.Tagset#addValue(org.corpus_tools.atomic.tagset.TagsetValue) */ @Override public boolean addValue(TagsetValue value) { List<TagsetValue> newValues = this.getValues(); boolean isNewlyAdded = newValues.add(value); setValues(newValues); return isNewlyAdded; } /* (non-Javadoc) * @see org.corpus_tools.atomic.tagset.Tagset#addValue(int, org.corpus_tools.atomic.tagset.TagsetValue) */ public boolean addValue(int index, TagsetValue value) { List<TagsetValue> newValues = this.getValues(); int oldSize = newValues.size(); newValues.add(index, value); setValues(newValues); return newValues.size() > oldSize; } /* (non-Javadoc) * @see org.corpus_tools.atomic.tagset.Tagset#removeValue(org.corpus_tools.atomic.tagset.TagsetValue) */ @Override public boolean removeValue(TagsetValue value) { List<TagsetValue> newValues = this.getValues(); boolean hadContainedValue = newValues.remove(value); setValues(newValues); return hadContainedValue; } /* (non-Javadoc) * @see org.corpus_tools.atomic.tagset.Tagset#setValues(java.util.Set) */ @Override public void setValues(List<TagsetValue> values) { List<TagsetValue> oldValues = this.values; this.values = values; firePropertyChange("values", oldValues, this.values); } /* (non-Javadoc) * @see org.corpus_tools.atomic.tagset.Tagset#getValues() */ @Override public List<TagsetValue> getValues() { return values; } /** * Implementation determining which parameters should be * taken into account when querying the valid values. * * As annotations in Salt **always** have a name, the * parameters which determine the set are *layer*, * *elementType* and *namespace*. Thus, there are 8 * possible combinations of `null`/non-`null` values: * * ```` * L E N Case * ---------- * 1 1 1 1 * 0 0 0 2 * 1 0 0 3 * 1 1 0 4 * 1 0 1 5 * 0 1 0 6 * 0 1 1 7 * 0 0 1 8 * ```` * * Depending on the combination of parameter values, * another method is called to return the correct value set. * * @see org.corpus_tools.atomic.tagset.Tagset#getValuesForParameters(java.lang.String, org.corpus_tools.salt.SALT_TYPE, java.lang.String, java.lang.String) */ @Override public Set<TagsetValue> getValuesForParameters(String layer, SALT_TYPE elementType, String namespace, String name) { if (layer == null) { if (elementType == null) { if (namespace == null) { // Case 2 return getValuesForParameters(name); } else { // Case 8 return getValuesForParameters(namespace, false, name); } } else { if (namespace == null) { // Case 6 return getValuesForParameters(elementType, name); } else { // Case 7 return getValuesForParameters(elementType, namespace, name); } } } else { if (elementType == null) { if (namespace == null) { // Case 3 return getValuesForParameters(layer, true, name); } else { // Case 5 return getValuesForParameters(layer, namespace, name); } } else { if (namespace == null) { // Case 4 return getValuesForParameters(layer, elementType, name); } else { // Case 1 Set<TagsetValue> validValues = new HashSet<>(); Stream<TagsetValue> allValidEntries = getValues().stream().filter(value -> ( Objects.equals(value.getLayer(), layer) && Objects.equals(value.getElementType(), elementType) && Objects.equals(value.getNamespace(), namespace) && Objects.equals(value.getName(), name))); allValidEntries.forEach(e -> validValues.add(e)); return validValues; } } } } private Set<TagsetValue> getValuesForParameters(String name) { Set<TagsetValue> validValues = new HashSet<>(); Stream<TagsetValue> allValidEntries = getValues().stream().filter(value -> (Objects.equals(value.getName(), name))); allValidEntries.forEach(e -> validValues.add(e)); return validValues; } private Set<TagsetValue> getValuesForParameters(String layerOrNamespace, boolean isFirstParameterLayerString, String name) { Set<TagsetValue> validValues = new HashSet<>(); if (isFirstParameterLayerString) { Stream<TagsetValue> allValidEntries = getValues().stream().filter(value -> ( Objects.equals(value.getLayer(), layerOrNamespace) && Objects.equals(value.getName(), name))); allValidEntries.forEach(e -> validValues.add(e)); } else { Stream<TagsetValue> allValidEntries = getValues().stream().filter(value -> ( Objects.equals(value.getNamespace(), layerOrNamespace) && Objects.equals(value.getName(), name))); allValidEntries.forEach(e -> validValues.add(e)); } return validValues; } private Set<TagsetValue> getValuesForParameters(String layer, SALT_TYPE elementType, String name) { Set<TagsetValue> validValues = new HashSet<>(); Stream<TagsetValue> allValidEntries = getValues().stream().filter(value -> ( Objects.equals(value.getLayer(), layer) && Objects.equals(value.getElementType(), elementType) && Objects.equals(value.getName(), name))); allValidEntries.forEach(e -> validValues.add(e)); return validValues; } private Set<TagsetValue> getValuesForParameters(String layer, String namespace, String name) { Set<TagsetValue> validValues = new HashSet<>(); Stream<TagsetValue> allValidEntries = getValues().stream().filter(value -> ( Objects.equals(value.getLayer(), layer) && Objects.equals(value.getNamespace(), namespace) && Objects.equals(value.getName(), name))); allValidEntries.forEach(e -> validValues.add(e)); return validValues; } private Set<TagsetValue> getValuesForParameters(SALT_TYPE elementType, String name) { Set<TagsetValue> validValues = new HashSet<>(); Stream<TagsetValue> allValidEntries = getValues().stream().filter(value -> ( Objects.equals(value.getElementType(), elementType) && Objects.equals(value.getName(), name))); allValidEntries.forEach(e -> validValues.add(e)); return validValues; } private Set<TagsetValue> getValuesForParameters(SALT_TYPE elementType, String namespace, String name) { Set<TagsetValue> validValues = new HashSet<>(); Stream<TagsetValue> allValidEntries = getValues().stream().filter(value -> ( Objects.equals(value.getElementType(), elementType) && Objects.equals(value.getNamespace(), namespace) && Objects.equals(value.getName(), name))); allValidEntries.forEach(e -> validValues.add(e)); return validValues; } @Override public Set<String> getAnnotationNamesForParameters(String layer, SALT_TYPE elementType, String namespace) { Stream<TagsetValue> allValidEntries = getValues().stream().filter(value -> ( (Objects.equals(value.getLayer(), layer) || value.getLayer() == null) && (Objects.equals(value.getElementType(), elementType) || value.getElementType() == null) && (Objects.equals(value.getNamespace(), namespace) || value.getNamespace() == null))); return allValidEntries.map(TagsetValue::getName).distinct().collect(Collectors.toCollection(HashSet<String>::new)); } }
plugins/org.corpus-tools.atomic/src/main/java/org/corpus_tools/atomic/tagset/impl/JavaTagsetImpl.java
/** * */ package org.corpus_tools.atomic.tagset.impl; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.TreeSet; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.corpus_tools.atomic.models.AbstractBean; import org.corpus_tools.atomic.tagset.Tagset; import org.corpus_tools.atomic.tagset.TagsetValue; import org.corpus_tools.salt.SALT_TYPE; import org.corpus_tools.salt.common.SCorpus; import org.corpus_tools.salt.graph.Identifier; import org.eclipse.emf.common.util.URI; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; /** * A simple implementation of a {@link Tagset}. * * @author Stephan Druskat <[[email protected]](mailto:[email protected])> * */ @JsonDeserialize(as = JavaTagsetImpl.class) public class JavaTagsetImpl extends AbstractBean implements Tagset { /** * Default constructor, needed to adhere to Java Bean specs. */ public JavaTagsetImpl() { // Do nothing, needed for serialization/deserialization } private static final Logger log = LogManager.getLogger(JavaTagsetImpl.class); private String name; private List<TagsetValue> values; private String corpus; /** * Unique serial version identifier for version 1L. * @see Serializable */ private static final long serialVersionUID = 1L; /** * Constructor taking and setting the name of the tagset. * * @param corpusId The {@link Identifier} id of the {@link SCorpus} the tagset is for * @param name The name of the tagset */ public JavaTagsetImpl(String corpusId, String name) { setName(name); setCorpusId(corpusId); this.values = new ArrayList<>(); } /* (non-Javadoc) * @see org.corpus_tools.atomic.tagset.Tagset#save(org.eclipse.emf.common.util.URI) */ @Override public boolean save(URI uri) { ObjectMapper mapper = new ObjectMapper(); String path = uri.toFileString(); try { mapper.writeValue(new File(path), this); } catch (IOException e1) { log.error("Error writing JSON file from tagset {}!", getName(), e1); return false; } return true; } /* (non-Javadoc) * @see org.corpus_tools.atomic.tagset.Tagset#getName() */ @Override public String getName() { return name; } /* (non-Javadoc) * @see org.corpus_tools.atomic.tagset.Tagset#setName(java.lang.String) */ @Override public void setName(String name) { this.name = name; } /* (non-Javadoc) * @see org.corpus_tools.atomic.tagset.Tagset#setCorpus(org.corpus_tools.salt.common.SCorpus) */ @Override public void setCorpusId(String corpus) { this.corpus = corpus; } /* (non-Javadoc) * @see org.corpus_tools.atomic.tagset.Tagset#getCorpus() */ @Override public String getCorpusId() { return corpus; } /* (non-Javadoc) * @see org.corpus_tools.atomic.tagset.Tagset#addValue(org.corpus_tools.atomic.tagset.TagsetValue) */ @Override public boolean addValue(TagsetValue value) { List<TagsetValue> newValues = this.getValues(); boolean isNewlyAdded = newValues.add(value); setValues(newValues); return isNewlyAdded; } /* (non-Javadoc) * @see org.corpus_tools.atomic.tagset.Tagset#addValue(int, org.corpus_tools.atomic.tagset.TagsetValue) */ public boolean addValue(int index, TagsetValue value) { List<TagsetValue> newValues = this.getValues(); int oldSize = newValues.size(); newValues.add(index, value); setValues(newValues); return newValues.size() > oldSize; } /* (non-Javadoc) * @see org.corpus_tools.atomic.tagset.Tagset#removeValue(org.corpus_tools.atomic.tagset.TagsetValue) */ @Override public boolean removeValue(TagsetValue value) { List<TagsetValue> newValues = this.getValues(); boolean hadContainedValue = newValues.remove(value); setValues(newValues); return hadContainedValue; } /* (non-Javadoc) * @see org.corpus_tools.atomic.tagset.Tagset#setValues(java.util.Set) */ @Override public void setValues(List<TagsetValue> values) { List<TagsetValue> oldValues = this.values; this.values = values; firePropertyChange("values", oldValues, this.values); } /* (non-Javadoc) * @see org.corpus_tools.atomic.tagset.Tagset#getValues() */ @Override public List<TagsetValue> getValues() { return values; } /* (non-Javadoc) * @see org.corpus_tools.atomic.tagset.Tagset#getValuesForParameters(java.lang.String, org.corpus_tools.salt.SALT_TYPE, java.lang.String, java.lang.String) */ @Override public Set<TagsetValue> getValuesForParameters(String layer, SALT_TYPE elementType, String namespace, String name) { Set<TagsetValue> validValues = new HashSet<>(); Stream<TagsetValue> allValidEntries = getValues().stream().filter(value -> ( (Objects.equals(value.getLayer(), layer) || value.getLayer() == null) && (Objects.equals(value.getElementType(), elementType) || value.getElementType() == null) && (Objects.equals(value.getNamespace(), namespace) || value.getNamespace() == null) && Objects.equals(value.getName(), name))); allValidEntries.forEach(e -> validValues.add(e)); return validValues; } @Override public Set<String> getAnnotationNamesForParameters(String layer, SALT_TYPE elementType, String namespace) { Stream<TagsetValue> allValidEntries = getValues().stream().filter(value -> ( (Objects.equals(value.getLayer(), layer) || value.getLayer() == null) && (Objects.equals(value.getElementType(), elementType) || value.getElementType() == null) && (Objects.equals(value.getNamespace(), namespace) || value.getNamespace() == null))); return allValidEntries.map(TagsetValue::getName).distinct().collect(Collectors.toCollection(HashSet<String>::new)); } }
Implement overrides for valid values getter depending on null values
plugins/org.corpus-tools.atomic/src/main/java/org/corpus_tools/atomic/tagset/impl/JavaTagsetImpl.java
Implement overrides for valid values getter depending on null values
<ide><path>lugins/org.corpus-tools.atomic/src/main/java/org/corpus_tools/atomic/tagset/impl/JavaTagsetImpl.java <ide> return values; <ide> } <ide> <del> /* (non-Javadoc) <add> <add> /** <add> * Implementation determining which parameters should be <add> * taken into account when querying the valid values. <add> * <add> * As annotations in Salt **always** have a name, the <add> * parameters which determine the set are *layer*, <add> * *elementType* and *namespace*. Thus, there are 8 <add> * possible combinations of `null`/non-`null` values: <add> * <add> * ```` <add> * L E N Case <add> * ---------- <add> * 1 1 1 1 <add> * 0 0 0 2 <add> * 1 0 0 3 <add> * 1 1 0 4 <add> * 1 0 1 5 <add> * 0 1 0 6 <add> * 0 1 1 7 <add> * 0 0 1 8 <add> * ```` <add> * <add> * Depending on the combination of parameter values, <add> * another method is called to return the correct value set. <add> * <ide> * @see org.corpus_tools.atomic.tagset.Tagset#getValuesForParameters(java.lang.String, org.corpus_tools.salt.SALT_TYPE, java.lang.String, java.lang.String) <ide> */ <ide> @Override <ide> public Set<TagsetValue> getValuesForParameters(String layer, SALT_TYPE elementType, String namespace, String name) { <del> Set<TagsetValue> validValues = new HashSet<>(); <del> Stream<TagsetValue> allValidEntries = getValues().stream().filter(value -> ( <del> (Objects.equals(value.getLayer(), layer) || value.getLayer() == null) <del> && (Objects.equals(value.getElementType(), elementType) || value.getElementType() == null) <del> && (Objects.equals(value.getNamespace(), namespace) || value.getNamespace() == null) <add> if (layer == null) { <add> if (elementType == null) { <add> if (namespace == null) { // Case 2 <add> return getValuesForParameters(name); <add> } <add> else { // Case 8 <add> return getValuesForParameters(namespace, false, name); <add> } <add> } <add> else { <add> if (namespace == null) { // Case 6 <add> return getValuesForParameters(elementType, name); <add> } <add> else { // Case 7 <add> return getValuesForParameters(elementType, namespace, name); <add> } <add> } <add> } <add> else { <add> if (elementType == null) { <add> if (namespace == null) { // Case 3 <add> return getValuesForParameters(layer, true, name); <add> } <add> else { // Case 5 <add> return getValuesForParameters(layer, namespace, name); <add> } <add> } <add> else { <add> if (namespace == null) { // Case 4 <add> return getValuesForParameters(layer, elementType, name); <add> } <add> else { // Case 1 <add> Set<TagsetValue> validValues = new HashSet<>(); <add> Stream<TagsetValue> allValidEntries = getValues().stream().filter(value -> ( <add> Objects.equals(value.getLayer(), layer) <add> && Objects.equals(value.getElementType(), elementType) <add> && Objects.equals(value.getNamespace(), namespace) <add> && Objects.equals(value.getName(), name))); <add> allValidEntries.forEach(e -> validValues.add(e)); <add> return validValues; <add> } <add> } <add> } <add> } <add> <add> private Set<TagsetValue> getValuesForParameters(String name) { <add> Set<TagsetValue> validValues = new HashSet<>(); <add> Stream<TagsetValue> allValidEntries = getValues().stream().filter(value -> (Objects.equals(value.getName(), name))); <add> allValidEntries.forEach(e -> validValues.add(e)); <add> return validValues; <add> } <add> <add> private Set<TagsetValue> getValuesForParameters(String layerOrNamespace, boolean isFirstParameterLayerString, String name) { <add> Set<TagsetValue> validValues = new HashSet<>(); <add> if (isFirstParameterLayerString) { <add> Stream<TagsetValue> allValidEntries = getValues().stream().filter(value -> ( <add> Objects.equals(value.getLayer(), layerOrNamespace) <add> && Objects.equals(value.getName(), name))); <add> allValidEntries.forEach(e -> validValues.add(e)); <add> } <add> else { <add> Stream<TagsetValue> allValidEntries = getValues().stream().filter(value -> ( <add> Objects.equals(value.getNamespace(), layerOrNamespace) <add> && Objects.equals(value.getName(), name))); <add> allValidEntries.forEach(e -> validValues.add(e)); <add> } <add> return validValues; <add> } <add> <add> private Set<TagsetValue> getValuesForParameters(String layer, SALT_TYPE elementType, String name) { <add> Set<TagsetValue> validValues = new HashSet<>(); <add> Stream<TagsetValue> allValidEntries = getValues().stream().filter(value -> ( <add> Objects.equals(value.getLayer(), layer) <add> && Objects.equals(value.getElementType(), elementType) <ide> && Objects.equals(value.getName(), name))); <ide> allValidEntries.forEach(e -> validValues.add(e)); <ide> return validValues; <ide> } <del> <add> <add> private Set<TagsetValue> getValuesForParameters(String layer, String namespace, String name) { <add> Set<TagsetValue> validValues = new HashSet<>(); <add> Stream<TagsetValue> allValidEntries = getValues().stream().filter(value -> ( <add> Objects.equals(value.getLayer(), layer) <add> && Objects.equals(value.getNamespace(), namespace) <add> && Objects.equals(value.getName(), name))); <add> allValidEntries.forEach(e -> validValues.add(e)); <add> return validValues; <add> } <add> <add> private Set<TagsetValue> getValuesForParameters(SALT_TYPE elementType, String name) { <add> Set<TagsetValue> validValues = new HashSet<>(); <add> Stream<TagsetValue> allValidEntries = getValues().stream().filter(value -> ( <add> Objects.equals(value.getElementType(), elementType) <add> && Objects.equals(value.getName(), name))); <add> allValidEntries.forEach(e -> validValues.add(e)); <add> return validValues; <add> } <add> <add> private Set<TagsetValue> getValuesForParameters(SALT_TYPE elementType, String namespace, String name) { <add> Set<TagsetValue> validValues = new HashSet<>(); <add> Stream<TagsetValue> allValidEntries = getValues().stream().filter(value -> ( <add> Objects.equals(value.getElementType(), elementType) <add> && Objects.equals(value.getNamespace(), namespace) <add> && Objects.equals(value.getName(), name))); <add> allValidEntries.forEach(e -> validValues.add(e)); <add> return validValues; <add> } <add> <ide> @Override <ide> public Set<String> getAnnotationNamesForParameters(String layer, SALT_TYPE elementType, String namespace) { <ide> Stream<TagsetValue> allValidEntries = getValues().stream().filter(value -> (
Java
mit
292952b44f1f9417318922d05926ec6a39c336f7
0
mindwind/craft-atom,mindwind/craft-atom
package org.craft.atom.protocol.rpc; import org.craft.atom.protocol.rpc.model.RpcBody; import org.craft.atom.protocol.rpc.spi.Serialization; import org.craft.atom.protocol.rpc.spi.SerializationFactory; /** * @author mindwind * @version 1.0, Jul 23, 2014 */ public class KryoSerializationFactory implements SerializationFactory<RpcBody> { // singleton private static final KryoSerializationFactory INSTNACE = new KryoSerializationFactory(); private KryoSerializationFactory() {} public static KryoSerializationFactory getInstance() { return INSTNACE; } // thread local cache private static final ThreadLocal<KryoSerialization> CACHE = new ThreadLocal<KryoSerialization>() { @Override protected KryoSerialization initialValue() { return new KryoSerialization(); } }; @Override public Serialization<RpcBody> newSerialization() { return CACHE.get(); } }
craft-atom-protocol-rpc/src/main/java/org/craft/atom/protocol/rpc/KryoSerializationFactory.java
package org.craft.atom.protocol.rpc; import org.craft.atom.protocol.rpc.model.RpcBody; import org.craft.atom.protocol.rpc.spi.Serialization; import org.craft.atom.protocol.rpc.spi.SerializationFactory; /** * @author mindwind * @version 1.0, Jul 23, 2014 */ public class KryoSerializationFactory implements SerializationFactory<RpcBody> { private static final KryoSerializationFactory INSTNACE = new KryoSerializationFactory(); private KryoSerializationFactory() {} public static KryoSerializationFactory getInstance() { return INSTNACE; } @Override public Serialization<RpcBody> newSerialization() { return new KryoSerialization(); } }
improve - performance use thread local pool cache avoid construct a new serialization each invocation.
craft-atom-protocol-rpc/src/main/java/org/craft/atom/protocol/rpc/KryoSerializationFactory.java
improve - performance
<ide><path>raft-atom-protocol-rpc/src/main/java/org/craft/atom/protocol/rpc/KryoSerializationFactory.java <ide> public class KryoSerializationFactory implements SerializationFactory<RpcBody> { <ide> <ide> <add> // singleton <ide> private static final KryoSerializationFactory INSTNACE = new KryoSerializationFactory(); <ide> private KryoSerializationFactory() {} <ide> public static KryoSerializationFactory getInstance() { return INSTNACE; } <del> <add> <add> <add> // thread local cache <add> private static final ThreadLocal<KryoSerialization> CACHE = new ThreadLocal<KryoSerialization>() { <add> @Override <add> protected KryoSerialization initialValue() { <add> return new KryoSerialization(); <add> } <add> }; <add> <ide> <ide> @Override <ide> public Serialization<RpcBody> newSerialization() { <del> return new KryoSerialization(); <add> return CACHE.get(); <ide> } <ide> <ide> }
Java
apache-2.0
1e2b082704b1fa1ff3ae4fbdf5afa69902f4aa26
0
mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid
/* * * * 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.usergrid.persistence.graph.serialization.impl.shard.impl; import java.nio.charset.Charset; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import javax.annotation.Nullable; import com.google.common.base.Optional; import com.netflix.astyanax.connectionpool.OperationResult; import org.apache.usergrid.persistence.core.astyanax.ScopedRowKey; import org.apache.usergrid.persistence.graph.Edge; import org.apache.usergrid.persistence.graph.serialization.impl.shard.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.usergrid.persistence.core.consistency.TimeService; import org.apache.usergrid.persistence.core.scope.ApplicationScope; import org.apache.usergrid.persistence.graph.GraphFig; import org.apache.usergrid.persistence.graph.MarkedEdge; import org.apache.usergrid.persistence.graph.SearchByEdgeType; import org.apache.usergrid.persistence.model.entity.Id; import org.apache.usergrid.persistence.model.util.UUIDGenerator; import com.google.common.base.Preconditions; import com.google.common.hash.HashFunction; import com.google.common.hash.Hasher; import com.google.common.hash.Hashing; import com.google.common.hash.PrimitiveSink; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.inject.Inject; import com.google.inject.Singleton; import com.netflix.astyanax.Keyspace; import com.netflix.astyanax.MutationBatch; import com.netflix.astyanax.connectionpool.exceptions.ConnectionException; import rx.Observable; import rx.schedulers.Schedulers; /** * Implementation of the shard group compaction */ @Singleton public class ShardGroupCompactionImpl implements ShardGroupCompaction { private final AtomicLong countAudits; private static final Logger logger = LoggerFactory.getLogger( ShardGroupCompactionImpl.class ); private static final Charset CHARSET = Charset.forName( "UTF-8" ); private static final HashFunction MURMUR_128 = Hashing.murmur3_128(); private final ListeningExecutorService taskExecutor; private final TimeService timeService; private final GraphFig graphFig; private final NodeShardAllocation nodeShardAllocation; private final ShardedEdgeSerialization shardedEdgeSerialization; private final EdgeColumnFamilies edgeColumnFamilies; private final Keyspace keyspace; private final EdgeShardSerialization edgeShardSerialization; private final Random random; private final ShardCompactionTaskTracker shardCompactionTaskTracker; private final ShardAuditTaskTracker shardAuditTaskTracker; @Inject public ShardGroupCompactionImpl( final TimeService timeService, final GraphFig graphFig, final NodeShardAllocation nodeShardAllocation, final ShardedEdgeSerialization shardedEdgeSerialization, final EdgeColumnFamilies edgeColumnFamilies, final Keyspace keyspace, final EdgeShardSerialization edgeShardSerialization, final AsyncTaskExecutor asyncTaskExecutor) { this.timeService = timeService; this.countAudits = new AtomicLong(); this.graphFig = graphFig; this.nodeShardAllocation = nodeShardAllocation; this.shardedEdgeSerialization = shardedEdgeSerialization; this.edgeColumnFamilies = edgeColumnFamilies; this.keyspace = keyspace; this.edgeShardSerialization = edgeShardSerialization; this.random = new Random(); this.shardCompactionTaskTracker = new ShardCompactionTaskTracker(); this.shardAuditTaskTracker = new ShardAuditTaskTracker(); this.taskExecutor = asyncTaskExecutor.getExecutorService(); } /** * Execute the compaction task. Will return the status the operations performed * * @param group The shard entry group to compact * * @return The result of the compaction operation */ public CompactionResult compact( final ApplicationScope scope, final DirectedEdgeMeta edgeMeta, final ShardEntryGroup group ) { final long startTime = timeService.getCurrentTime(); Preconditions.checkNotNull( group, "group cannot be null" ); Preconditions.checkArgument( group.isCompactionPending(), "Compaction is pending" ); Preconditions .checkArgument( group.shouldCompact( startTime ), "Compaction cannot be run yet. Ignoring compaction." ); if(logger.isTraceEnabled()) { logger.trace("Compacting shard group. Audit count is {} ", countAudits.get()); } final CompactionResult.CompactionBuilder resultBuilder = CompactionResult.builder(); final Shard targetShard = group.getCompactionTarget(); final Set<Shard> sourceShards = new HashSet<>( group.getReadShards() ); //remove the target sourceShards.remove( targetShard ); final UUID timestamp = UUIDGenerator.newTimeUUID(); final long newShardPivot = targetShard.getShardIndex(); final int maxWorkSize = graphFig.getScanPageSize(); /** * As we move edges, we want to keep track of it */ long totalEdgeCount = 0; for ( Shard sourceShard : sourceShards ) { final MutationBatch newRowBatch = keyspace.prepareMutationBatch(); final MutationBatch deleteRowBatch = keyspace.prepareMutationBatch(); final MutationBatch updateShardMetaBatch = keyspace.prepareMutationBatch(); long edgeCount = 0; Iterator<MarkedEdge> edges = edgeMeta .loadEdges( shardedEdgeSerialization, edgeColumnFamilies, scope, Collections.singleton( sourceShard ), Long.MAX_VALUE, SearchByEdgeType.Order.DESCENDING ); MarkedEdge shardEnd = null; while ( edges.hasNext() ) { final MarkedEdge edge = edges.next(); final long edgeTimestamp = edge.getTimestamp(); shardEnd = edge; /** * The edge is within a different shard, break */ if ( edgeTimestamp < newShardPivot ) { break; } newRowBatch.mergeShallow( edgeMeta .writeEdge( shardedEdgeSerialization, edgeColumnFamilies, scope, targetShard, edge, timestamp ) ); deleteRowBatch.mergeShallow( edgeMeta .deleteEdge( shardedEdgeSerialization, edgeColumnFamilies, scope, sourceShard, edge, timestamp ) ); edgeCount++; // if we're at our count, execute the mutation of writing the edges to the new row, then remove them // from the old rows if ( edgeCount % maxWorkSize == 0 ) { try { // write the edges into the new shard atomically so we know they all succeed newRowBatch.withAtomicBatch(true).execute(); // Update the shard end after each batch so any reads during transition stay as close to current sourceShard.setShardEnd( Optional.of(new DirectedEdge(shardEnd.getTargetNode(), shardEnd.getTimestamp())) ); if(logger.isTraceEnabled()) { logger.trace("Updating shard {} during batch removal with shardEnd {}", sourceShard, shardEnd); } updateShardMetaBatch.mergeShallow( edgeShardSerialization.writeShardMeta(scope, sourceShard, edgeMeta)); // on purpose block this thread before deleting the old edges to be sure there are no gaps // duplicates are filtered on graph seeking so this is OK Thread.sleep(1000); if(logger.isTraceEnabled()) { logger.trace("Deleting batch of {} from old shard", maxWorkSize); } deleteRowBatch.withAtomicBatch(true).execute(); updateShardMetaBatch.execute(); } catch ( Throwable t ) { logger.error( "Unable to move edges from shard {} to shard {}", sourceShard, targetShard ); } totalEdgeCount += edgeCount; edgeCount = 0; } } totalEdgeCount += edgeCount; try { // write the edges into the new shard atomically so we know they all succeed newRowBatch.withAtomicBatch(true).execute(); // on purpose block this thread before deleting the old edges to be sure there are no gaps // duplicates are filtered on graph seeking so this is OK Thread.sleep(1000); if(logger.isTraceEnabled()) { logger.trace("Deleting remaining {} edges from old shard", edgeCount); } deleteRowBatch.withAtomicBatch(true).execute(); if (shardEnd != null){ sourceShard.setShardEnd( Optional.of(new DirectedEdge(shardEnd.getTargetNode(), shardEnd.getTimestamp())) ); if(logger.isTraceEnabled()) { logger.trace("Updating for last time shard {} with shardEnd {}", sourceShard, shardEnd); } updateShardMetaBatch.mergeShallow( edgeShardSerialization.writeShardMeta(scope, sourceShard, edgeMeta)); updateShardMetaBatch.execute(); } } catch ( Throwable t ) { logger.error( "Unable to move edges to target shard {}", targetShard ); } } if (logger.isTraceEnabled()) { logger.trace("Finished compacting {} shards and moved {} edges", sourceShards, totalEdgeCount); } logger.info("Finished compacting {} shards and moved {} edges", sourceShards, totalEdgeCount); resultBuilder.withCopiedEdges( totalEdgeCount ).withSourceShards( sourceShards ).withTargetShard( targetShard ); /** * We didn't move anything this pass, mark the shard as compacted. If we move something, * it means that we missed it on the first pass * or someone is still not writing to the target shard only. */ if ( totalEdgeCount == 0 ) { //now that we've marked our target as compacted, we can successfully remove any shards that are not // compacted themselves in the sources final MutationBatch shardRemovalRollup = keyspace.prepareMutationBatch(); for ( Shard source : sourceShards ) { //if we can't safely delete it, don't do so if ( !group.canBeDeleted( source ) ) { continue; } logger.info( "Source shards have been fully drained. Removing shard {}", source ); final MutationBatch shardRemoval = edgeShardSerialization.removeShardMeta( scope, source, edgeMeta ); shardRemovalRollup.mergeShallow( shardRemoval ); resultBuilder.withRemovedShard( source ); } try { shardRemovalRollup.execute(); } catch ( ConnectionException e ) { throw new RuntimeException( "Unable to connect to cassandra", e ); } //Overwrite our shard index with a newly created one that has been marked as compacted Shard compactedShard = new Shard( targetShard.getShardIndex(), timeService.getCurrentTime(), true ); compactedShard.setShardEnd(targetShard.getShardEnd()); logger.info( "Shard has been fully compacted. Marking shard {} as compacted in Cassandra", compactedShard ); final MutationBatch updateMark = edgeShardSerialization.writeShardMeta( scope, compactedShard, edgeMeta ); try { updateMark.execute(); } catch ( ConnectionException e ) { throw new RuntimeException( "Unable to connect to cassandra", e ); } resultBuilder.withCompactedShard( compactedShard ); } return resultBuilder.build(); } @Override public ListenableFuture<AuditResult> evaluateShardGroup( final ApplicationScope scope, final DirectedEdgeMeta edgeMeta, final ShardEntryGroup group ) { final double repairChance = random.nextDouble(); //don't audit, we didn't hit our chance if ( repairChance > graphFig.getShardRepairChance() ) { return Futures.immediateFuture( AuditResult.NOT_CHECKED ); } countAudits.getAndIncrement(); if(logger.isTraceEnabled()) { logger.trace("Auditing shard group {}. count is {} ", group, countAudits.get()); } /** * Try and submit. During back pressure, we may not be able to submit, that's ok. Better to drop than to * hose the system */ final ListenableFuture<AuditResult> future; try { future = taskExecutor.submit( new ShardAuditTask( scope, edgeMeta, group ) ); } catch ( RejectedExecutionException ree ) { //ignore, if this happens we don't care, we're saturated, we can check later logger.info( "Rejected audit for shard of scope {} edge, meta {} and group {}", scope, edgeMeta, group ); return Futures.immediateFuture( AuditResult.NOT_CHECKED ); } /** * Log our success or failures for debugging purposes */ Futures.addCallback( future, new FutureCallback<AuditResult>() { @Override public void onSuccess( @Nullable final AuditResult result ) { if (logger.isTraceEnabled()) { logger.trace("Successfully completed audit of task {}", result); } } @Override public void onFailure( final Throwable t ) { logger.error( "Unable to perform audit. Exception is ", t ); } } ); return future; } private final class ShardAuditTask implements Callable<AuditResult> { private final ApplicationScope scope; private final DirectedEdgeMeta edgeMeta; private final ShardEntryGroup group; public ShardAuditTask( final ApplicationScope scope, final DirectedEdgeMeta edgeMeta, final ShardEntryGroup group ) { this.scope = scope; this.edgeMeta = edgeMeta; this.group = group; } @Override public AuditResult call() throws Exception { /** * We don't have a compaction pending. Run an audit on the shards */ if ( !group.isCompactionPending() ) { /** * Check if we should allocate, we may want to */ /** * It's already compacting, don't do anything */ if ( !shardAuditTaskTracker.canStartTask( scope, edgeMeta, group ) ) { return AuditResult.CHECKED_NO_OP; } try { final boolean created = nodeShardAllocation.auditShard( scope, group, edgeMeta ); if ( !created ) { return AuditResult.CHECKED_NO_OP; } } finally { shardAuditTaskTracker.complete( scope, edgeMeta, group ); } return AuditResult.CHECKED_CREATED; } //check our taskmanager /** * Do the compaction */ if ( group.shouldCompact( timeService.getCurrentTime() ) ) { /** * It's already compacting, don't do anything */ if ( !shardCompactionTaskTracker.canStartTask( scope, edgeMeta, group ) ) { if(logger.isTraceEnabled()) { logger.trace("Already compacting, won't compact group: {}", group); } return AuditResult.COMPACTING; } /** * We use a finally b/c we always want to remove the task track */ try { CompactionResult result = compact( scope, edgeMeta, group ); logger.info( "Compaction result for compaction of scope {} with edge meta data of {} and shard group {} is {}", scope, edgeMeta, group, result ); } finally { shardCompactionTaskTracker.complete( scope, edgeMeta, group ); } return AuditResult.COMPACTED; } //no op, there's nothing we need to do to this shard return AuditResult.NOT_CHECKED; } } /** * Inner class used to track running tasks per instance */ private static abstract class TaskTracker { private static final Boolean TRUE = true; private ConcurrentHashMap<Long, Boolean> runningTasks = new ConcurrentHashMap<>(); /** * Sets this data into our scope to signal it's running to stop other threads from attempting to run */ public boolean canStartTask( final ApplicationScope scope, final DirectedEdgeMeta edgeMeta, ShardEntryGroup group ) { final Long hash = doHash( scope, edgeMeta, group ).hash().asLong(); final Boolean returned = runningTasks.putIfAbsent( hash, TRUE ); //logger.info("hash components are app: {}, edgeMeta: {}, group: {}", scope.getApplication(), edgeMeta, group); //logger.info("checking hash value of: {}, already started: {}", hash, returned ); /** * Someone already put the value */ return returned == null; } /** * Mark this entry group as complete */ public void complete( final ApplicationScope scope, final DirectedEdgeMeta edgeMeta, ShardEntryGroup group ) { final long hash = doHash( scope, edgeMeta, group ).hash().asLong(); runningTasks.remove( hash ); } protected abstract Hasher doHash( final ApplicationScope scope, final DirectedEdgeMeta directedEdgeMeta, final ShardEntryGroup shardEntryGroup ); } /** * Task tracker for shard compaction */ private static final class ShardCompactionTaskTracker extends ShardAuditTaskTracker { /** * Hash our data into a consistent long */ @Override protected Hasher doHash( final ApplicationScope scope, final DirectedEdgeMeta directedEdgeMeta, final ShardEntryGroup shardEntryGroup ) { final Hasher hasher = super.doHash( scope, directedEdgeMeta, shardEntryGroup ); // add the compaction target to the hash final Shard compactionTarget = shardEntryGroup.getCompactionTarget(); hasher.putLong( compactionTarget.getShardIndex() ); return hasher; } } /** * Task tracker for shard audit */ private static class ShardAuditTaskTracker extends TaskTracker { /** * Hash our data into a consistent long */ protected Hasher doHash( final ApplicationScope scope, final DirectedEdgeMeta directedEdgeMeta, final ShardEntryGroup shardEntryGroup ) { final Hasher hasher = MURMUR_128.newHasher(); addToHash( hasher, scope.getApplication() ); /** Commenting the full meta from the hash so we allocate/compact shards in a more controlled fashion for ( DirectedEdgeMeta.NodeMeta nodeMeta : directedEdgeMeta.getNodes() ) { addToHash( hasher, nodeMeta.getId() ); hasher.putInt( nodeMeta.getNodeType().getStorageValue() ); } **/ /** * Add our edge type */ for ( String type : directedEdgeMeta.getTypes() ) { hasher.putString( type, CHARSET ); } return hasher; } protected void addToHash( final PrimitiveSink into, final Id id ) { final UUID nodeUuid = id.getUuid(); final String nodeType = id.getType(); into.putLong( nodeUuid.getMostSignificantBits() ).putLong( nodeUuid.getLeastSignificantBits() ) .putString( nodeType, CHARSET ); } } public static final class CompactionResult { public final long copiedEdges; public final Shard targetShard; public final Set<Shard> sourceShards; public final Set<Shard> removedShards; public final Shard compactedShard; private CompactionResult( final long copiedEdges, final Shard targetShard, final Set<Shard> sourceShards, final Set<Shard> removedShards, final Shard compactedShard ) { this.copiedEdges = copiedEdges; this.targetShard = targetShard; this.compactedShard = compactedShard; this.sourceShards = Collections.unmodifiableSet( sourceShards ); this.removedShards = Collections.unmodifiableSet( removedShards ); } /** * Create a builder to use to create the result */ public static CompactionBuilder builder() { return new CompactionBuilder(); } @Override public String toString() { return "CompactionResult{" + "copiedEdges=" + copiedEdges + ", targetShard=" + targetShard + ", sourceShards=" + sourceShards + ", removedShards=" + removedShards + ", compactedShard=" + compactedShard + '}'; } public static final class CompactionBuilder { private long copiedEdges; private Shard targetShard; private Set<Shard> sourceShards; private Set<Shard> removedShards = new HashSet<>(); private Shard compactedShard; public CompactionBuilder withCopiedEdges( final long copiedEdges ) { this.copiedEdges = copiedEdges; return this; } public CompactionBuilder withTargetShard( final Shard targetShard ) { this.targetShard = targetShard; return this; } public CompactionBuilder withSourceShards( final Set<Shard> sourceShards ) { this.sourceShards = sourceShards; return this; } public CompactionBuilder withRemovedShard( final Shard removedShard ) { this.removedShards.add( removedShard ); return this; } public CompactionBuilder withCompactedShard( final Shard compactedShard ) { this.compactedShard = compactedShard; return this; } public CompactionResult build() { return new CompactionResult( copiedEdges, targetShard, sourceShards, removedShards, compactedShard ); } } } }
stack/corepersistence/graph/src/main/java/org/apache/usergrid/persistence/graph/serialization/impl/shard/impl/ShardGroupCompactionImpl.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.usergrid.persistence.graph.serialization.impl.shard.impl; import java.nio.charset.Charset; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import javax.annotation.Nullable; import com.google.common.base.Optional; import com.netflix.astyanax.connectionpool.OperationResult; import org.apache.usergrid.persistence.core.astyanax.ScopedRowKey; import org.apache.usergrid.persistence.graph.Edge; import org.apache.usergrid.persistence.graph.serialization.impl.shard.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.usergrid.persistence.core.consistency.TimeService; import org.apache.usergrid.persistence.core.scope.ApplicationScope; import org.apache.usergrid.persistence.graph.GraphFig; import org.apache.usergrid.persistence.graph.MarkedEdge; import org.apache.usergrid.persistence.graph.SearchByEdgeType; import org.apache.usergrid.persistence.model.entity.Id; import org.apache.usergrid.persistence.model.util.UUIDGenerator; import com.google.common.base.Preconditions; import com.google.common.hash.HashFunction; import com.google.common.hash.Hasher; import com.google.common.hash.Hashing; import com.google.common.hash.PrimitiveSink; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.inject.Inject; import com.google.inject.Singleton; import com.netflix.astyanax.Keyspace; import com.netflix.astyanax.MutationBatch; import com.netflix.astyanax.connectionpool.exceptions.ConnectionException; import rx.Observable; import rx.schedulers.Schedulers; /** * Implementation of the shard group compaction */ @Singleton public class ShardGroupCompactionImpl implements ShardGroupCompaction { private final AtomicLong countAudits; private static final Logger logger = LoggerFactory.getLogger( ShardGroupCompactionImpl.class ); private static final Charset CHARSET = Charset.forName( "UTF-8" ); private static final HashFunction MURMUR_128 = Hashing.murmur3_128(); private final ListeningExecutorService taskExecutor; private final TimeService timeService; private final GraphFig graphFig; private final NodeShardAllocation nodeShardAllocation; private final ShardedEdgeSerialization shardedEdgeSerialization; private final EdgeColumnFamilies edgeColumnFamilies; private final Keyspace keyspace; private final EdgeShardSerialization edgeShardSerialization; private final Random random; private final ShardCompactionTaskTracker shardCompactionTaskTracker; private final ShardAuditTaskTracker shardAuditTaskTracker; @Inject public ShardGroupCompactionImpl( final TimeService timeService, final GraphFig graphFig, final NodeShardAllocation nodeShardAllocation, final ShardedEdgeSerialization shardedEdgeSerialization, final EdgeColumnFamilies edgeColumnFamilies, final Keyspace keyspace, final EdgeShardSerialization edgeShardSerialization, final AsyncTaskExecutor asyncTaskExecutor) { this.timeService = timeService; this.countAudits = new AtomicLong(); this.graphFig = graphFig; this.nodeShardAllocation = nodeShardAllocation; this.shardedEdgeSerialization = shardedEdgeSerialization; this.edgeColumnFamilies = edgeColumnFamilies; this.keyspace = keyspace; this.edgeShardSerialization = edgeShardSerialization; this.random = new Random(); this.shardCompactionTaskTracker = new ShardCompactionTaskTracker(); this.shardAuditTaskTracker = new ShardAuditTaskTracker(); this.taskExecutor = asyncTaskExecutor.getExecutorService(); } /** * Execute the compaction task. Will return the status the operations performed * * @param group The shard entry group to compact * * @return The result of the compaction operation */ public CompactionResult compact( final ApplicationScope scope, final DirectedEdgeMeta edgeMeta, final ShardEntryGroup group ) { final long startTime = timeService.getCurrentTime(); Preconditions.checkNotNull( group, "group cannot be null" ); Preconditions.checkArgument( group.isCompactionPending(), "Compaction is pending" ); Preconditions .checkArgument( group.shouldCompact( startTime ), "Compaction cannot be run yet. Ignoring compaction." ); if(logger.isTraceEnabled()) { logger.trace("Compacting shard group. Audit count is {} ", countAudits.get()); } final CompactionResult.CompactionBuilder resultBuilder = CompactionResult.builder(); final Shard targetShard = group.getCompactionTarget(); final Set<Shard> sourceShards = new HashSet<>( group.getReadShards() ); //remove the target sourceShards.remove( targetShard ); final UUID timestamp = UUIDGenerator.newTimeUUID(); final long newShardPivot = targetShard.getShardIndex(); final int maxWorkSize = graphFig.getScanPageSize(); /** * As we move edges, we want to keep track of it */ long totalEdgeCount = 0; for ( Shard sourceShard : sourceShards ) { final MutationBatch newRowBatch = keyspace.prepareMutationBatch(); final MutationBatch deleteRowBatch = keyspace.prepareMutationBatch(); final MutationBatch updateShardMetaBatch = keyspace.prepareMutationBatch(); long edgeCount = 0; Iterator<MarkedEdge> edges = edgeMeta .loadEdges( shardedEdgeSerialization, edgeColumnFamilies, scope, Collections.singleton( sourceShard ), Long.MAX_VALUE, SearchByEdgeType.Order.DESCENDING ); MarkedEdge shardEnd = null; while ( edges.hasNext() ) { final MarkedEdge edge = edges.next(); final long edgeTimestamp = edge.getTimestamp(); shardEnd = edge; /** * The edge is within a different shard, break */ if ( edgeTimestamp < newShardPivot ) { break; } newRowBatch.mergeShallow( edgeMeta .writeEdge( shardedEdgeSerialization, edgeColumnFamilies, scope, targetShard, edge, timestamp ) ); deleteRowBatch.mergeShallow( edgeMeta .deleteEdge( shardedEdgeSerialization, edgeColumnFamilies, scope, sourceShard, edge, timestamp ) ); edgeCount++; // if we're at our count, execute the mutation of writing the edges to the new row, then remove them // from the old rows if ( edgeCount % maxWorkSize == 0 ) { try { // write the edges into the new shard atomically so we know they all succeed newRowBatch.withAtomicBatch(true).execute(); // Update the shard end after each batch so any reads during transition stay as close to current sourceShard.setShardEnd( Optional.of(new DirectedEdge(shardEnd.getTargetNode(), shardEnd.getTimestamp())) ); if(logger.isTraceEnabled()) { logger.trace("Updating shard {} during batch removal with shardEnd {}", sourceShard, shardEnd); } updateShardMetaBatch.mergeShallow( edgeShardSerialization.writeShardMeta(scope, sourceShard, edgeMeta)); // on purpose block this thread before deleting the old edges to be sure there are no gaps // duplicates are filtered on graph seeking so this is OK Thread.sleep(1000); if(logger.isTraceEnabled()) { logger.trace("Deleting batch of {} from old shard", maxWorkSize); } deleteRowBatch.withAtomicBatch(true).execute(); updateShardMetaBatch.execute(); } catch ( Throwable t ) { logger.error( "Unable to move edges from shard {} to shard {}", sourceShard, targetShard ); } totalEdgeCount += edgeCount; edgeCount = 0; } } totalEdgeCount += edgeCount; try { // write the edges into the new shard atomically so we know they all succeed newRowBatch.withAtomicBatch(true).execute(); // on purpose block this thread before deleting the old edges to be sure there are no gaps // duplicates are filtered on graph seeking so this is OK Thread.sleep(1000); if(logger.isTraceEnabled()) { logger.trace("Deleting remaining {} edges from old shard", edgeCount); } deleteRowBatch.withAtomicBatch(true).execute(); if (shardEnd != null){ sourceShard.setShardEnd( Optional.of(new DirectedEdge(shardEnd.getTargetNode(), shardEnd.getTimestamp())) ); if(logger.isTraceEnabled()) { logger.trace("Updating for last time shard {} with shardEnd {}", sourceShard, shardEnd); } updateShardMetaBatch.mergeShallow( edgeShardSerialization.writeShardMeta(scope, sourceShard, edgeMeta)); updateShardMetaBatch.execute(); } } catch ( Throwable t ) { logger.error( "Unable to move edges to target shard {}", targetShard ); } } if (logger.isTraceEnabled()) { logger.trace("Finished compacting {} shards and moved {} edges", sourceShards, totalEdgeCount); } logger.info("Finished compacting {} shards and moved {} edges", sourceShards, totalEdgeCount); resultBuilder.withCopiedEdges( totalEdgeCount ).withSourceShards( sourceShards ).withTargetShard( targetShard ); /** * We didn't move anything this pass, mark the shard as compacted. If we move something, * it means that we missed it on the first pass * or someone is still not writing to the target shard only. */ if ( totalEdgeCount == 0 ) { //now that we've marked our target as compacted, we can successfully remove any shards that are not // compacted themselves in the sources final MutationBatch shardRemovalRollup = keyspace.prepareMutationBatch(); for ( Shard source : sourceShards ) { //if we can't safely delete it, don't do so if ( !group.canBeDeleted( source ) ) { continue; } logger.info( "Source shards have been fully drained. Removing shard {}", source ); final MutationBatch shardRemoval = edgeShardSerialization.removeShardMeta( scope, source, edgeMeta ); shardRemovalRollup.mergeShallow( shardRemoval ); resultBuilder.withRemovedShard( source ); } try { shardRemovalRollup.execute(); } catch ( ConnectionException e ) { throw new RuntimeException( "Unable to connect to cassandra", e ); } //Overwrite our shard index with a newly created one that has been marked as compacted Shard compactedShard = new Shard( targetShard.getShardIndex(), timeService.getCurrentTime(), true ); compactedShard.setShardEnd(targetShard.getShardEnd()); logger.info( "Shard has been fully compacted. Marking shard {} as compacted in Cassandra", compactedShard ); final MutationBatch updateMark = edgeShardSerialization.writeShardMeta( scope, compactedShard, edgeMeta ); try { updateMark.execute(); } catch ( ConnectionException e ) { throw new RuntimeException( "Unable to connect to cassandra", e ); } resultBuilder.withCompactedShard( compactedShard ); } return resultBuilder.build(); } @Override public ListenableFuture<AuditResult> evaluateShardGroup( final ApplicationScope scope, final DirectedEdgeMeta edgeMeta, final ShardEntryGroup group ) { final double repairChance = random.nextDouble(); //don't audit, we didn't hit our chance if ( repairChance > graphFig.getShardRepairChance() ) { return Futures.immediateFuture( AuditResult.NOT_CHECKED ); } countAudits.getAndIncrement(); if(logger.isTraceEnabled()) { logger.trace("Auditing shard group {}. count is {} ", group, countAudits.get()); } /** * Try and submit. During back pressure, we may not be able to submit, that's ok. Better to drop than to * hose the system */ final ListenableFuture<AuditResult> future; try { future = taskExecutor.submit( new ShardAuditTask( scope, edgeMeta, group ) ); } catch ( RejectedExecutionException ree ) { //ignore, if this happens we don't care, we're saturated, we can check later logger.info( "Rejected audit for shard of scope {} edge, meta {} and group {}", scope, edgeMeta, group ); return Futures.immediateFuture( AuditResult.NOT_CHECKED ); } /** * Log our success or failures for debugging purposes */ Futures.addCallback( future, new FutureCallback<AuditResult>() { @Override public void onSuccess( @Nullable final AuditResult result ) { if (logger.isTraceEnabled()) { logger.trace("Successfully completed audit of task {}", result); } } @Override public void onFailure( final Throwable t ) { logger.error( "Unable to perform audit. Exception is ", t ); } } ); return future; } private final class ShardAuditTask implements Callable<AuditResult> { private final ApplicationScope scope; private final DirectedEdgeMeta edgeMeta; private final ShardEntryGroup group; public ShardAuditTask( final ApplicationScope scope, final DirectedEdgeMeta edgeMeta, final ShardEntryGroup group ) { this.scope = scope; this.edgeMeta = edgeMeta; this.group = group; } @Override public AuditResult call() throws Exception { /** * We don't have a compaction pending. Run an audit on the shards */ if ( !group.isCompactionPending() ) { /** * Check if we should allocate, we may want to */ /** * It's already compacting, don't do anything */ if ( !shardAuditTaskTracker.canStartTask( scope, edgeMeta, group ) ) { return AuditResult.CHECKED_NO_OP; } try { final boolean created = nodeShardAllocation.auditShard( scope, group, edgeMeta ); if ( !created ) { return AuditResult.CHECKED_NO_OP; } } finally { shardAuditTaskTracker.complete( scope, edgeMeta, group ); } return AuditResult.CHECKED_CREATED; } //check our taskmanager /** * Do the compaction */ if ( group.shouldCompact( timeService.getCurrentTime() ) ) { /** * It's already compacting, don't do anything */ if ( !shardCompactionTaskTracker.canStartTask( scope, edgeMeta, group ) ) { logger.info("the group is already compacting"); return AuditResult.COMPACTING; } /** * We use a finally b/c we always want to remove the task track */ try { CompactionResult result = compact( scope, edgeMeta, group ); logger.info( "Compaction result for compaction of scope {} with edge meta data of {} and shard group {} is {}", scope, edgeMeta, group, result ); } finally { shardCompactionTaskTracker.complete( scope, edgeMeta, group ); } return AuditResult.COMPACTED; } //no op, there's nothing we need to do to this shard return AuditResult.NOT_CHECKED; } } /** * Inner class used to track running tasks per instance */ private static abstract class TaskTracker { private static final Boolean TRUE = true; private ConcurrentHashMap<Long, Boolean> runningTasks = new ConcurrentHashMap<>(); /** * Sets this data into our scope to signal it's running to stop other threads from attempting to run */ public boolean canStartTask( final ApplicationScope scope, final DirectedEdgeMeta edgeMeta, ShardEntryGroup group ) { final Long hash = doHash( scope, edgeMeta, group ).hash().asLong(); final Boolean returned = runningTasks.putIfAbsent( hash, TRUE ); //logger.info("hash components are app: {}, edgeMeta: {}, group: {}", scope.getApplication(), edgeMeta, group); //logger.info("checking hash value of: {}, already started: {}", hash, returned ); /** * Someone already put the value */ return returned == null; } /** * Mark this entry group as complete */ public void complete( final ApplicationScope scope, final DirectedEdgeMeta edgeMeta, ShardEntryGroup group ) { final long hash = doHash( scope, edgeMeta, group ).hash().asLong(); runningTasks.remove( hash ); } protected abstract Hasher doHash( final ApplicationScope scope, final DirectedEdgeMeta directedEdgeMeta, final ShardEntryGroup shardEntryGroup ); } /** * Task tracker for shard compaction */ private static final class ShardCompactionTaskTracker extends ShardAuditTaskTracker { /** * Hash our data into a consistent long */ @Override protected Hasher doHash( final ApplicationScope scope, final DirectedEdgeMeta directedEdgeMeta, final ShardEntryGroup shardEntryGroup ) { final Hasher hasher = super.doHash( scope, directedEdgeMeta, shardEntryGroup ); // add the compaction target to the hash final Shard compactionTarget = shardEntryGroup.getCompactionTarget(); hasher.putLong( compactionTarget.getShardIndex() ); return hasher; } } /** * Task tracker for shard audit */ private static class ShardAuditTaskTracker extends TaskTracker { /** * Hash our data into a consistent long */ protected Hasher doHash( final ApplicationScope scope, final DirectedEdgeMeta directedEdgeMeta, final ShardEntryGroup shardEntryGroup ) { final Hasher hasher = MURMUR_128.newHasher(); addToHash( hasher, scope.getApplication() ); /** Commenting the full meta from the hash so we allocate/compact shards in a more controlled fashion for ( DirectedEdgeMeta.NodeMeta nodeMeta : directedEdgeMeta.getNodes() ) { addToHash( hasher, nodeMeta.getId() ); hasher.putInt( nodeMeta.getNodeType().getStorageValue() ); } **/ /** * Add our edge type */ for ( String type : directedEdgeMeta.getTypes() ) { hasher.putString( type, CHARSET ); } return hasher; } protected void addToHash( final PrimitiveSink into, final Id id ) { final UUID nodeUuid = id.getUuid(); final String nodeType = id.getType(); into.putLong( nodeUuid.getMostSignificantBits() ).putLong( nodeUuid.getLeastSignificantBits() ) .putString( nodeType, CHARSET ); } } public static final class CompactionResult { public final long copiedEdges; public final Shard targetShard; public final Set<Shard> sourceShards; public final Set<Shard> removedShards; public final Shard compactedShard; private CompactionResult( final long copiedEdges, final Shard targetShard, final Set<Shard> sourceShards, final Set<Shard> removedShards, final Shard compactedShard ) { this.copiedEdges = copiedEdges; this.targetShard = targetShard; this.compactedShard = compactedShard; this.sourceShards = Collections.unmodifiableSet( sourceShards ); this.removedShards = Collections.unmodifiableSet( removedShards ); } /** * Create a builder to use to create the result */ public static CompactionBuilder builder() { return new CompactionBuilder(); } @Override public String toString() { return "CompactionResult{" + "copiedEdges=" + copiedEdges + ", targetShard=" + targetShard + ", sourceShards=" + sourceShards + ", removedShards=" + removedShards + ", compactedShard=" + compactedShard + '}'; } public static final class CompactionBuilder { private long copiedEdges; private Shard targetShard; private Set<Shard> sourceShards; private Set<Shard> removedShards = new HashSet<>(); private Shard compactedShard; public CompactionBuilder withCopiedEdges( final long copiedEdges ) { this.copiedEdges = copiedEdges; return this; } public CompactionBuilder withTargetShard( final Shard targetShard ) { this.targetShard = targetShard; return this; } public CompactionBuilder withSourceShards( final Set<Shard> sourceShards ) { this.sourceShards = sourceShards; return this; } public CompactionBuilder withRemovedShard( final Shard removedShard ) { this.removedShards.add( removedShard ); return this; } public CompactionBuilder withCompactedShard( final Shard compactedShard ) { this.compactedShard = compactedShard; return this; } public CompactionResult build() { return new CompactionResult( copiedEdges, targetShard, sourceShards, removedShards, compactedShard ); } } } }
Fix info log statement to be trace.
stack/corepersistence/graph/src/main/java/org/apache/usergrid/persistence/graph/serialization/impl/shard/impl/ShardGroupCompactionImpl.java
Fix info log statement to be trace.
<ide><path>tack/corepersistence/graph/src/main/java/org/apache/usergrid/persistence/graph/serialization/impl/shard/impl/ShardGroupCompactionImpl.java <ide> * It's already compacting, don't do anything <ide> */ <ide> if ( !shardCompactionTaskTracker.canStartTask( scope, edgeMeta, group ) ) { <del> logger.info("the group is already compacting"); <add> <add> if(logger.isTraceEnabled()) { <add> logger.trace("Already compacting, won't compact group: {}", group); <add> } <add> <add> <ide> return AuditResult.COMPACTING; <ide> } <ide>
Java
mit
dc48576dae1834b86a7a3e06ebeb1e4ac6a663cf
0
Thatsmusic99/HeadsPlus
package io.github.thatsmusic99.headsplus.commands; import io.github.thatsmusic99.headsplus.HeadsPlus; import io.github.thatsmusic99.headsplus.api.HPPlayer; import io.github.thatsmusic99.headsplus.api.events.SellHeadEvent; import io.github.thatsmusic99.headsplus.commands.maincommand.DebugPrint; import io.github.thatsmusic99.headsplus.config.HeadsPlusConfigHeads; import io.github.thatsmusic99.headsplus.config.HeadsPlusMessagesManager; import io.github.thatsmusic99.headsplus.nms.NMSManager; import io.github.thatsmusic99.headsplus.reflection.NBTManager; import io.github.thatsmusic99.headsplus.util.CachedValues; import io.github.thatsmusic99.headsplus.util.InventoryManager; import net.milkbowl.vault.economy.Economy; import net.milkbowl.vault.economy.EconomyResponse; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @CommandInfo( commandname = "sellhead", permission = "headsplus.sellhead", subcommand = "sellead", maincommand = false, usage = "/sellhead [All|Entity|#] [#]" ) public class SellHead implements CommandExecutor, IHeadsPlusCommand { private final HeadsPlusConfigHeads hpch = HeadsPlus.getInstance().getHeadsConfig(); private final HeadsPlusMessagesManager hpc = HeadsPlus.getInstance().getMessagesConfig(); private final List<String> soldHeads = new ArrayList<>(); private final HashMap<String, Integer> hm = new HashMap<>(); public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { try { HeadsPlus hp = HeadsPlus.getInstance(); if (sender instanceof Player) { Player p = (Player) sender; if (hp.canSellHeads()) { soldHeads.clear(); hm.clear(); ItemStack invi = checkHand(p); if (args.length == 0 && (sender.hasPermission("headsplus.sellhead"))) { // If sold via hand if (hp.getConfiguration().getMechanics().getBoolean("sellhead-gui")) { InventoryManager.getOrCreate(p).showScreen(InventoryManager.Type.SELL); return true; } else { if (invi != null) { if (NBTManager.isSellable(invi)) { String s = NBTManager.getType(invi).toLowerCase(); if (hpch.mHeads.contains(s) || hpch.uHeads.contains(s) || s.equalsIgnoreCase("player")) { double price; if (invi.getAmount() > 0) { price = invi.getAmount() * nbt().getPrice(invi); soldHeads.add(s); hm.put(s, invi.getAmount()); double balance = HeadsPlus.getInstance().getEconomy().getBalance(p); SellHeadEvent she = new SellHeadEvent(price, soldHeads, p, balance, balance + price, hm); Bukkit.getServer().getPluginManager().callEvent(she); if (!she.isCancelled()) { EconomyResponse zr = HeadsPlus.getInstance().getEconomy().depositPlayer(p, price); String success = hpc.getString("commands.sellhead.sell-success", p).replaceAll("\\{price}", Double.toString(price)).replaceAll("\\{balance}", HeadsPlus.getInstance().getConfiguration().fixBalanceStr(zr.balance)); if (zr.transactionSuccess()) { if (price > 0) { itemRemoval(p, args, -1); sender.sendMessage(success); return true; } } else { sender.sendMessage(hpc.getString("commands.errors.cmd-fail", p)); } } } } } else { sender.sendMessage(hpc.getString("commands.sellhead.false-head", p)); return true; } } else { sender.sendMessage(hpc.getString("commands.sellhead.false-head", p)); return true; } } } else { if (!p.hasPermission("headsplus.sellhead")) { p.sendMessage(hpc.getString("commands.errors.no-perm", p)); } else { if (args[0].equalsIgnoreCase("all")) { sellAll(p, args); } else { double price = 0.0; int limit = -1; if (args.length > 1 && CachedValues.MATCH_PAGE.matcher(args[1]).matches()) { limit = Integer.parseInt(args[1]); } int is = 0; for (ItemStack i : p.getInventory()) { if (i != null) { if (NBTManager.isSellable(i)) { String st = NBTManager.getType(i).toLowerCase(); if (st.equalsIgnoreCase(args[0])) { if (is != limit) { price = setPrice(price, args, i, p, limit); ++is; } } } } } if (HeadsPlus.getInstance().getNMSVersion().getOrder() < 4) { ItemStack i = p.getInventory().getHelmet(); if (i != null) { if (NBTManager.isSellable(i)) { String st = NBTManager.getType(i).toLowerCase(); if (st.equalsIgnoreCase(args[0])) { if (is != limit) { price = setPrice(price, args, i, p, limit); } } } } } ItemStack is2 = nms().getOffHand(p); if (is2 != null) { if (NBTManager.isSellable(is2)) { String st = NBTManager.getType(is2).toLowerCase(); if (st.equalsIgnoreCase(args[0])) { if (is != limit) { price = setPrice(price, args, is2, p, limit); } } } } if (price == 0.0) { sender.sendMessage(hpc.getString("commands.sellhead.no-heads", p)); return true; } pay(p, args, price, limit); return true; } } } } else { sender.sendMessage(hpc.getString("commands.errors.disabled", p)); } } else { sender.sendMessage("[HeadsPlus] You must be a player to run this command!"); } } catch (Exception e) { DebugPrint.createReport(e, "Command (sellhead)", true, sender); } return false; } @SuppressWarnings("deprecation") private static ItemStack checkHand(Player p) { if (Bukkit.getVersion().contains("1.8")) { return p.getInventory().getItemInHand(); } else { return p.getInventory().getItemInMainHand(); } } @SuppressWarnings("deprecation") private void setHand(Player p, ItemStack i) { if (Bukkit.getVersion().contains("1.8")) { p.getInventory().setItemInHand(i); } else { p.getInventory().setItemInMainHand(i); } } private void itemRemoval(Player p, String[] a, int limit) { int l = limit; if (a.length > 0) { if (p.getInventory().getHelmet() != null) { ItemStack is = p.getInventory().getHelmet(); if (NBTManager.isSellable(is) && !NBTManager.getType(is).isEmpty()) { if (a[0].equalsIgnoreCase("all") || NBTManager.getType(is).equalsIgnoreCase(a[0])) { if (is.getAmount() > l && l != -1) { is.setAmount(is.getAmount() - l); l = 0; } else { p.getInventory().setHelmet(new ItemStack(Material.AIR)); HPPlayer hp = HPPlayer.getHPPlayer(p); hp.clearMask(); if (l != -1) { l = is.getAmount() - l; } } } } } if (nms().getOffHand(p) != null) { ItemStack is = nms().getOffHand(p); if (NBTManager.isSellable(is) && !NBTManager.getType(is).isEmpty()) { if (a[0].equalsIgnoreCase("all") || NBTManager.getType(is).equalsIgnoreCase(a[0])) { if (is.getAmount() > l && l != -1) { is.setAmount(is.getAmount() - l); l = 0; } else { p.getInventory().setItemInOffHand(new ItemStack(Material.AIR)); if (l != -1) { l = is.getAmount() - l; } } } } } for (ItemStack is : p.getInventory()) { if (is != null) { if (NBTManager.isSellable(is) && !NBTManager.getType(is).isEmpty()) { if (!a[0].equalsIgnoreCase("all")) { if (!NBTManager.getType(is).equalsIgnoreCase(a[0])) continue; } if (is.getAmount() > l && l != -1) { is.setAmount(is.getAmount() - l); l = 0; } else if (l > 0) { p.getInventory().remove(is); l = l - is.getAmount(); if (l <= -1) { l = 0; } } else if (l == -1){ p.getInventory().remove(is); } } } } } else { setHand(p, new ItemStack(Material.AIR)); } } private double setPrice(Double p, String[] a, ItemStack i, Player pl, int limit) { if (a.length > 0) { // More than one argument if (!CachedValues.MATCH_PAGE.matcher(a[0]).matches()) { // More than one head if (a[0].equalsIgnoreCase("all")) { // Sell everything if (NBTManager.isSellable(i)) { String s = NBTManager.getType(i).toLowerCase(); if (hpch.mHeads.contains(s) || hpch.uHeads.contains(s) || s.equalsIgnoreCase("player")) { soldHeads.add(s); int o = i(s, i.getAmount(), limit, false); p += o * NBTManager.getPrice(i); } } } else { // Selected mob p = f(i, p, a[0], limit); } } else { if (Integer.parseInt(a[0]) <= i.getAmount()) { if (NBTManager.isSellable(i)) { String s = NBTManager.getType(i); if (hpch.mHeads.contains(s) || hpch.uHeads.contains(s) || s.equalsIgnoreCase("player")) { p = NBTManager.getPrice(i) * Integer.parseInt(a[0]); soldHeads.add(s); i(s, i.getAmount(), limit, false); } } } else { pl.sendMessage(hpc.getString("commands.sellhead.not-enough-heads", pl)); } } } return p; } private void sellAll(Player p, String[] a) { Double price = 0.0; if (HeadsPlus.getInstance().getNMSVersion().getOrder() < 4) { ItemStack i = p.getInventory().getHelmet(); if (i != null) { if (NBTManager.isSellable(i)) { price = setPrice(price, a, i, p, -1); } } } /* ItemStack is2 = nms().getOffHand(p); if (is2 != null) { if (nms().isSellable(is2)) { price = setPrice(price, a, is2, p, -1); } } */ for (ItemStack is : p.getInventory()) { if (is != null) { price = setPrice(price, a, is, p, -1); } } if (price == 0) { p.sendMessage(hpc.getString("commands.sellhead.no-heads", p)); return; } pay(p, a, price, -1); } private void pay(Player p, String[] a, double pr, int limit) { Economy econ = HeadsPlus.getInstance().getEconomy(); SellHeadEvent she = new SellHeadEvent(pr, soldHeads, p, econ.getBalance(p), econ.getBalance(p) + pr, hm); Bukkit.getServer().getPluginManager().callEvent(she); if (!she.isCancelled()) { EconomyResponse zr = econ.depositPlayer(p, pr); String success = hpc.getString("commands.sellhead.sell-success", p).replaceAll("\\{price}", Double.toString(pr)).replaceAll("\\{balance}", HeadsPlus.getInstance().getConfiguration().fixBalanceStr(zr.balance)); if (zr.transactionSuccess()) { itemRemoval(p, a, limit); p.sendMessage(success); } else { p.sendMessage(hpc.getString("commands.errors.cmd-fail", p)); } } } private Double f(ItemStack i, Double p, String s, int l) { String st = NBTManager.getType(i).toLowerCase(); if (NBTManager.isSellable(i)) { if (st.equalsIgnoreCase(s)) { soldHeads.add(s); int o = i(s, i.getAmount(), l, true); p = (o * NBTManager.getPrice(i)); } } return p; } private int i(String s, int amount, int l, boolean g) { if (hm.get(s) == null) { if (amount > l && l != -1) { hm.put(s, l); return l; } else { hm.put(s, amount); return amount; } } if (hm.get(s) > 0) { int i = hm.get(s); i += amount; if (i > l && l != -1) { hm.put(s, l); return l; } else { hm.put(s, i); return g ? i : amount; } } else { if (amount > l && l != -1) { hm.put(s, l); return l; } else { hm.put(s, amount); return amount; } } } @Override public String getCmdDescription(CommandSender sender) { return HeadsPlus.getInstance().getMessagesConfig().getString("descriptions.sellhead", sender); } @Override public boolean fire(String[] args, CommandSender sender) { return false; } @Override public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, @NotNull String[] args) { return new ArrayList<>(); } private NMSManager nms() { return HeadsPlus.getInstance().getNMS(); } private NBTManager nbt() { return HeadsPlus.getInstance().getNBTManager(); } }
src/main/java/io/github/thatsmusic99/headsplus/commands/SellHead.java
package io.github.thatsmusic99.headsplus.commands; import io.github.thatsmusic99.headsplus.HeadsPlus; import io.github.thatsmusic99.headsplus.api.HPPlayer; import io.github.thatsmusic99.headsplus.api.events.SellHeadEvent; import io.github.thatsmusic99.headsplus.commands.maincommand.DebugPrint; import io.github.thatsmusic99.headsplus.config.HeadsPlusConfigHeads; import io.github.thatsmusic99.headsplus.config.HeadsPlusMessagesManager; import io.github.thatsmusic99.headsplus.nms.NMSManager; import io.github.thatsmusic99.headsplus.reflection.NBTManager; import io.github.thatsmusic99.headsplus.util.CachedValues; import io.github.thatsmusic99.headsplus.util.InventoryManager; import net.milkbowl.vault.economy.Economy; import net.milkbowl.vault.economy.EconomyResponse; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @CommandInfo( commandname = "sellhead", permission = "headsplus.sellhead", subcommand = "sellead", maincommand = false, usage = "/sellhead [All|Entity|#] [#]" ) public class SellHead implements CommandExecutor, IHeadsPlusCommand { private final HeadsPlusConfigHeads hpch = HeadsPlus.getInstance().getHeadsConfig(); private final HeadsPlusMessagesManager hpc = HeadsPlus.getInstance().getMessagesConfig(); private final List<String> soldHeads = new ArrayList<>(); private final HashMap<String, Integer> hm = new HashMap<>(); public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { try { HeadsPlus hp = HeadsPlus.getInstance(); if (sender instanceof Player) { Player p = (Player) sender; if (hp.canSellHeads()) { soldHeads.clear(); hm.clear(); ItemStack invi = checkHand(p); if (args.length == 0 && (sender.hasPermission("headsplus.sellhead"))) { // If sold via hand if (hp.getConfiguration().getMechanics().getBoolean("sellhead-gui")) { InventoryManager.getOrCreate(p).showScreen(InventoryManager.Type.SELL); return true; } else { if (invi != null) { if (NBTManager.isSellable(invi)) { String s = NBTManager.getType(invi).toLowerCase(); if (hpch.mHeads.contains(s) || hpch.uHeads.contains(s) || s.equalsIgnoreCase("player")) { double price; if (invi.getAmount() > 0) { price = invi.getAmount() * nbt().getPrice(invi); soldHeads.add(s); hm.put(s, invi.getAmount()); double balance = HeadsPlus.getInstance().getEconomy().getBalance(p); SellHeadEvent she = new SellHeadEvent(price, soldHeads, p, balance, balance + price, hm); Bukkit.getServer().getPluginManager().callEvent(she); if (!she.isCancelled()) { EconomyResponse zr = HeadsPlus.getInstance().getEconomy().depositPlayer(p, price); String success = hpc.getString("commands.sellhead.sell-success", p).replaceAll("\\{price}", Double.toString(price)).replaceAll("\\{balance}", HeadsPlus.getInstance().getConfiguration().fixBalanceStr(zr.balance)); if (zr.transactionSuccess()) { if (price > 0) { itemRemoval(p, args, -1); sender.sendMessage(success); return true; } } else { sender.sendMessage(hpc.getString("commands.errors.cmd-fail", p)); } } } } } else { sender.sendMessage(hpc.getString("commands.sellhead.false-head", p)); return true; } } else { sender.sendMessage(hpc.getString("commands.sellhead.false-head", p)); return true; } } } else { if (args.length > 1 && CachedValues.MATCH_PAGE.matcher(args[1]).matches()) { if (!p.hasPermission("headsplus.sellhead")) { p.sendMessage(hpc.getString("commands.errors.no-perm", p)); } else { if (args[0].equalsIgnoreCase("all")) { sellAll(p, args); } else { double price = 0.0; int limit = -1; if (CachedValues.MATCH_PAGE.matcher(args[1]).matches()) { limit = Integer.parseInt(args[1]); } int is = 0; for (ItemStack i : p.getInventory()) { if (i != null) { // boolean found = false; if (NBTManager.isSellable(i)) { String st = NBTManager.getType(i).toLowerCase(); if (st.equalsIgnoreCase(args[0])) { if (is != limit) { price = setPrice(price, args, i, p, limit); ++is; } } } } } if (HeadsPlus.getInstance().getNMSVersion().getOrder() < 4) { ItemStack i = p.getInventory().getHelmet(); if (i != null) { if (NBTManager.isSellable(i)) { String st = NBTManager.getType(i).toLowerCase(); if (st.equalsIgnoreCase(args[0])) { if (is != limit) { price = setPrice(price, args, i, p, limit); } } } } } ItemStack is2 = nms().getOffHand(p); if (is2 != null) { if (NBTManager.isSellable(is2)) { String st = NBTManager.getType(is2).toLowerCase(); if (st.equalsIgnoreCase(args[0])) { if (is != limit) { price = setPrice(price, args, is2, p, limit); } } } } if (price == 0.0) { sender.sendMessage(hpc.getString("commands.sellhead.no-heads", p)); return true; } pay(p, args, price, limit); return true; } } } else { sender.sendMessage(hpc.getString("commands.head.alpha-names", p)); } } } else { sender.sendMessage(hpc.getString("commands.errors.disabled", p)); } } else { sender.sendMessage("[HeadsPlus] You must be a player to run this command!"); } } catch (Exception e) { DebugPrint.createReport(e, "Command (sellhead)", true, sender); } return false; } @SuppressWarnings("deprecation") private static ItemStack checkHand(Player p) { if (Bukkit.getVersion().contains("1.8")) { return p.getInventory().getItemInHand(); } else { return p.getInventory().getItemInMainHand(); } } @SuppressWarnings("deprecation") private void setHand(Player p, ItemStack i) { if (Bukkit.getVersion().contains("1.8")) { p.getInventory().setItemInHand(i); } else { p.getInventory().setItemInMainHand(i); } } private void itemRemoval(Player p, String[] a, int limit) { int l = limit; if (a.length > 0) { if (p.getInventory().getHelmet() != null) { ItemStack is = p.getInventory().getHelmet(); if (NBTManager.isSellable(is) && !NBTManager.getType(is).isEmpty()) { if (a[0].equalsIgnoreCase("all") || NBTManager.getType(is).equalsIgnoreCase(a[0])) { if (is.getAmount() > l && l != -1) { is.setAmount(is.getAmount() - l); l = 0; } else { p.getInventory().setHelmet(new ItemStack(Material.AIR)); HPPlayer hp = HPPlayer.getHPPlayer(p); hp.clearMask(); if (l != -1) { l = is.getAmount() - l; } } } } } if (nms().getOffHand(p) != null) { ItemStack is = nms().getOffHand(p); if (NBTManager.isSellable(is) && !NBTManager.getType(is).isEmpty()) { if (a[0].equalsIgnoreCase("all") || NBTManager.getType(is).equalsIgnoreCase(a[0])) { if (is.getAmount() > l && l != -1) { is.setAmount(is.getAmount() - l); l = 0; } else { p.getInventory().setItemInOffHand(new ItemStack(Material.AIR)); if (l != -1) { l = is.getAmount() - l; } } } } } for (ItemStack is : p.getInventory()) { if (is != null) { if (NBTManager.isSellable(is) && !NBTManager.getType(is).isEmpty()) { if (!a[0].equalsIgnoreCase("all")) { if (!NBTManager.getType(is).equalsIgnoreCase(a[0])) continue; } if (is.getAmount() > l && l != -1) { is.setAmount(is.getAmount() - l); l = 0; } else if (l > 0) { p.getInventory().remove(is); l = l - is.getAmount(); if (l <= -1) { l = 0; } } else if (l == -1){ p.getInventory().remove(is); } } } } } else { setHand(p, new ItemStack(Material.AIR)); } } private double setPrice(Double p, String[] a, ItemStack i, Player pl, int limit) { if (a.length > 0) { // More than one argument if (!CachedValues.MATCH_PAGE.matcher(a[0]).matches()) { // More than one head if (a[0].equalsIgnoreCase("all")) { // Sell everything if (NBTManager.isSellable(i)) { String s = NBTManager.getType(i).toLowerCase(); if (hpch.mHeads.contains(s) || hpch.uHeads.contains(s) || s.equalsIgnoreCase("player")) { soldHeads.add(s); int o = i(s, i.getAmount(), limit, false); p += o * NBTManager.getPrice(i); } } } else { // Selected mob p = f(i, p, a[0], limit); } } else { if (Integer.parseInt(a[0]) <= i.getAmount()) { if (NBTManager.isSellable(i)) { String s = NBTManager.getType(i); if (hpch.mHeads.contains(s) || hpch.uHeads.contains(s) || s.equalsIgnoreCase("player")) { p = NBTManager.getPrice(i) * Integer.parseInt(a[0]); soldHeads.add(s); i(s, i.getAmount(), limit, false); } } } else { pl.sendMessage(hpc.getString("commands.sellhead.not-enough-heads", pl)); } } } return p; } private void sellAll(Player p, String[] a) { Double price = 0.0; if (HeadsPlus.getInstance().getNMSVersion().getOrder() < 4) { ItemStack i = p.getInventory().getHelmet(); if (i != null) { if (NBTManager.isSellable(i)) { price = setPrice(price, a, i, p, -1); } } } /* ItemStack is2 = nms().getOffHand(p); if (is2 != null) { if (nms().isSellable(is2)) { price = setPrice(price, a, is2, p, -1); } } */ for (ItemStack is : p.getInventory()) { if (is != null) { price = setPrice(price, a, is, p, -1); } } if (price == 0) { p.sendMessage(hpc.getString("commands.sellhead.no-heads", p)); return; } pay(p, a, price, -1); } private void pay(Player p, String[] a, double pr, int limit) { Economy econ = HeadsPlus.getInstance().getEconomy(); SellHeadEvent she = new SellHeadEvent(pr, soldHeads, p, econ.getBalance(p), econ.getBalance(p) + pr, hm); Bukkit.getServer().getPluginManager().callEvent(she); if (!she.isCancelled()) { EconomyResponse zr = econ.depositPlayer(p, pr); String success = hpc.getString("commands.sellhead.sell-success", p).replaceAll("\\{price}", Double.toString(pr)).replaceAll("\\{balance}", HeadsPlus.getInstance().getConfiguration().fixBalanceStr(zr.balance)); if (zr.transactionSuccess()) { itemRemoval(p, a, limit); p.sendMessage(success); } else { p.sendMessage(hpc.getString("commands.errors.cmd-fail", p)); } } } private Double f(ItemStack i, Double p, String s, int l) { String st = NBTManager.getType(i).toLowerCase(); if (NBTManager.isSellable(i)) { if (st.equalsIgnoreCase(s)) { soldHeads.add(s); int o = i(s, i.getAmount(), l, true); p = (o * NBTManager.getPrice(i)); } } return p; } private int i(String s, int amount, int l, boolean g) { if (hm.get(s) == null) { if (amount > l && l != -1) { hm.put(s, l); return l; } else { hm.put(s, amount); return amount; } } if (hm.get(s) > 0) { int i = hm.get(s); i += amount; if (i > l && l != -1) { hm.put(s, l); return l; } else { hm.put(s, i); return g ? i : amount; } } else { if (amount > l && l != -1) { hm.put(s, l); return l; } else { hm.put(s, amount); return amount; } } } @Override public String getCmdDescription(CommandSender sender) { return HeadsPlus.getInstance().getMessagesConfig().getString("descriptions.sellhead", sender); } @Override public boolean fire(String[] args, CommandSender sender) { return false; } @Override public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, @NotNull String[] args) { return new ArrayList<>(); } private NMSManager nms() { return HeadsPlus.getInstance().getNMS(); } private NBTManager nbt() { return HeadsPlus.getInstance().getNBTManager(); } }
Fixed /sellhead all not working
src/main/java/io/github/thatsmusic99/headsplus/commands/SellHead.java
Fixed /sellhead all not working
<ide><path>rc/main/java/io/github/thatsmusic99/headsplus/commands/SellHead.java <ide> } <ide> } <ide> } else { <del> if (args.length > 1 && CachedValues.MATCH_PAGE.matcher(args[1]).matches()) { <del> if (!p.hasPermission("headsplus.sellhead")) { <del> p.sendMessage(hpc.getString("commands.errors.no-perm", p)); <add> if (!p.hasPermission("headsplus.sellhead")) { <add> p.sendMessage(hpc.getString("commands.errors.no-perm", p)); <add> } else { <add> if (args[0].equalsIgnoreCase("all")) { <add> sellAll(p, args); <ide> } else { <del> if (args[0].equalsIgnoreCase("all")) { <del> sellAll(p, args); <del> } else { <del> double price = 0.0; <del> int limit = -1; <del> if (CachedValues.MATCH_PAGE.matcher(args[1]).matches()) { <del> limit = Integer.parseInt(args[1]); <del> } <del> int is = 0; <del> for (ItemStack i : p.getInventory()) { <del> if (i != null) { <del> // boolean found = false; <del> if (NBTManager.isSellable(i)) { <del> String st = NBTManager.getType(i).toLowerCase(); <del> if (st.equalsIgnoreCase(args[0])) { <del> if (is != limit) { <del> price = setPrice(price, args, i, p, limit); <del> ++is; <del> } <del> <add> double price = 0.0; <add> int limit = -1; <add> if (args.length > 1 && CachedValues.MATCH_PAGE.matcher(args[1]).matches()) { <add> limit = Integer.parseInt(args[1]); <add> } <add> int is = 0; <add> for (ItemStack i : p.getInventory()) { <add> if (i != null) { <add> if (NBTManager.isSellable(i)) { <add> String st = NBTManager.getType(i).toLowerCase(); <add> if (st.equalsIgnoreCase(args[0])) { <add> if (is != limit) { <add> price = setPrice(price, args, i, p, limit); <add> ++is; <ide> } <ide> } <ide> } <ide> } <del> if (HeadsPlus.getInstance().getNMSVersion().getOrder() < 4) { <del> ItemStack i = p.getInventory().getHelmet(); <del> if (i != null) { <del> if (NBTManager.isSellable(i)) { <del> String st = NBTManager.getType(i).toLowerCase(); <del> if (st.equalsIgnoreCase(args[0])) { <del> if (is != limit) { <del> price = setPrice(price, args, i, p, limit); <del> } <add> } <add> if (HeadsPlus.getInstance().getNMSVersion().getOrder() < 4) { <add> ItemStack i = p.getInventory().getHelmet(); <add> if (i != null) { <add> if (NBTManager.isSellable(i)) { <add> String st = NBTManager.getType(i).toLowerCase(); <add> if (st.equalsIgnoreCase(args[0])) { <add> if (is != limit) { <add> price = setPrice(price, args, i, p, limit); <ide> } <ide> } <ide> } <ide> } <del> <del> ItemStack is2 = nms().getOffHand(p); <del> if (is2 != null) { <del> if (NBTManager.isSellable(is2)) { <del> String st = NBTManager.getType(is2).toLowerCase(); <del> if (st.equalsIgnoreCase(args[0])) { <del> if (is != limit) { <del> price = setPrice(price, args, is2, p, limit); <del> } <add> } <add> ItemStack is2 = nms().getOffHand(p); <add> if (is2 != null) { <add> if (NBTManager.isSellable(is2)) { <add> String st = NBTManager.getType(is2).toLowerCase(); <add> if (st.equalsIgnoreCase(args[0])) { <add> if (is != limit) { <add> price = setPrice(price, args, is2, p, limit); <ide> } <ide> } <ide> } <del> if (price == 0.0) { <del> sender.sendMessage(hpc.getString("commands.sellhead.no-heads", p)); <del> return true; <del> } <del> pay(p, args, price, limit); <add> } <add> if (price == 0.0) { <add> sender.sendMessage(hpc.getString("commands.sellhead.no-heads", p)); <ide> return true; <ide> } <del> } <del> } else { <del> sender.sendMessage(hpc.getString("commands.head.alpha-names", p)); <del> } <del> <add> pay(p, args, price, limit); <add> return true; <add> } <add> } <ide> } <ide> } else { <ide> sender.sendMessage(hpc.getString("commands.errors.disabled", p));
Java
epl-1.0
d5364efea9eaeb989c4b3616b07d709c0c7a488e
0
peterkir/org.eclipse.oomph,peterkir/org.eclipse.oomph,peterkir/org.eclipse.oomph,peterkir/org.eclipse.oomph,peterkir/org.eclipse.oomph
/* * Copyright (c) 2014, 2015 Eike Stepper (Berlin, Germany) and others. * 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: * Eike Stepper - initial API and implementation */ package org.eclipse.oomph.setup.internal.core; import org.eclipse.oomph.base.util.BaseUtil; import org.eclipse.oomph.setup.Index; import org.eclipse.oomph.setup.Installation; import org.eclipse.oomph.setup.LocationCatalog; import org.eclipse.oomph.setup.Product; import org.eclipse.oomph.setup.ProductCatalog; import org.eclipse.oomph.setup.ProductVersion; import org.eclipse.oomph.setup.SetupFactory; import org.eclipse.oomph.setup.SetupPackage; import org.eclipse.oomph.setup.Stream; import org.eclipse.oomph.setup.User; import org.eclipse.oomph.setup.Workspace; import org.eclipse.oomph.setup.impl.InstallationTaskImpl; import org.eclipse.oomph.setup.internal.core.util.SetupCoreUtil; import org.eclipse.oomph.util.IORuntimeException; import org.eclipse.oomph.util.IOUtil; import org.eclipse.oomph.util.OS; import org.eclipse.oomph.util.PropertiesUtil; import org.eclipse.emf.common.CommonPlugin; import org.eclipse.emf.common.util.ECollections; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.common.util.EMap; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.plugin.EcorePlugin; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.URIConverter; import org.eclipse.emf.ecore.util.EcoreUtil; import org.eclipse.emf.ecore.util.InternalEList; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.Platform; import org.eclipse.osgi.service.datalocation.Location; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Map; import java.util.Map.Entry; /** * @author Eike Stepper */ public class SetupContext { public static final String OOMPH_NODE = "org.eclipse.oomph.setup"; public static final String LOG_FILE_NAME = "setup.log"; public static final String USER_SCHEME = "user"; public static boolean isUserScheme(String scheme) { return USER_SCHEME.equals(scheme) || "user-ext".equals(scheme); } /** * Resolves a '{@link #USER_SCHEME user}' scheme URI to a 'file' scheme URI. */ public static URI resolveUser(URI uri) { if (isUserScheme(uri.scheme())) { return SetupContext.GLOBAL_SETUPS_LOCATION_URI.appendSegments(uri.segments()).appendFragment(uri.fragment()); } return uri; } // Basic locations public static final URI CONFIGURATION_LOCATION_URI = getStaticConfigurationLocation(); public static final URI WORKSPACE_LOCATION_URI = CommonPlugin.IS_RESOURCES_BUNDLE_AVAILABLE ? WorkspaceUtil.getStaticWorkspaceLocationURI() : null; public static final URI PRODUCT_LOCATION = getStaticInstallLocation(); public static final URI PRODUCT_ROOT_LOCATION = PRODUCT_LOCATION.trimSegments(OS.INSTANCE.isMac() ? 3 : 1); // State locations public static final URI GLOBAL_STATE_LOCATION_URI = URI.createFileURI(PropertiesUtil.USER_HOME).appendSegments(new String[] { ".eclipse", OOMPH_NODE }); public static final URI GLOBAL_SETUPS_URI = URI.createURI(USER_SCHEME + ":/"); public static final URI GLOBAL_SETUPS_LOCATION_URI = GLOBAL_STATE_LOCATION_URI.appendSegment("setups"); public static final URI CONFIGURATION_STATE_LOCATION_URI = CONFIGURATION_LOCATION_URI.appendSegment(OOMPH_NODE); public static final URI WORKSPACE_STATE_LOCATION_URI = WORKSPACE_LOCATION_URI == null ? null : WORKSPACE_LOCATION_URI.appendSegments(new String[] { ".metadata", ".plugins", OOMPH_NODE }); // Resource locations public static final URI SETUP_LOG_URI = CONFIGURATION_STATE_LOCATION_URI.appendSegment(LOG_FILE_NAME); public static final URI INDEX_SETUP_URI = URI.createURI("index:/org.eclipse.setup"); public static final URI INDEX_SETUP_LOCATION_URI = URI.createURI("http://git.eclipse.org/c/oomph/org.eclipse.oomph.git/plain/setups/org.eclipse.setup"); public static final URI INDEX_SETUP_ARCHIVE_LOCATION_URI = URI.createURI("http://www.eclipse.org/setups/setups.zip"); public static final URI INSTALLATION_SETUP_FILE_NAME_URI = URI.createURI("installation.setup"); public static final URI INSTALLATION_SETUP_URI = CONFIGURATION_STATE_LOCATION_URI.appendSegment(INSTALLATION_SETUP_FILE_NAME_URI.lastSegment()); public static final URI WORKSPACE_SETUP_FILE_NAME_URI = URI.createURI("workspace.setup"); public static final URI WORKSPACE_SETUP_URI = WORKSPACE_STATE_LOCATION_URI == null ? null : WORKSPACE_STATE_LOCATION_URI .appendSegment(WORKSPACE_SETUP_FILE_NAME_URI.lastSegment()); public static final URI WORKSPACE_SETUP_RELATIVE_URI = URI.createHierarchicalURI(new String[] { ".metadata", ".plugins", OOMPH_NODE, WORKSPACE_SETUP_FILE_NAME_URI.lastSegment() }, null, null); public static final URI USER_SETUP_URI = GLOBAL_SETUPS_URI.appendSegment("user.setup"); public static final URI USER_SETUP_LOCATION_URI = GLOBAL_SETUPS_LOCATION_URI.appendSegment("user.setup"); public static final URI CATALOG_SELECTION_SETUP_URI = GLOBAL_SETUPS_URI.appendSegment("catalogs.setup"); public static final URI CATALOG_SELECTION_SETUP_LOCATION_URI = GLOBAL_SETUPS_LOCATION_URI.appendSegment("catalogs.setup"); public static final URI LOCATION_CATALOG_SETUP_URI = GLOBAL_SETUPS_URI.appendSegment("locations.setup"); private static volatile SetupContext self = new SetupContext(); // static creation methods // private constructors private final Installation installation; private final Workspace workspace; private final User user; private SetupContext() { installation = createInstallation(); ((InternalEObject)installation).eSetProxyURI(INSTALLATION_SETUP_URI.appendFragment("/")); workspace = createWorkspace(); if (WORKSPACE_SETUP_URI != null) { ((InternalEObject)workspace).eSetProxyURI(WORKSPACE_SETUP_URI.appendFragment("/")); } user = createUser(); ((InternalEObject)user).eSetProxyURI(USER_SETUP_URI.appendFragment("/")); } private SetupContext(Installation installation, Workspace workspace, User user) { this.installation = installation; this.workspace = workspace; this.user = user; } public Installation getInstallation() { return installation; } public Workspace getWorkspace() { return workspace; } public User getUser() { return user; } /** * Returns a setup context consisting purely of proxy instances for the current self-hosted installation. */ public static SetupContext getSelf() { return self; } public static void setSelf(SetupContext setupContext) { self = setupContext; } // static creation methods public static SetupContext createSelf(Installation installation, Workspace workspace, User user) { return proxify(installation, workspace, user); } public static SetupContext createSelf(ResourceSet resourceSet) { Installation installation = getInstallation(resourceSet, true, Mode.CREATE_AND_SAVE); Workspace workspace = getWorkspace(resourceSet, true, Mode.CREATE_AND_SAVE); Installation effectiveInstallation = null; URI uri = installation.eResource().getURI(); if (uri.segmentCount() > 3) { String eclipseLauncher = PropertiesUtil.getProperty("eclipse.launcher"); if (eclipseLauncher != null) { File eclipseLauncherExecutable = new File(eclipseLauncher); if (eclipseLauncherExecutable.exists()) { effectiveInstallation = installation; } } } SetupContext.associate(effectiveInstallation, workspace); User user = getUser(resourceSet, false); return createSelf(installation, workspace, user); } public static SetupContext createInstallationAndUser(ResourceSet resourceSet) { return new SetupContext(getInstallation(resourceSet, true, Mode.CREATE), null, getUser(resourceSet, true)); } public static SetupContext create(ResourceSet resourceSet) { return new SetupContext(getInstallation(resourceSet, true, Mode.CREATE), getWorkspace(resourceSet, true, Mode.CREATE), getUser(resourceSet, true)); } public static SetupContext createInstallationWorkspaceAndUser(ResourceSet resourceSet) { return new SetupContext(getInstallation(resourceSet, false, Mode.NONE), getWorkspace(resourceSet, false, Mode.NONE), getUser(resourceSet, false)); } public static SetupContext createUserOnly(ResourceSet resourceSet) { return new SetupContext(null, null, getUser(resourceSet, true)); } public static SetupContext create(ResourceSet resourceSet, ProductVersion productVersion) { Installation installation = getInstallation(resourceSet, false, Mode.CREATE); installation.setProductVersion(productVersion); return new SetupContext(installation, getWorkspace(resourceSet, false, Mode.NONE), getUser(resourceSet, true)); } public static SetupContext create(ProductVersion productVersion, Stream stream) { User user = createUser(); Workspace workspace = createWorkspace(); workspace.getStreams().add(stream); Installation installation = createInstallation(); installation.setProductVersion(productVersion); return new SetupContext(installation, workspace, user); } public static SetupContext create(Installation installation, Collection<? extends Stream> streams, User user) { Workspace workspace = createWorkspace(); workspace.getStreams().addAll(streams); Resource workspaceResource = installation.eResource().getResourceSet().createResource(WORKSPACE_SETUP_FILE_NAME_URI); workspaceResource.getContents().add(workspace); return new SetupContext(installation, workspace, user); } public static SetupContext create() { return new SetupContext(); } public static SetupContext create(Installation installation, Workspace workspace, User user) { return new SetupContext(installation, workspace, user); } public static SetupContext create(Installation installation, Workspace workspace) { User user = createUser(); Resource userResource = installation.eResource().getResourceSet().getResourceFactoryRegistry().getFactory(USER_SETUP_URI).createResource(USER_SETUP_URI); userResource.getContents().add(user); return new SetupContext(installation, workspace, user); } public static SetupContext createCopy(Installation installation, Workspace workspace, User user) { Resource.Factory.Registry resourceFactoryRegistry = SetupCoreUtil.createResourceSet().getResourceFactoryRegistry(); Installation copiedInstallation = EcoreUtil.copy(installation); Resource installationResource = resourceFactoryRegistry.getFactory(INSTALLATION_SETUP_FILE_NAME_URI).createResource(INSTALLATION_SETUP_FILE_NAME_URI); installationResource.getContents().add(copiedInstallation); Workspace copiedWorkspace = EcoreUtil.copy(workspace); if (workspace != null) { Resource workResource = resourceFactoryRegistry.getFactory(WORKSPACE_SETUP_FILE_NAME_URI).createResource(WORKSPACE_SETUP_FILE_NAME_URI); workResource.getContents().add(copiedWorkspace); } User copiedUser = EcoreUtil.copy(user); Resource userResource = resourceFactoryRegistry.getFactory(USER_SETUP_URI).createResource(USER_SETUP_URI); userResource.getContents().add(copiedUser); return new SetupContext(copiedInstallation, copiedWorkspace, copiedUser); } public static User createUser() { User user = SetupFactory.eINSTANCE.createUser(); user.setName(PropertiesUtil.getProperty("user.name", "user")); return user; } public static Workspace createWorkspace() { Workspace workspace = SetupFactory.eINSTANCE.createWorkspace(); workspace.setName("workspace"); return workspace; } public static Installation createInstallation() { Installation installation = SetupFactory.eINSTANCE.createInstallation(); installation.setName("installation"); return installation; } public static void associate(final Installation installation, final Workspace workspace) { final ResourceSet resourceSet = SetupCoreUtil.createResourceSet(); URIConverter uriConverter = resourceSet.getURIConverter(); BaseUtil.execute(5000, new Runnable() { public void run() { associate(resourceSet, installation, workspace); } }, uriConverter, LOCATION_CATALOG_SETUP_URI, installation == null ? null : installation.eResource().getURI(), workspace == null ? null : workspace .eResource().getURI()); } private static void associate(ResourceSet resourceSet, Installation installation, Workspace workspace) { URIConverter uriConverter = resourceSet.getURIConverter(); Resource resource; if (uriConverter.exists(LOCATION_CATALOG_SETUP_URI, null)) { resource = BaseUtil.loadResourceSafely(resourceSet, LOCATION_CATALOG_SETUP_URI); } else { resource = resourceSet.createResource(LOCATION_CATALOG_SETUP_URI); } EList<EObject> contents = resource.getContents(); LocationCatalog locationCatalog = (LocationCatalog)EcoreUtil.getObjectByType(contents, SetupPackage.Literals.LOCATION_CATALOG); if (locationCatalog == null) { locationCatalog = SetupFactory.eINSTANCE.createLocationCatalog(); contents.add(locationCatalog); } EMap<Installation, EList<Workspace>> installations = locationCatalog.getInstallations(); removeProxies(installations); EMap<Workspace, EList<Installation>> workspaces = locationCatalog.getWorkspaces(); removeProxies(workspaces); Installation localInstallation = installation == null ? null : (Installation)resourceSet.getEObject(EcoreUtil.getURI(installation), true); Workspace localWorkspace = workspace == null ? null : (Workspace)resourceSet.getEObject(EcoreUtil.getURI(workspace), true); if (installation != null) { int installationEntryIndex = installations.indexOfKey(localInstallation); if (installationEntryIndex == -1) { installations.put(localInstallation, localWorkspace == null ? ECollections.<Workspace> emptyEList() : ECollections.singletonEList(localWorkspace)); installations.move(0, installations.size() - 1); } else if (localWorkspace != null) { EList<Workspace> associatedWorkspaces = installations.get(installationEntryIndex).getValue(); int position = associatedWorkspaces.indexOf(localWorkspace); if (position == -1) { associatedWorkspaces.add(0, localWorkspace); } else { associatedWorkspaces.move(0, position); } installations.move(0, installationEntryIndex); } } if (localWorkspace != null) { int workspaceEntryIndex = workspaces.indexOfKey(localWorkspace); if (workspaceEntryIndex == -1) { workspaces.put(localWorkspace, localInstallation == null ? ECollections.<Installation> emptyEList() : ECollections.singletonEList(localInstallation)); workspaces.move(0, workspaces.size() - 1); } else if (localInstallation != null) { EList<Installation> associatedInstallations = workspaces.get(workspaceEntryIndex).getValue(); int position = associatedInstallations.indexOf(localInstallation); if (position == -1) { associatedInstallations.add(0, localInstallation); } else { associatedInstallations.move(0, position); } workspaces.move(0, workspaceEntryIndex); } } try { resource.save(null); } catch (IOException ex) { SetupCorePlugin.INSTANCE.log(ex); } } private static <K extends EObject, V extends EObject> void removeProxies(EMap<K, EList<V>> map) { for (Iterator<Entry<K, EList<V>>> it = map.iterator(); it.hasNext();) { Entry<K, EList<V>> entry = it.next(); K key = entry.getKey(); if (key == null || key.eIsProxy()) { it.remove(); } else { for (Iterator<V> it2 = entry.getValue().iterator(); it2.hasNext();) { V value = it2.next(); if (value.eIsProxy()) { it2.remove(); } } } } } private static URI getStaticInstallLocation() { try { if (!Platform.isRunning()) { return URI.createFileURI(File.createTempFile("installation", "").toString()); } Location location = Platform.getInstallLocation(); URI result = getURI(location); if (OS.INSTANCE.isMac()) { result = result.trimSegments(1).appendSegment("Eclipse"); } return result; } catch (IOException ex) { throw new RuntimeException(ex); } } private static URI getURI(Location location) throws IOException { URI result = URI.createURI(FileLocator.resolve(location.getURL()).toString()); if (result.isFile()) { result = URI.createFileURI(result.toFileString()); } return result.hasTrailingPathSeparator() ? result.trimSegments(1) : result; } private static URI getStaticConfigurationLocation() { try { if (!Platform.isRunning()) { return URI.createFileURI(File.createTempFile(InstallationTaskImpl.CONFIGURATION_FOLDER_NAME, "").toString()); } Location location = Platform.getConfigurationLocation(); URI result = getURI(location); Location parentLocation = location.getParentLocation(); if (parentLocation != null) { URI targetInstallation = result.appendSegment(OOMPH_NODE).appendSegment("installation.setup"); File target = new File(targetInstallation.toFileString()); if (!target.exists()) { URI parentURI = getURI(parentLocation); URI sourceInstallation = parentURI.appendSegment(OOMPH_NODE).appendSegment("installation.setup"); File source = new File(sourceInstallation.toFileString()); if (source.exists()) { try { IOUtil.copyFile(source, target); } catch (IORuntimeException ex) { // Ignore. } } } } return result; } catch (IOException ex) { throw new IORuntimeException(ex); } } private enum Mode { NONE, CREATE, CREATE_AND_SAVE } private static Installation getInstallation(ResourceSet resourceSet, boolean realInstallation, Mode mode) { Installation installation = null; Resource installationResource = null; if (realInstallation) { if (resourceSet.getURIConverter().exists(INSTALLATION_SETUP_URI, null)) { installationResource = BaseUtil.loadResourceSafely(resourceSet, INSTALLATION_SETUP_URI); installation = (Installation)EcoreUtil.getObjectByType(installationResource.getContents(), SetupPackage.Literals.INSTALLATION); } } else { installationResource = resourceSet.getResource(INSTALLATION_SETUP_FILE_NAME_URI, false); if (installationResource == null) { installationResource = resourceSet.getResource(INSTALLATION_SETUP_URI, false); } if (installationResource != null) { installation = (Installation)installationResource.getContents().get(0); } } boolean save = false; if (installation == null && mode != Mode.NONE) { if (installationResource == null) { installationResource = resourceSet.createResource(realInstallation ? INSTALLATION_SETUP_URI : INSTALLATION_SETUP_FILE_NAME_URI); } else { installationResource.unload(); } installation = createInstallation(); installationResource.getContents().add(installation); save = mode == Mode.CREATE_AND_SAVE; } if (realInstallation && installation != null && installation.getProductVersion() == null) { ProductCatalog productCatalog = null; Resource indexResource = BaseUtil.loadResourceSafely(resourceSet, INDEX_SETUP_URI); Index index = (Index)EcoreUtil.getObjectByType(indexResource.getContents(), SetupPackage.Literals.INDEX); if (index != null) { EList<ProductCatalog> productCatalogs = index.getProductCatalogs(); if (!productCatalogs.isEmpty()) { productCatalog = productCatalogs.get(0); } } if (productCatalog == null) { Resource selfProductCatalogResource = BaseUtil.loadResourceSafely(resourceSet, URI.createURI("catalog:/self-product-catalog.setup")); productCatalog = (ProductCatalog)EcoreUtil.getObjectByType(selfProductCatalogResource.getContents(), SetupPackage.Literals.PRODUCT_CATALOG); } EList<Product> products = productCatalog.getProducts(); EList<ProductVersion> versions = products.get(0).getVersions(); installation.setProductVersion(versions.get(0)); if (save) { BaseUtil.saveEObject(installation); } } return installation; } private static Workspace getWorkspace(ResourceSet resourceSet, boolean realWorkspace, Mode mode) { Resource workspaceResource = null; Workspace workspace = null; if (realWorkspace) { if (resourceSet.getURIConverter().exists(WORKSPACE_SETUP_URI, null)) { workspaceResource = BaseUtil.loadResourceSafely(resourceSet, WORKSPACE_SETUP_URI); workspace = (Workspace)EcoreUtil.getObjectByType(workspaceResource.getContents(), SetupPackage.Literals.WORKSPACE); } } else { workspaceResource = resourceSet.getResource(WORKSPACE_SETUP_FILE_NAME_URI, false); if (workspaceResource == null && WORKSPACE_SETUP_URI != null) { workspaceResource = resourceSet.getResource(WORKSPACE_SETUP_URI, false); } if (workspaceResource != null) { workspace = (Workspace)workspaceResource.getContents().get(0); } } if (workspace == null && mode != Mode.NONE) { if (workspaceResource == null) { workspaceResource = resourceSet.createResource(realWorkspace ? WORKSPACE_SETUP_URI : WORKSPACE_SETUP_FILE_NAME_URI); } else { workspaceResource.unload(); } workspace = createWorkspace(); workspaceResource.getContents().add(workspace); if (mode == Mode.CREATE_AND_SAVE) { BaseUtil.saveEObject(workspace); } } return workspace; } private static User getUser(ResourceSet resourceSet, boolean demandCreate) { Resource userResource = null; User user = null; if (resourceSet.getURIConverter().exists(USER_SETUP_URI, null)) { userResource = BaseUtil.loadResourceSafely(resourceSet, USER_SETUP_URI); user = (User)EcoreUtil.getObjectByType(userResource.getContents(), SetupPackage.Literals.USER); } if (user == null && demandCreate) { if (userResource == null) { userResource = resourceSet.createResource(USER_SETUP_URI); } else { userResource.unload(); } user = createUser(); userResource.getContents().add(user); try { userResource.save(null); } catch (IOException ex) { throw new IORuntimeException(ex); } } return user; } private static SetupContext proxify(Installation installation, Workspace workspace, User user) { EcoreUtil.Copier copier = new EcoreUtil.Copier(false, false) { private static final long serialVersionUID = 1L; @Override protected void copyContainment(EReference eReference, EObject eObject, EObject copyEObject) { } @Override protected void copyProxyURI(EObject eObject, EObject copyEObject) { ((InternalEObject)copyEObject).eSetProxyURI(EcoreUtil.getURI(eObject)); } }; Installation installationCopy = (Installation)copier.copy(installation); if (installation != null) { copier.copy(installation.getProductVersion()); } Workspace workspaceCopy = (Workspace)copier.copy(workspace); if (workspace != null) { copier.copyAll(workspace.getStreams()); } User userCopy = (User)copier.copy(user); for (Map.Entry<EObject, EObject> entry : new LinkedHashSet<Map.Entry<EObject, EObject>>(copier.entrySet())) { EObject eObject = entry.getKey(); EObject copyEObject = entry.getValue(); for (EObject eContainer = eObject.eContainer(); eContainer != null; eContainer = eContainer.eContainer()) { EObject copyEContainer = copier.get(eContainer); if (copyEContainer == null) { copyEContainer = copier.copy(eContainer); } @SuppressWarnings("unchecked") InternalEList<EObject> list = (InternalEList<EObject>)copyEContainer.eGet(eObject.eContainmentFeature()); list.addUnique(copyEObject); eObject = eContainer; copyEObject = copyEContainer; } } copier.copyReferences(); return new SetupContext(installationCopy, workspaceCopy, userCopy); } /** * @author Eike Stepper */ private static class WorkspaceUtil { private static URI getStaticWorkspaceLocationURI() { try { IWorkspaceRoot workspaceRoot = EcorePlugin.getWorkspaceRoot(); return URI.createFileURI(workspaceRoot.getLocation().toOSString()); } catch (Throwable throwable) { return null; } } } }
plugins/org.eclipse.oomph.setup.core/src/org/eclipse/oomph/setup/internal/core/SetupContext.java
/* * Copyright (c) 2014, 2015 Eike Stepper (Berlin, Germany) and others. * 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: * Eike Stepper - initial API and implementation */ package org.eclipse.oomph.setup.internal.core; import org.eclipse.oomph.base.util.BaseUtil; import org.eclipse.oomph.setup.Index; import org.eclipse.oomph.setup.Installation; import org.eclipse.oomph.setup.LocationCatalog; import org.eclipse.oomph.setup.Product; import org.eclipse.oomph.setup.ProductCatalog; import org.eclipse.oomph.setup.ProductVersion; import org.eclipse.oomph.setup.SetupFactory; import org.eclipse.oomph.setup.SetupPackage; import org.eclipse.oomph.setup.Stream; import org.eclipse.oomph.setup.User; import org.eclipse.oomph.setup.Workspace; import org.eclipse.oomph.setup.impl.InstallationTaskImpl; import org.eclipse.oomph.setup.internal.core.util.SetupCoreUtil; import org.eclipse.oomph.util.IORuntimeException; import org.eclipse.oomph.util.IOUtil; import org.eclipse.oomph.util.OS; import org.eclipse.oomph.util.PropertiesUtil; import org.eclipse.emf.common.CommonPlugin; import org.eclipse.emf.common.util.ECollections; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.common.util.EMap; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.plugin.EcorePlugin; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.URIConverter; import org.eclipse.emf.ecore.util.EcoreUtil; import org.eclipse.emf.ecore.util.InternalEList; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.Platform; import org.eclipse.osgi.service.datalocation.Location; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Map; import java.util.Map.Entry; /** * @author Eike Stepper */ public class SetupContext { public static final String OOMPH_NODE = "org.eclipse.oomph.setup"; public static final String LOG_FILE_NAME = "setup.log"; public static final String USER_SCHEME = "user"; public static boolean isUserScheme(String scheme) { return USER_SCHEME.equals(scheme) || "user-ext".equals(scheme); } /** * Resolves a '{@link #USER_SCHEME user}' scheme URI to a 'file' scheme URI. */ public static URI resolveUser(URI uri) { if (isUserScheme(uri.scheme())) { return SetupContext.GLOBAL_SETUPS_LOCATION_URI.appendSegments(uri.segments()).appendFragment(uri.fragment()); } return uri; } // Basic locations public static final URI CONFIGURATION_LOCATION_URI = getStaticConfigurationLocation(); public static final URI WORKSPACE_LOCATION_URI = CommonPlugin.IS_RESOURCES_BUNDLE_AVAILABLE ? WorkspaceUtil.getStaticWorkspaceLocationURI() : null; public static final URI PRODUCT_LOCATION = getStaticInstallLocation(); public static final URI PRODUCT_ROOT_LOCATION = PRODUCT_LOCATION.trimSegments(OS.INSTANCE.isMac() ? 3 : 1); // State locations public static final URI GLOBAL_STATE_LOCATION_URI = URI.createFileURI(PropertiesUtil.USER_HOME).appendSegments(new String[] { ".eclipse", OOMPH_NODE }); public static final URI GLOBAL_SETUPS_URI = URI.createURI(USER_SCHEME + ":/"); public static final URI GLOBAL_SETUPS_LOCATION_URI = GLOBAL_STATE_LOCATION_URI.appendSegment("setups"); public static final URI CONFIGURATION_STATE_LOCATION_URI = CONFIGURATION_LOCATION_URI.appendSegment(OOMPH_NODE); public static final URI WORKSPACE_STATE_LOCATION_URI = WORKSPACE_LOCATION_URI == null ? null : WORKSPACE_LOCATION_URI.appendSegments(new String[] { ".metadata", ".plugins", OOMPH_NODE }); // Resource locations public static final URI SETUP_LOG_URI = CONFIGURATION_STATE_LOCATION_URI.appendSegment(LOG_FILE_NAME); public static final URI INDEX_SETUP_URI = URI.createURI("index:/org.eclipse.setup"); public static final URI INDEX_SETUP_LOCATION_URI = URI.createURI("http://git.eclipse.org/c/oomph/org.eclipse.oomph.git/plain/setups/org.eclipse.setup"); public static final URI INDEX_SETUP_ARCHIVE_LOCATION_URI = URI.createURI("http://www.eclipse.org/setups/setups.zip"); public static final URI INSTALLATION_SETUP_FILE_NAME_URI = URI.createURI("installation.setup"); public static final URI INSTALLATION_SETUP_URI = CONFIGURATION_STATE_LOCATION_URI.appendSegment(INSTALLATION_SETUP_FILE_NAME_URI.lastSegment()); public static final URI WORKSPACE_SETUP_FILE_NAME_URI = URI.createURI("workspace.setup"); public static final URI WORKSPACE_SETUP_URI = WORKSPACE_STATE_LOCATION_URI == null ? null : WORKSPACE_STATE_LOCATION_URI .appendSegment(WORKSPACE_SETUP_FILE_NAME_URI.lastSegment()); public static final URI WORKSPACE_SETUP_RELATIVE_URI = URI.createHierarchicalURI(new String[] { ".metadata", ".plugins", OOMPH_NODE, WORKSPACE_SETUP_FILE_NAME_URI.lastSegment() }, null, null); public static final URI USER_SETUP_URI = GLOBAL_SETUPS_URI.appendSegment("user.setup"); public static final URI USER_SETUP_LOCATION_URI = GLOBAL_SETUPS_LOCATION_URI.appendSegment("user.setup"); public static final URI CATALOG_SELECTION_SETUP_URI = GLOBAL_SETUPS_URI.appendSegment("catalogs.setup"); public static final URI CATALOG_SELECTION_SETUP_LOCATION_URI = GLOBAL_SETUPS_LOCATION_URI.appendSegment("catalogs.setup"); public static final URI LOCATION_CATALOG_SETUP_URI = GLOBAL_SETUPS_URI.appendSegment("locations.setup"); private static volatile SetupContext self = new SetupContext(); // static creation methods // private constructors private final Installation installation; private final Workspace workspace; private final User user; private SetupContext() { installation = createInstallation(); ((InternalEObject)installation).eSetProxyURI(INSTALLATION_SETUP_URI.appendFragment("/")); workspace = createWorkspace(); if (WORKSPACE_SETUP_URI != null) { ((InternalEObject)workspace).eSetProxyURI(WORKSPACE_SETUP_URI.appendFragment("/")); } user = createUser(); ((InternalEObject)user).eSetProxyURI(USER_SETUP_URI.appendFragment("/")); } private SetupContext(Installation installation, Workspace workspace, User user) { this.installation = installation; this.workspace = workspace; this.user = user; } public Installation getInstallation() { return installation; } public Workspace getWorkspace() { return workspace; } public User getUser() { return user; } /** * Returns a setup context consisting purely of proxy instances for the current self-hosted installation. */ public static SetupContext getSelf() { return self; } public static void setSelf(SetupContext setupContext) { self = setupContext; } // static creation methods public static SetupContext createSelf(Installation installation, Workspace workspace, User user) { return proxify(installation, workspace, user); } public static SetupContext createSelf(ResourceSet resourceSet) { Installation installation = getInstallation(resourceSet, true, Mode.CREATE_AND_SAVE); Workspace workspace = getWorkspace(resourceSet, true, Mode.CREATE_AND_SAVE); Installation effectiveInstallation = null; URI uri = installation.eResource().getURI(); if (uri.segmentCount() > 3) { String eclipseLauncher = PropertiesUtil.getProperty("eclipse.launcher"); if (eclipseLauncher == null) { throw new IllegalStateException("There is no eclipse.launcher property defined"); } File eclipseLauncherExecutable = new File(eclipseLauncher); if (eclipseLauncherExecutable.exists()) { effectiveInstallation = installation; } } SetupContext.associate(effectiveInstallation, workspace); User user = getUser(resourceSet, false); return createSelf(installation, workspace, user); } public static SetupContext createInstallationAndUser(ResourceSet resourceSet) { return new SetupContext(getInstallation(resourceSet, true, Mode.CREATE), null, getUser(resourceSet, true)); } public static SetupContext create(ResourceSet resourceSet) { return new SetupContext(getInstallation(resourceSet, true, Mode.CREATE), getWorkspace(resourceSet, true, Mode.CREATE), getUser(resourceSet, true)); } public static SetupContext createInstallationWorkspaceAndUser(ResourceSet resourceSet) { return new SetupContext(getInstallation(resourceSet, false, Mode.NONE), getWorkspace(resourceSet, false, Mode.NONE), getUser(resourceSet, false)); } public static SetupContext createUserOnly(ResourceSet resourceSet) { return new SetupContext(null, null, getUser(resourceSet, true)); } public static SetupContext create(ResourceSet resourceSet, ProductVersion productVersion) { Installation installation = getInstallation(resourceSet, false, Mode.CREATE); installation.setProductVersion(productVersion); return new SetupContext(installation, getWorkspace(resourceSet, false, Mode.NONE), getUser(resourceSet, true)); } public static SetupContext create(ProductVersion productVersion, Stream stream) { User user = createUser(); Workspace workspace = createWorkspace(); workspace.getStreams().add(stream); Installation installation = createInstallation(); installation.setProductVersion(productVersion); return new SetupContext(installation, workspace, user); } public static SetupContext create(Installation installation, Collection<? extends Stream> streams, User user) { Workspace workspace = createWorkspace(); workspace.getStreams().addAll(streams); Resource workspaceResource = installation.eResource().getResourceSet().createResource(WORKSPACE_SETUP_FILE_NAME_URI); workspaceResource.getContents().add(workspace); return new SetupContext(installation, workspace, user); } public static SetupContext create() { return new SetupContext(); } public static SetupContext create(Installation installation, Workspace workspace, User user) { return new SetupContext(installation, workspace, user); } public static SetupContext create(Installation installation, Workspace workspace) { User user = createUser(); Resource userResource = installation.eResource().getResourceSet().getResourceFactoryRegistry().getFactory(USER_SETUP_URI).createResource(USER_SETUP_URI); userResource.getContents().add(user); return new SetupContext(installation, workspace, user); } public static SetupContext createCopy(Installation installation, Workspace workspace, User user) { Resource.Factory.Registry resourceFactoryRegistry = SetupCoreUtil.createResourceSet().getResourceFactoryRegistry(); Installation copiedInstallation = EcoreUtil.copy(installation); Resource installationResource = resourceFactoryRegistry.getFactory(INSTALLATION_SETUP_FILE_NAME_URI).createResource(INSTALLATION_SETUP_FILE_NAME_URI); installationResource.getContents().add(copiedInstallation); Workspace copiedWorkspace = EcoreUtil.copy(workspace); if (workspace != null) { Resource workResource = resourceFactoryRegistry.getFactory(WORKSPACE_SETUP_FILE_NAME_URI).createResource(WORKSPACE_SETUP_FILE_NAME_URI); workResource.getContents().add(copiedWorkspace); } User copiedUser = EcoreUtil.copy(user); Resource userResource = resourceFactoryRegistry.getFactory(USER_SETUP_URI).createResource(USER_SETUP_URI); userResource.getContents().add(copiedUser); return new SetupContext(copiedInstallation, copiedWorkspace, copiedUser); } public static User createUser() { User user = SetupFactory.eINSTANCE.createUser(); user.setName(PropertiesUtil.getProperty("user.name", "user")); return user; } public static Workspace createWorkspace() { Workspace workspace = SetupFactory.eINSTANCE.createWorkspace(); workspace.setName("workspace"); return workspace; } public static Installation createInstallation() { Installation installation = SetupFactory.eINSTANCE.createInstallation(); installation.setName("installation"); return installation; } public static void associate(final Installation installation, final Workspace workspace) { final ResourceSet resourceSet = SetupCoreUtil.createResourceSet(); URIConverter uriConverter = resourceSet.getURIConverter(); BaseUtil.execute(5000, new Runnable() { public void run() { associate(resourceSet, installation, workspace); } }, uriConverter, LOCATION_CATALOG_SETUP_URI, installation == null ? null : installation.eResource().getURI(), workspace == null ? null : workspace .eResource().getURI()); } private static void associate(ResourceSet resourceSet, Installation installation, Workspace workspace) { URIConverter uriConverter = resourceSet.getURIConverter(); Resource resource; if (uriConverter.exists(LOCATION_CATALOG_SETUP_URI, null)) { resource = BaseUtil.loadResourceSafely(resourceSet, LOCATION_CATALOG_SETUP_URI); } else { resource = resourceSet.createResource(LOCATION_CATALOG_SETUP_URI); } EList<EObject> contents = resource.getContents(); LocationCatalog locationCatalog = (LocationCatalog)EcoreUtil.getObjectByType(contents, SetupPackage.Literals.LOCATION_CATALOG); if (locationCatalog == null) { locationCatalog = SetupFactory.eINSTANCE.createLocationCatalog(); contents.add(locationCatalog); } EMap<Installation, EList<Workspace>> installations = locationCatalog.getInstallations(); removeProxies(installations); EMap<Workspace, EList<Installation>> workspaces = locationCatalog.getWorkspaces(); removeProxies(workspaces); Installation localInstallation = installation == null ? null : (Installation)resourceSet.getEObject(EcoreUtil.getURI(installation), true); Workspace localWorkspace = workspace == null ? null : (Workspace)resourceSet.getEObject(EcoreUtil.getURI(workspace), true); if (installation != null) { int installationEntryIndex = installations.indexOfKey(localInstallation); if (installationEntryIndex == -1) { installations.put(localInstallation, localWorkspace == null ? ECollections.<Workspace> emptyEList() : ECollections.singletonEList(localWorkspace)); installations.move(0, installations.size() - 1); } else if (localWorkspace != null) { EList<Workspace> associatedWorkspaces = installations.get(installationEntryIndex).getValue(); int position = associatedWorkspaces.indexOf(localWorkspace); if (position == -1) { associatedWorkspaces.add(0, localWorkspace); } else { associatedWorkspaces.move(0, position); } installations.move(0, installationEntryIndex); } } if (localWorkspace != null) { int workspaceEntryIndex = workspaces.indexOfKey(localWorkspace); if (workspaceEntryIndex == -1) { workspaces.put(localWorkspace, localInstallation == null ? ECollections.<Installation> emptyEList() : ECollections.singletonEList(localInstallation)); workspaces.move(0, workspaces.size() - 1); } else if (localInstallation != null) { EList<Installation> associatedInstallations = workspaces.get(workspaceEntryIndex).getValue(); int position = associatedInstallations.indexOf(localInstallation); if (position == -1) { associatedInstallations.add(0, localInstallation); } else { associatedInstallations.move(0, position); } workspaces.move(0, workspaceEntryIndex); } } try { resource.save(null); } catch (IOException ex) { SetupCorePlugin.INSTANCE.log(ex); } } private static <K extends EObject, V extends EObject> void removeProxies(EMap<K, EList<V>> map) { for (Iterator<Entry<K, EList<V>>> it = map.iterator(); it.hasNext();) { Entry<K, EList<V>> entry = it.next(); K key = entry.getKey(); if (key == null || key.eIsProxy()) { it.remove(); } else { for (Iterator<V> it2 = entry.getValue().iterator(); it2.hasNext();) { V value = it2.next(); if (value.eIsProxy()) { it2.remove(); } } } } } private static URI getStaticInstallLocation() { try { if (!Platform.isRunning()) { return URI.createFileURI(File.createTempFile("installation", "").toString()); } Location location = Platform.getInstallLocation(); URI result = getURI(location); if (OS.INSTANCE.isMac()) { result = result.trimSegments(1).appendSegment("Eclipse"); } return result; } catch (IOException ex) { throw new RuntimeException(ex); } } private static URI getURI(Location location) throws IOException { URI result = URI.createURI(FileLocator.resolve(location.getURL()).toString()); if (result.isFile()) { result = URI.createFileURI(result.toFileString()); } return result.hasTrailingPathSeparator() ? result.trimSegments(1) : result; } private static URI getStaticConfigurationLocation() { try { if (!Platform.isRunning()) { return URI.createFileURI(File.createTempFile(InstallationTaskImpl.CONFIGURATION_FOLDER_NAME, "").toString()); } Location location = Platform.getConfigurationLocation(); URI result = getURI(location); Location parentLocation = location.getParentLocation(); if (parentLocation != null) { URI targetInstallation = result.appendSegment(OOMPH_NODE).appendSegment("installation.setup"); File target = new File(targetInstallation.toFileString()); if (!target.exists()) { URI parentURI = getURI(parentLocation); URI sourceInstallation = parentURI.appendSegment(OOMPH_NODE).appendSegment("installation.setup"); File source = new File(sourceInstallation.toFileString()); if (source.exists()) { try { IOUtil.copyFile(source, target); } catch (IORuntimeException ex) { // Ignore. } } } } return result; } catch (IOException ex) { throw new IORuntimeException(ex); } } private enum Mode { NONE, CREATE, CREATE_AND_SAVE } private static Installation getInstallation(ResourceSet resourceSet, boolean realInstallation, Mode mode) { Installation installation = null; Resource installationResource = null; if (realInstallation) { if (resourceSet.getURIConverter().exists(INSTALLATION_SETUP_URI, null)) { installationResource = BaseUtil.loadResourceSafely(resourceSet, INSTALLATION_SETUP_URI); installation = (Installation)EcoreUtil.getObjectByType(installationResource.getContents(), SetupPackage.Literals.INSTALLATION); } } else { installationResource = resourceSet.getResource(INSTALLATION_SETUP_FILE_NAME_URI, false); if (installationResource == null) { installationResource = resourceSet.getResource(INSTALLATION_SETUP_URI, false); } if (installationResource != null) { installation = (Installation)installationResource.getContents().get(0); } } boolean save = false; if (installation == null && mode != Mode.NONE) { if (installationResource == null) { installationResource = resourceSet.createResource(realInstallation ? INSTALLATION_SETUP_URI : INSTALLATION_SETUP_FILE_NAME_URI); } else { installationResource.unload(); } installation = createInstallation(); installationResource.getContents().add(installation); save = mode == Mode.CREATE_AND_SAVE; } if (realInstallation && installation != null && installation.getProductVersion() == null) { ProductCatalog productCatalog = null; Resource indexResource = BaseUtil.loadResourceSafely(resourceSet, INDEX_SETUP_URI); Index index = (Index)EcoreUtil.getObjectByType(indexResource.getContents(), SetupPackage.Literals.INDEX); if (index != null) { EList<ProductCatalog> productCatalogs = index.getProductCatalogs(); if (!productCatalogs.isEmpty()) { productCatalog = productCatalogs.get(0); } } if (productCatalog == null) { Resource selfProductCatalogResource = BaseUtil.loadResourceSafely(resourceSet, URI.createURI("catalog:/self-product-catalog.setup")); productCatalog = (ProductCatalog)EcoreUtil.getObjectByType(selfProductCatalogResource.getContents(), SetupPackage.Literals.PRODUCT_CATALOG); } EList<Product> products = productCatalog.getProducts(); EList<ProductVersion> versions = products.get(0).getVersions(); installation.setProductVersion(versions.get(0)); if (save) { BaseUtil.saveEObject(installation); } } return installation; } private static Workspace getWorkspace(ResourceSet resourceSet, boolean realWorkspace, Mode mode) { Resource workspaceResource = null; Workspace workspace = null; if (realWorkspace) { if (resourceSet.getURIConverter().exists(WORKSPACE_SETUP_URI, null)) { workspaceResource = BaseUtil.loadResourceSafely(resourceSet, WORKSPACE_SETUP_URI); workspace = (Workspace)EcoreUtil.getObjectByType(workspaceResource.getContents(), SetupPackage.Literals.WORKSPACE); } } else { workspaceResource = resourceSet.getResource(WORKSPACE_SETUP_FILE_NAME_URI, false); if (workspaceResource == null && WORKSPACE_SETUP_URI != null) { workspaceResource = resourceSet.getResource(WORKSPACE_SETUP_URI, false); } if (workspaceResource != null) { workspace = (Workspace)workspaceResource.getContents().get(0); } } if (workspace == null && mode != Mode.NONE) { if (workspaceResource == null) { workspaceResource = resourceSet.createResource(realWorkspace ? WORKSPACE_SETUP_URI : WORKSPACE_SETUP_FILE_NAME_URI); } else { workspaceResource.unload(); } workspace = createWorkspace(); workspaceResource.getContents().add(workspace); if (mode == Mode.CREATE_AND_SAVE) { BaseUtil.saveEObject(workspace); } } return workspace; } private static User getUser(ResourceSet resourceSet, boolean demandCreate) { Resource userResource = null; User user = null; if (resourceSet.getURIConverter().exists(USER_SETUP_URI, null)) { userResource = BaseUtil.loadResourceSafely(resourceSet, USER_SETUP_URI); user = (User)EcoreUtil.getObjectByType(userResource.getContents(), SetupPackage.Literals.USER); } if (user == null && demandCreate) { if (userResource == null) { userResource = resourceSet.createResource(USER_SETUP_URI); } else { userResource.unload(); } user = createUser(); userResource.getContents().add(user); try { userResource.save(null); } catch (IOException ex) { throw new IORuntimeException(ex); } } return user; } private static SetupContext proxify(Installation installation, Workspace workspace, User user) { EcoreUtil.Copier copier = new EcoreUtil.Copier(false, false) { private static final long serialVersionUID = 1L; @Override protected void copyContainment(EReference eReference, EObject eObject, EObject copyEObject) { } @Override protected void copyProxyURI(EObject eObject, EObject copyEObject) { ((InternalEObject)copyEObject).eSetProxyURI(EcoreUtil.getURI(eObject)); } }; Installation installationCopy = (Installation)copier.copy(installation); if (installation != null) { copier.copy(installation.getProductVersion()); } Workspace workspaceCopy = (Workspace)copier.copy(workspace); if (workspace != null) { copier.copyAll(workspace.getStreams()); } User userCopy = (User)copier.copy(user); for (Map.Entry<EObject, EObject> entry : new LinkedHashSet<Map.Entry<EObject, EObject>>(copier.entrySet())) { EObject eObject = entry.getKey(); EObject copyEObject = entry.getValue(); for (EObject eContainer = eObject.eContainer(); eContainer != null; eContainer = eContainer.eContainer()) { EObject copyEContainer = copier.get(eContainer); if (copyEContainer == null) { copyEContainer = copier.copy(eContainer); } @SuppressWarnings("unchecked") InternalEList<EObject> list = (InternalEList<EObject>)copyEContainer.eGet(eObject.eContainmentFeature()); list.addUnique(copyEObject); eObject = eContainer; copyEObject = copyEContainer; } } copier.copyReferences(); return new SetupContext(installationCopy, workspaceCopy, userCopy); } /** * @author Eike Stepper */ private static class WorkspaceUtil { private static URI getStaticWorkspaceLocationURI() { try { IWorkspaceRoot workspaceRoot = EcorePlugin.getWorkspaceRoot(); return URI.createFileURI(workspaceRoot.getLocation().toOSString()); } catch (Throwable throwable) { return null; } } } }
[471731] Unskippable pop-up when starting IDE https://bugs.eclipse.org/bugs/show_bug.cgi?id=471731
plugins/org.eclipse.oomph.setup.core/src/org/eclipse/oomph/setup/internal/core/SetupContext.java
[471731] Unskippable pop-up when starting IDE
<ide><path>lugins/org.eclipse.oomph.setup.core/src/org/eclipse/oomph/setup/internal/core/SetupContext.java <ide> if (uri.segmentCount() > 3) <ide> { <ide> String eclipseLauncher = PropertiesUtil.getProperty("eclipse.launcher"); <del> if (eclipseLauncher == null) <del> { <del> throw new IllegalStateException("There is no eclipse.launcher property defined"); <del> } <del> <del> File eclipseLauncherExecutable = new File(eclipseLauncher); <del> if (eclipseLauncherExecutable.exists()) <del> { <del> effectiveInstallation = installation; <add> if (eclipseLauncher != null) <add> { <add> File eclipseLauncherExecutable = new File(eclipseLauncher); <add> if (eclipseLauncherExecutable.exists()) <add> { <add> effectiveInstallation = installation; <add> } <ide> } <ide> } <ide>
Java
apache-2.0
3287d4ca3c3b2715872c18e730529ea1299d47a8
0
alexismp/egress,alexismp/egress,alexismp/egress,alexismp/egress
/* * Copyright 2015 alexismp. * * 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.alexismp.egress; import com.firebase.client.AuthData; import com.firebase.client.DataSnapshot; import com.firebase.client.Firebase; import com.firebase.client.FirebaseError; import com.firebase.client.ValueEventListener; import com.firebase.geofire.GeoFire; import com.firebase.geofire.GeoLocation; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author alexismp */ public class addStationServlet extends HttpServlet { GeoFire geofire; Firebase firebase; Map<String, Object> emptyOwner = new HashMap<>(); Map<String, Object> randomOwner = new HashMap<>(); @Override public void init() throws ServletException { super.init(); firebase = new Firebase("https://shining-inferno-9452.firebaseio.com"); geofire = new GeoFire(firebase.child("_geofire")); login(); emptyOwner.put("owner", ""); randomOwner.put("owner", "[email protected]"); } /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (final PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet addStationServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Updating location for all stations... </h1>"); resetData(); out.println("<h1>... done.</h1>"); out.println("</body>"); out.println("</html>"); } } // adds Geofire location for all 6441 stations private void resetData() { for (int i = 1; i <= 6441; i++) { final String key = "" + i; // use single event listener so no further callbacks are made // (and there is no need to remove the event listener) firebase.child(key).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { // Add an empty "owner" attribute to existing data // randomly set this attribute to "[email protected]" int random = (int) (Math.random() * 3); if (random % 3 == 0) { snapshot.getRef().updateChildren(emptyOwner); } else { snapshot.getRef().updateChildren(randomOwner); } // Adding Geofire data to firebase (under "[root]/_geofire" ) System.out.println("Adding station [" + key + "] to Geofire ... "); GeoLocation location = new GeoLocation( Float.parseFloat(snapshot.child("LATITUDE").getValue().toString()), Float.parseFloat(snapshot.child("LONGITUDE").getValue().toString())); geofire.setLocation(key, location); } @Override public void onCancelled(FirebaseError error) { } }); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> private void login() { System.out.println("Loging in..."); firebase.authWithPassword("[email protected]", "foo", new Firebase.AuthResultHandler() { @Override public void onAuthenticated(AuthData authData) { System.out.println("Authenticated with password : " + authData.getProviderData().get("displayName")); // Authentication just completed successfully :) } @Override public void onAuthenticationError(FirebaseError error) { // Something went wrong :( } }); firebase.authWithOAuthToken("google", "<OAuth Token>", new Firebase.AuthResultHandler() { @Override public void onAuthenticated(AuthData authData) { System.out.println("Authenticated with Google: " + authData); // the Google user is now authenticated with Firebase } @Override public void onAuthenticationError(FirebaseError firebaseError) { // there was an error } }); } }
src/main/java/org/alexismp/egress/addStationServlet.java
/* * Copyright 2015 alexismp. * * 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.alexismp.egress; import com.firebase.client.DataSnapshot; import com.firebase.client.Firebase; import com.firebase.client.FirebaseError; import com.firebase.client.ValueEventListener; import com.firebase.geofire.GeoFire; import com.firebase.geofire.GeoLocation; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author alexismp */ public class addStationServlet extends HttpServlet { GeoFire geofire; Firebase firebase; Map<String, Object> emptyOwner = new HashMap<>(); Map<String, Object> randomOwner = new HashMap<>(); @Override public void init() throws ServletException { super.init(); firebase = new Firebase("https://shining-inferno-9452.firebaseio.com"); geofire = new GeoFire(firebase.child("_geofire")); emptyOwner.put("owner", ""); randomOwner.put("owner", "[email protected]"); } /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (final PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet addStationServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Updating location for all stations... </h1>"); for (int i = 1; i <= 6441; i++) { final String key = "" + i; firebase.child(key).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { System.out.println(snapshot.getValue()); // reset values and add some random values int random = (int) (Math.random() * 3); if (random % 3 == 0) { snapshot.getRef().updateChildren(emptyOwner); } else { snapshot.getRef().updateChildren(randomOwner); } System.out.println("Adding station [" + key + "] to Geofire ... "); GeoLocation location = new GeoLocation( Float.parseFloat(snapshot.child("LATITUDE").getValue().toString()), Float.parseFloat(snapshot.child("LONGITUDE").getValue().toString())); geofire.setLocation(key, location); } @Override public void onCancelled(FirebaseError error) { } }); } out.println("<h1>... done.</h1>"); out.println("</body>"); out.println("</html>"); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
modularization before removing servlet altogether
src/main/java/org/alexismp/egress/addStationServlet.java
modularization before removing servlet altogether
<ide><path>rc/main/java/org/alexismp/egress/addStationServlet.java <ide> */ <ide> package org.alexismp.egress; <ide> <add>import com.firebase.client.AuthData; <ide> import com.firebase.client.DataSnapshot; <ide> import com.firebase.client.Firebase; <ide> import com.firebase.client.FirebaseError; <ide> super.init(); <ide> firebase = new Firebase("https://shining-inferno-9452.firebaseio.com"); <ide> geofire = new GeoFire(firebase.child("_geofire")); <add> login(); <ide> emptyOwner.put("owner", ""); <ide> randomOwner.put("owner", "[email protected]"); <ide> } <ide> out.println("<body>"); <ide> out.println("<h1>Updating location for all stations... </h1>"); <ide> <del> for (int i = 1; i <= 6441; i++) { <del> final String key = "" + i; <del> firebase.child(key).addValueEventListener(new ValueEventListener() { <del> @Override <del> public void onDataChange(DataSnapshot snapshot) { <del> System.out.println(snapshot.getValue()); <del> // reset values and add some random values <del> int random = (int) (Math.random() * 3); <del> if (random % 3 == 0) { <del> snapshot.getRef().updateChildren(emptyOwner); <del> } else { <del> snapshot.getRef().updateChildren(randomOwner); <del> } <del> <del> System.out.println("Adding station [" + key + "] to Geofire ... "); <del> GeoLocation location = new GeoLocation( <del> Float.parseFloat(snapshot.child("LATITUDE").getValue().toString()), <del> Float.parseFloat(snapshot.child("LONGITUDE").getValue().toString())); <del> geofire.setLocation(key, location); <del> } <del> <del> @Override <del> public void onCancelled(FirebaseError error) { <del> } <del> }); <del> <del> } <add> resetData(); <ide> <ide> out.println("<h1>... done.</h1>"); <ide> out.println("</body>"); <ide> out.println("</html>"); <add> } <add> } <add> <add> // adds Geofire location for all 6441 stations <add> private void resetData() { <add> for (int i = 1; i <= 6441; i++) { <add> final String key = "" + i; <add> // use single event listener so no further callbacks are made <add> // (and there is no need to remove the event listener) <add> firebase.child(key).addListenerForSingleValueEvent(new ValueEventListener() { <add> @Override <add> public void onDataChange(DataSnapshot snapshot) { <add> // Add an empty "owner" attribute to existing data <add> // randomly set this attribute to "[email protected]" <add> int random = (int) (Math.random() * 3); <add> if (random % 3 == 0) { <add> snapshot.getRef().updateChildren(emptyOwner); <add> } else { <add> snapshot.getRef().updateChildren(randomOwner); <add> } <add> <add> // Adding Geofire data to firebase (under "[root]/_geofire" ) <add> System.out.println("Adding station [" + key + "] to Geofire ... "); <add> GeoLocation location = new GeoLocation( <add> Float.parseFloat(snapshot.child("LATITUDE").getValue().toString()), <add> Float.parseFloat(snapshot.child("LONGITUDE").getValue().toString())); <add> geofire.setLocation(key, location); <add> } <add> <add> @Override <add> public void onCancelled(FirebaseError error) { <add> } <add> }); <add> <ide> } <ide> } <ide> <ide> return "Short description"; <ide> }// </editor-fold> <ide> <add> private void login() { <add> System.out.println("Loging in..."); <add> firebase.authWithPassword("[email protected]", "foo", <add> new Firebase.AuthResultHandler() { <add> @Override <add> public void onAuthenticated(AuthData authData) { <add> System.out.println("Authenticated with password : " + authData.getProviderData().get("displayName")); <add> // Authentication just completed successfully :) <add> } <add> <add> @Override <add> public void onAuthenticationError(FirebaseError error) { <add> // Something went wrong :( <add> } <add> }); <add> <add> firebase.authWithOAuthToken("google", "<OAuth Token>", new Firebase.AuthResultHandler() { <add> @Override <add> public void onAuthenticated(AuthData authData) { <add> System.out.println("Authenticated with Google: " + authData); <add> // the Google user is now authenticated with Firebase <add> } <add> <add> @Override <add> public void onAuthenticationError(FirebaseError firebaseError) { <add> // there was an error <add> } <add> }); <add> } <add> <ide> }
Java
apache-2.0
cd1e923c905a3530d71ff4f85259649fbf560c6d
0
foam-framework/foam2,foam-framework/foam2,jacksonic/vjlofvhjfgm,foam-framework/foam2,jacksonic/vjlofvhjfgm,foam-framework/foam2,jacksonic/vjlofvhjfgm,foam-framework/foam2
/** * @license * Copyright 2018 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ package foam.dao; import foam.core.X; import foam.nanos.auth.*; import foam.test.TestObj; import foam.test.TestUtils; import foam.util.Auth; import java.util.List; public class AuthenticatedDAOTest extends foam.nanos.test.Test { private Group basicUserGroup_; private Group adminGroup_; private User testUser_; private DAO userDAO_; private String INVALID_DAO_MESSAGE = "When using a DAO decorated by AuthenticatedDAO, you may only call the context-oriented methods: put_(), find_(), select_(), remove_(), removeAll_(), pipe_(), and listen_(). Alternatively, you can also use .inX() to set the context on the DAO."; public void runTest(X x) { x = getTestingSubcontext(x); AuthenticatedDAO_NonContextMethods_findThrowsException(x); AuthenticatedDAO_NonContextMethods_putThrowsException(x); AuthenticatedDAO_NonContextMethods_removeThrowsException(x); AuthenticatedDAO_NonContextMethods_removeAllThrowsException(x); AuthenticatedDAO_NonContextMethods_selectThrowsException(x); // Set the test user to be part of a basic user group with no permissions. testUser_.setGroup(basicUserGroup_.getId()); userDAO_.put(testUser_); X basicUserContext = Auth.sudo(x, testUser_); AuthenticatedDAO_ContextMethods_UnauthorizedUser_find(basicUserContext); AuthenticatedDAO_ContextMethods_UnauthorizedUser_put(basicUserContext); AuthenticatedDAO_ContextMethods_UnauthorizedUser_remove(basicUserContext); AuthenticatedDAO_ContextMethods_UnauthorizedUser_removeAll(basicUserContext); AuthenticatedDAO_ContextMethods_UnauthorizedUser_select(basicUserContext); // Set the test user to be part of a user group with all permissions. testUser_.setGroup(adminGroup_.getId()); userDAO_.put(testUser_); X adminUserContext = Auth.sudo(x, testUser_); AuthenticatedDAO_ContextMethods_AuthorizedUser_find(adminUserContext); AuthenticatedDAO_ContextMethods_AuthorizedUser_put_create(adminUserContext); AuthenticatedDAO_ContextMethods_AuthorizedUser_put_update(adminUserContext); AuthenticatedDAO_ContextMethods_AuthorizedUser_remove(adminUserContext); AuthenticatedDAO_ContextMethods_AuthorizedUser_removeAll(adminUserContext); AuthenticatedDAO_ContextMethods_AuthorizedUser_select(adminUserContext); } private X getTestingSubcontext(X x) { // Mock the userDAO and put a test user in it. x = TestUtils.mockDAO(x, "localUserDAO"); userDAO_ = (DAO) x.get("localUserDAO"); testUser_ = TestUtils.createTestUser(); userDAO_.put(testUser_); // Mock the groupDAO. x = TestUtils.mockDAO(x, "localGroupDAO"); DAO groupDAO = (DAO) x.get("localGroupDAO"); // Put a group in the groupDAO with permission to read, update, and delete the testObjDAO. Permission adminPermissions[] = new Permission[5]; Permission READ_PERMISSION = new Permission(); Permission CREATE_PERMISSION = new Permission(); Permission UPDATE_PERMISSION = new Permission(); Permission REMOVE_PERMISSION = new Permission(); Permission DELETE_PERMISSION = new Permission(); READ_PERMISSION.setId("testObj.read.*"); CREATE_PERMISSION.setId("testObj.create"); UPDATE_PERMISSION.setId("testObj.update.*"); REMOVE_PERMISSION.setId("testObj.remove.*"); DELETE_PERMISSION.setId("testObj.delete.*"); adminPermissions[0] = READ_PERMISSION; adminPermissions[1] = CREATE_PERMISSION; adminPermissions[2] = UPDATE_PERMISSION; adminPermissions[3] = REMOVE_PERMISSION; adminPermissions[4] = DELETE_PERMISSION; adminGroup_ = new Group(); adminGroup_.setId("admin"); adminGroup_.setEnabled(true); adminGroup_.setPermissions(adminPermissions); groupDAO.put(adminGroup_); // Put a group in the groupDAO with permission to read only one specific testObj. Permission basicUserPermissions[] = new Permission[3]; Permission READ_SPECIFIC_TESTOBJ = new Permission(); Permission DELETE_SPECIFIC_TESTOBJ = new Permission(); Permission REMOVE_SPECIFIC_TESTOBJ = new Permission(); READ_SPECIFIC_TESTOBJ.setId("testObj.read.public"); DELETE_SPECIFIC_TESTOBJ.setId("testObj.delete.public"); REMOVE_SPECIFIC_TESTOBJ.setId("testObj.remove.public"); basicUserPermissions[0] = READ_SPECIFIC_TESTOBJ; basicUserPermissions[1] = DELETE_SPECIFIC_TESTOBJ; basicUserPermissions[2] = REMOVE_SPECIFIC_TESTOBJ; basicUserGroup_ = new Group(); basicUserGroup_.setId("basic"); basicUserGroup_.setEnabled(true); basicUserGroup_.setPermissions(basicUserPermissions); groupDAO.put(basicUserGroup_); // Mock the AuthService. UserAndGroupAuthService auth = new UserAndGroupAuthService(x); auth.start(); x = x.put("auth", auth); return x; } private void AuthenticatedDAO_NonContextMethods_findThrowsException(X x) { // Create the decorated DAO to test. DAO testObjDAO = new MDAO(TestObj.getOwnClassInfo()); ProxyDAO dao = new AuthenticatedDAO("testObj", testObjDAO); // Populate the DAO: Put something in to try to find. TestObj testObj = new TestObj.Builder(x).setId("123").build(); testObjDAO.put(testObj); test( TestUtils.testThrows( () -> dao.find(testObj), INVALID_DAO_MESSAGE, AuthorizationException.class ), "Should throw 'AuthorizationException' with appropriate message when a user tries to 'find' from the DAO." ); } private void AuthenticatedDAO_NonContextMethods_putThrowsException(X x) { // Create the decorated DAO to test. DAO testObjDAO = new MDAO(TestObj.getOwnClassInfo()); ProxyDAO dao = new AuthenticatedDAO("testObj", testObjDAO); // Create an object to try to put. TestObj testObj = new TestObj.Builder(x).setId("123").build(); test( TestUtils.testThrows( () -> dao.put(testObj), INVALID_DAO_MESSAGE, AuthorizationException.class ), "Should throw 'AuthorizationException' with appropriate message when a user tries to 'put' to the DAO." ); } private void AuthenticatedDAO_NonContextMethods_removeThrowsException(X x) { // Create the decorated DAO to test. DAO testObjDAO = new MDAO(TestObj.getOwnClassInfo()); ProxyDAO dao = new AuthenticatedDAO("testObj", testObjDAO); // Create an object to try to remove. TestObj testObj = new TestObj.Builder(x).setId("123").build(); testObjDAO.put(testObj); test( TestUtils.testThrows( () -> dao.remove(testObj), INVALID_DAO_MESSAGE, AuthorizationException.class ), "Should throw 'AuthorizationException' with appropriate message when a user tries to 'remove' from the DAO." ); } private void AuthenticatedDAO_NonContextMethods_removeAllThrowsException(X x) { // Create the decorated DAO to test. DAO testObjDAO = new MDAO(TestObj.getOwnClassInfo()); ProxyDAO dao = new AuthenticatedDAO("testObj", testObjDAO); // Create an object to try to remove. TestObj testObj = new TestObj.Builder(x).setId("123").build(); testObjDAO.put(testObj); test( TestUtils.testThrows( dao::removeAll, INVALID_DAO_MESSAGE, AuthorizationException.class ), "Should throw 'AuthorizationException' with appropriate message when a user tries to 'removeAll' from the DAO." ); } private void AuthenticatedDAO_NonContextMethods_selectThrowsException(X x) { // Create the decorated DAO to test. DAO testObjDAO = new MDAO(TestObj.getOwnClassInfo()); ProxyDAO dao = new AuthenticatedDAO("testObj", testObjDAO); // Create an object to try to select. TestObj testObj = new TestObj.Builder(x).setId("123").build(); testObjDAO.put(testObj); test( TestUtils.testThrows( dao::select, INVALID_DAO_MESSAGE, AuthorizationException.class ), "Should throw 'AuthorizationException' with appropriate message when a user tries to 'select' from the DAO." ); } private void AuthenticatedDAO_ContextMethods_UnauthorizedUser_find(X x) { // Create the decorated DAO to test. DAO testObjDAO = new MDAO(TestObj.getOwnClassInfo()); ProxyDAO dao = new AuthenticatedDAO("testObj", testObjDAO); // Create an object to try to select. TestObj testObj = new TestObj.Builder(x).setId("123").build(); testObjDAO.put(testObj); test( TestUtils.testThrows( () -> dao.find_(x, testObj), "Permission denied.", AuthorizationException.class ), "Should throw 'AuthorizationException' with appropriate message when an unauthenticated user tries to 'find_' from the DAO." ); } private void AuthenticatedDAO_ContextMethods_UnauthorizedUser_put(X x) { // Create the decorated DAO to test. DAO testObjDAO = new MDAO(TestObj.getOwnClassInfo()); ProxyDAO dao = new AuthenticatedDAO("testObj", testObjDAO); // Create an object to try to put. TestObj testObj = new TestObj.Builder(x).setId("123").build(); test( TestUtils.testThrows( () -> dao.put_(x, testObj), "Permission denied.", AuthorizationException.class ), "Should throw 'AuthorizationException' with appropriate message when an unauthenticated user tries to 'put_' to the DAO." ); } private void AuthenticatedDAO_ContextMethods_UnauthorizedUser_remove(X x) { // Create the decorated DAO to test. DAO testObjDAO = new MDAO(TestObj.getOwnClassInfo()); ProxyDAO dao = new AuthenticatedDAO("testObj", testObjDAO); // Create an object to try to remove. TestObj testObj = new TestObj.Builder(x).setId("123").build(); testObjDAO.put(testObj); test( TestUtils.testThrows( () -> dao.remove_(x, testObj), "Permission denied.", AuthorizationException.class ), "Should throw 'AuthorizationException' with appropriate message when an unauthenticated user tries to 'remove_' from the DAO." ); } private void AuthenticatedDAO_ContextMethods_UnauthorizedUser_select(X x) { // Create the decorated DAO to test. DAO testObjDAO = new MDAO(TestObj.getOwnClassInfo()); ProxyDAO dao = new AuthenticatedDAO("testObj", testObjDAO); // Put an object that the user should be allowed to read. TestObj publicTestObj = new TestObj.Builder(x).setId("public").setDescription("Basic user has permission to read this").build(); testObjDAO.put(publicTestObj); // Put an object that the user should not be allowed to read. TestObj privateTestObj = new TestObj.Builder(x).setId("private").setDescription("Basic user does not have permission to read this").build(); testObjDAO.put(privateTestObj); ArraySink sink = new ArraySink(); dao.select_(x, sink, 0, 1000, null, null); List arr = sink.getArray(); test(arr.size() == 1 && arr.get(0).equals(publicTestObj), "When a user uses the 'select_' method, it should only return the objects that the user has permission to read."); } private void AuthenticatedDAO_ContextMethods_UnauthorizedUser_removeAll(X x) { // Create the decorated DAO to test. DAO testObjDAO = new MDAO(TestObj.getOwnClassInfo()); ProxyDAO dao = new AuthenticatedDAO("testObj", testObjDAO); // Put an object that the user should be allowed to read. TestObj publicTestObj = new TestObj.Builder(x).setId("public").setDescription("Basic user has permission to read this").build(); testObjDAO.put(publicTestObj); // Put an object that the user should not be allowed to read. TestObj privateTestObj = new TestObj.Builder(x).setId("private").setDescription("Basic user does not have permission to read this").build(); testObjDAO.put(privateTestObj); // Call removeAll_ as a basic user. dao.removeAll_(x, 0, 1000, null, null); // Select on the underlying DAO to see if it was removed. ArraySink sink = new ArraySink(); testObjDAO.select(sink); List arr = sink.getArray(); test(arr.size() == 1 && arr.get(0).equals(privateTestObj), "When a user uses the 'removeAll_' method, it should only remove the objects that the user has permission to delete."); } private void AuthenticatedDAO_ContextMethods_AuthorizedUser_find(X x) { // Create the decorated DAO to test. DAO testObjDAO = new MDAO(TestObj.getOwnClassInfo()); ProxyDAO dao = new AuthenticatedDAO("testObj", testObjDAO); // Create an object to try to find. TestObj testObj = new TestObj.Builder(x).setId("123").build(); testObjDAO.put(testObj); try { TestObj result = (TestObj) dao.find_(x, testObj); test(result.equals(testObj), "User with 'testObjDAO.read.*' permission can use 'find_' method."); } catch (Throwable t) { test(false, "User with 'testObj.read.*' permission using 'find_' method should not throw an exception."); t.printStackTrace(); } } private void AuthenticatedDAO_ContextMethods_AuthorizedUser_put_create(X x) { // Create the decorated DAO to test. DAO testObjDAO = new MDAO(TestObj.getOwnClassInfo()); ProxyDAO dao = new AuthenticatedDAO("testObj", testObjDAO); try { TestObj testObj = new TestObj.Builder(x).setId("123").build(); TestObj result = (TestObj) dao.put_(x, testObj); test(result.equals(testObj), "User with 'testObjDAO.create' permission can use 'put_' method to create a new object."); } catch (Throwable t) { test(false, "User with 'testObj.create' permission using 'put_' method to create a new object should not throw an exception."); t.printStackTrace(); } } private void AuthenticatedDAO_ContextMethods_AuthorizedUser_put_update(X x) { // Create the decorated DAO to test. DAO testObjDAO = new MDAO(TestObj.getOwnClassInfo()); ProxyDAO dao = new AuthenticatedDAO("testObj", testObjDAO); // Create an object to try to update. TestObj testObj = new TestObj.Builder(x).setId("123").setDescription("Initial").build(); testObjDAO.put(testObj); try { testObj.setDescription("Updated value"); TestObj result = (TestObj) dao.put_(x, testObj); test(result.equals(testObj), "User with 'testObjDAO.update.*' permission can use 'put_' method to update an existing object."); } catch (Throwable t) { test(false, "User with 'testObj.update.*' permission using 'put_' method to update an existing object should not throw an exception."); t.printStackTrace(); } } private void AuthenticatedDAO_ContextMethods_AuthorizedUser_remove(X x) { // Create the decorated DAO to test. DAO testObjDAO = new MDAO(TestObj.getOwnClassInfo()); ProxyDAO dao = new AuthenticatedDAO("testObj", testObjDAO); // Create an object to try to remove. TestObj testObj = new TestObj.Builder(x).setId("123").build(); testObjDAO.put(testObj); try { TestObj result = (TestObj) dao.remove_(x, testObj); test(result.equals(testObj), "User with 'testObj.remove.*' permission can use 'remove_' method to remove an existing object."); TestObj findResult = (TestObj) testObjDAO.find(testObj.getId()); assert findResult == null; } catch (Throwable t) { test(false, "User with 'testObj.remove.*' permission using 'remove_' method to remove an existing object should not throw an exception."); t.printStackTrace(); } } private void AuthenticatedDAO_ContextMethods_AuthorizedUser_removeAll(X x) { // Create the decorated DAO to test. DAO testObjDAO = new MDAO(TestObj.getOwnClassInfo()); ProxyDAO dao = new AuthenticatedDAO("testObj", testObjDAO); // Create an object to try to remove. TestObj testObj = new TestObj.Builder(x).setId("123").build(); testObjDAO.put(testObj); try { dao.removeAll_(x, 0, 1000, null, null); ArraySink sink = new ArraySink(); testObjDAO.select(sink); List arr = sink.getArray(); test(arr.size() == 0, "User with 'testObj.delete.* permission should be able to use 'removeAll_' method to remove all existing objects."); } catch (Throwable t) { test(false, "User with 'testObj.delete' permission using 'removeAll_' method to remove all existing objects should not throw an exception."); t.printStackTrace(); } } private void AuthenticatedDAO_ContextMethods_AuthorizedUser_select(X x) { // Create the decorated DAO to test. DAO testObjDAO = new MDAO(TestObj.getOwnClassInfo()); ProxyDAO dao = new AuthenticatedDAO("testObj", testObjDAO); // Create an object to try to select. TestObj testObj = new TestObj.Builder(x).setId("123").build(); testObjDAO.put(testObj); try { ArraySink sink = new ArraySink(); ArraySink result = (ArraySink) dao.select_(x, sink, 0, 1000, null, null); List arr = result.getArray(); test(arr.size() == 1 && arr.get(0).equals(testObj), "User with 'testObjDAO.read.*' permission can use 'select_' method."); } catch (Throwable t) { test(false, "User with 'testObj.read.*' permission using 'select_' method should not throw an exception."); t.printStackTrace(); } } }
src/foam/dao/AuthenticatedDAOTest.java
/** * @license * Copyright 2018 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ package foam.dao; import foam.core.X; import foam.nanos.auth.*; import foam.test.TestObj; import foam.test.TestUtils; import foam.util.Auth; import java.util.List; public class AuthenticatedDAOTest extends foam.nanos.test.Test { private Group basicUserGroup_; private Group adminGroup_; private User testUser_; private DAO userDAO_; private String INVALID_DAO_MESSAGE = "When using a DAO decorated by AuthenticatedDAO, you may only call the context-oriented methods: put_(), find_(), select_(), remove_(), removeAll_(), pipe_(), and listen_(). Alternatively, you can also use .inX() to set the context on the DAO."; public void runTest(X x) { x = getTestingSubcontext(x); AuthenticatedDAO_NonContextMethods_findThrowsException(x); AuthenticatedDAO_NonContextMethods_putThrowsException(x); AuthenticatedDAO_NonContextMethods_removeThrowsException(x); AuthenticatedDAO_NonContextMethods_removeAllThrowsException(x); AuthenticatedDAO_NonContextMethods_selectThrowsException(x); // Set the test user to be part of a basic user group with no permissions. testUser_.setGroup(basicUserGroup_.getId()); userDAO_.put(testUser_); X basicUserContext = Auth.sudo(x, testUser_); AuthenticatedDAO_ContextMethods_UnauthorizedUser_find(basicUserContext); AuthenticatedDAO_ContextMethods_UnauthorizedUser_put(basicUserContext); AuthenticatedDAO_ContextMethods_UnauthorizedUser_remove(basicUserContext); AuthenticatedDAO_ContextMethods_UnauthorizedUser_removeAll(basicUserContext); AuthenticatedDAO_ContextMethods_UnauthorizedUser_select(basicUserContext); // Set the test user to be part of a user group with all permissions. testUser_.setGroup(adminGroup_.getId()); userDAO_.put(testUser_); X adminUserContext = Auth.sudo(x, testUser_); AuthenticatedDAO_ContextMethods_AuthorizedUser_find(adminUserContext); AuthenticatedDAO_ContextMethods_AuthorizedUser_put_create(adminUserContext); AuthenticatedDAO_ContextMethods_AuthorizedUser_put_update(adminUserContext); AuthenticatedDAO_ContextMethods_AuthorizedUser_remove(adminUserContext); AuthenticatedDAO_ContextMethods_AuthorizedUser_removeAll(adminUserContext); AuthenticatedDAO_ContextMethods_AuthorizedUser_select(adminUserContext); } private X getTestingSubcontext(X x) { // Mock the userDAO and put a test user in it. x = TestUtils.mockDAO(x, "localUserDAO"); userDAO_ = (DAO) x.get("localUserDAO"); testUser_ = TestUtils.createTestUser(); userDAO_.put(testUser_); // Mock the groupDAO. x = TestUtils.mockDAO(x, "groupDAO"); DAO groupDAO = (DAO) x.get("groupDAO"); // Put a group in the groupDAO with permission to read, update, and delete the testObjDAO. Permission adminPermissions[] = new Permission[5]; Permission READ_PERMISSION = new Permission(); Permission CREATE_PERMISSION = new Permission(); Permission UPDATE_PERMISSION = new Permission(); Permission REMOVE_PERMISSION = new Permission(); Permission DELETE_PERMISSION = new Permission(); READ_PERMISSION.setId("testObj.read.*"); CREATE_PERMISSION.setId("testObj.create"); UPDATE_PERMISSION.setId("testObj.update.*"); REMOVE_PERMISSION.setId("testObj.remove.*"); DELETE_PERMISSION.setId("testObj.delete.*"); adminPermissions[0] = READ_PERMISSION; adminPermissions[1] = CREATE_PERMISSION; adminPermissions[2] = UPDATE_PERMISSION; adminPermissions[3] = REMOVE_PERMISSION; adminPermissions[4] = DELETE_PERMISSION; adminGroup_ = new Group(); adminGroup_.setId("admin"); adminGroup_.setEnabled(true); adminGroup_.setPermissions(adminPermissions); groupDAO.put(adminGroup_); // Put a group in the groupDAO with permission to read only one specific testObj. Permission basicUserPermissions[] = new Permission[3]; Permission READ_SPECIFIC_TESTOBJ = new Permission(); Permission DELETE_SPECIFIC_TESTOBJ = new Permission(); Permission REMOVE_SPECIFIC_TESTOBJ = new Permission(); READ_SPECIFIC_TESTOBJ.setId("testObj.read.public"); DELETE_SPECIFIC_TESTOBJ.setId("testObj.delete.public"); REMOVE_SPECIFIC_TESTOBJ.setId("testObj.remove.public"); basicUserPermissions[0] = READ_SPECIFIC_TESTOBJ; basicUserPermissions[1] = DELETE_SPECIFIC_TESTOBJ; basicUserPermissions[2] = REMOVE_SPECIFIC_TESTOBJ; basicUserGroup_ = new Group(); basicUserGroup_.setId("basic"); basicUserGroup_.setEnabled(true); basicUserGroup_.setPermissions(basicUserPermissions); groupDAO.put(basicUserGroup_); // Mock the AuthService. UserAndGroupAuthService auth = new UserAndGroupAuthService(x); auth.start(); x = x.put("auth", auth); return x; } private void AuthenticatedDAO_NonContextMethods_findThrowsException(X x) { // Create the decorated DAO to test. DAO testObjDAO = new MDAO(TestObj.getOwnClassInfo()); ProxyDAO dao = new AuthenticatedDAO("testObj", testObjDAO); // Populate the DAO: Put something in to try to find. TestObj testObj = new TestObj.Builder(x).setId("123").build(); testObjDAO.put(testObj); test( TestUtils.testThrows( () -> dao.find(testObj), INVALID_DAO_MESSAGE, AuthorizationException.class ), "Should throw 'AuthorizationException' with appropriate message when a user tries to 'find' from the DAO." ); } private void AuthenticatedDAO_NonContextMethods_putThrowsException(X x) { // Create the decorated DAO to test. DAO testObjDAO = new MDAO(TestObj.getOwnClassInfo()); ProxyDAO dao = new AuthenticatedDAO("testObj", testObjDAO); // Create an object to try to put. TestObj testObj = new TestObj.Builder(x).setId("123").build(); test( TestUtils.testThrows( () -> dao.put(testObj), INVALID_DAO_MESSAGE, AuthorizationException.class ), "Should throw 'AuthorizationException' with appropriate message when a user tries to 'put' to the DAO." ); } private void AuthenticatedDAO_NonContextMethods_removeThrowsException(X x) { // Create the decorated DAO to test. DAO testObjDAO = new MDAO(TestObj.getOwnClassInfo()); ProxyDAO dao = new AuthenticatedDAO("testObj", testObjDAO); // Create an object to try to remove. TestObj testObj = new TestObj.Builder(x).setId("123").build(); testObjDAO.put(testObj); test( TestUtils.testThrows( () -> dao.remove(testObj), INVALID_DAO_MESSAGE, AuthorizationException.class ), "Should throw 'AuthorizationException' with appropriate message when a user tries to 'remove' from the DAO." ); } private void AuthenticatedDAO_NonContextMethods_removeAllThrowsException(X x) { // Create the decorated DAO to test. DAO testObjDAO = new MDAO(TestObj.getOwnClassInfo()); ProxyDAO dao = new AuthenticatedDAO("testObj", testObjDAO); // Create an object to try to remove. TestObj testObj = new TestObj.Builder(x).setId("123").build(); testObjDAO.put(testObj); test( TestUtils.testThrows( dao::removeAll, INVALID_DAO_MESSAGE, AuthorizationException.class ), "Should throw 'AuthorizationException' with appropriate message when a user tries to 'removeAll' from the DAO." ); } private void AuthenticatedDAO_NonContextMethods_selectThrowsException(X x) { // Create the decorated DAO to test. DAO testObjDAO = new MDAO(TestObj.getOwnClassInfo()); ProxyDAO dao = new AuthenticatedDAO("testObj", testObjDAO); // Create an object to try to select. TestObj testObj = new TestObj.Builder(x).setId("123").build(); testObjDAO.put(testObj); test( TestUtils.testThrows( dao::select, INVALID_DAO_MESSAGE, AuthorizationException.class ), "Should throw 'AuthorizationException' with appropriate message when a user tries to 'select' from the DAO." ); } private void AuthenticatedDAO_ContextMethods_UnauthorizedUser_find(X x) { // Create the decorated DAO to test. DAO testObjDAO = new MDAO(TestObj.getOwnClassInfo()); ProxyDAO dao = new AuthenticatedDAO("testObj", testObjDAO); // Create an object to try to select. TestObj testObj = new TestObj.Builder(x).setId("123").build(); testObjDAO.put(testObj); test( TestUtils.testThrows( () -> dao.find_(x, testObj), "Permission denied.", AuthorizationException.class ), "Should throw 'AuthorizationException' with appropriate message when an unauthenticated user tries to 'find_' from the DAO." ); } private void AuthenticatedDAO_ContextMethods_UnauthorizedUser_put(X x) { // Create the decorated DAO to test. DAO testObjDAO = new MDAO(TestObj.getOwnClassInfo()); ProxyDAO dao = new AuthenticatedDAO("testObj", testObjDAO); // Create an object to try to put. TestObj testObj = new TestObj.Builder(x).setId("123").build(); test( TestUtils.testThrows( () -> dao.put_(x, testObj), "Permission denied.", AuthorizationException.class ), "Should throw 'AuthorizationException' with appropriate message when an unauthenticated user tries to 'put_' to the DAO." ); } private void AuthenticatedDAO_ContextMethods_UnauthorizedUser_remove(X x) { // Create the decorated DAO to test. DAO testObjDAO = new MDAO(TestObj.getOwnClassInfo()); ProxyDAO dao = new AuthenticatedDAO("testObj", testObjDAO); // Create an object to try to remove. TestObj testObj = new TestObj.Builder(x).setId("123").build(); testObjDAO.put(testObj); test( TestUtils.testThrows( () -> dao.remove_(x, testObj), "Permission denied.", AuthorizationException.class ), "Should throw 'AuthorizationException' with appropriate message when an unauthenticated user tries to 'remove_' from the DAO." ); } private void AuthenticatedDAO_ContextMethods_UnauthorizedUser_select(X x) { // Create the decorated DAO to test. DAO testObjDAO = new MDAO(TestObj.getOwnClassInfo()); ProxyDAO dao = new AuthenticatedDAO("testObj", testObjDAO); // Put an object that the user should be allowed to read. TestObj publicTestObj = new TestObj.Builder(x).setId("public").setDescription("Basic user has permission to read this").build(); testObjDAO.put(publicTestObj); // Put an object that the user should not be allowed to read. TestObj privateTestObj = new TestObj.Builder(x).setId("private").setDescription("Basic user does not have permission to read this").build(); testObjDAO.put(privateTestObj); ArraySink sink = new ArraySink(); dao.select_(x, sink, 0, 1000, null, null); List arr = sink.getArray(); test(arr.size() == 1 && arr.get(0).equals(publicTestObj), "When a user uses the 'select_' method, it should only return the objects that the user has permission to read."); } private void AuthenticatedDAO_ContextMethods_UnauthorizedUser_removeAll(X x) { // Create the decorated DAO to test. DAO testObjDAO = new MDAO(TestObj.getOwnClassInfo()); ProxyDAO dao = new AuthenticatedDAO("testObj", testObjDAO); // Put an object that the user should be allowed to read. TestObj publicTestObj = new TestObj.Builder(x).setId("public").setDescription("Basic user has permission to read this").build(); testObjDAO.put(publicTestObj); // Put an object that the user should not be allowed to read. TestObj privateTestObj = new TestObj.Builder(x).setId("private").setDescription("Basic user does not have permission to read this").build(); testObjDAO.put(privateTestObj); // Call removeAll_ as a basic user. dao.removeAll_(x, 0, 1000, null, null); // Select on the underlying DAO to see if it was removed. ArraySink sink = new ArraySink(); testObjDAO.select(sink); List arr = sink.getArray(); test(arr.size() == 1 && arr.get(0).equals(privateTestObj), "When a user uses the 'removeAll_' method, it should only remove the objects that the user has permission to delete."); } private void AuthenticatedDAO_ContextMethods_AuthorizedUser_find(X x) { // Create the decorated DAO to test. DAO testObjDAO = new MDAO(TestObj.getOwnClassInfo()); ProxyDAO dao = new AuthenticatedDAO("testObj", testObjDAO); // Create an object to try to find. TestObj testObj = new TestObj.Builder(x).setId("123").build(); testObjDAO.put(testObj); try { TestObj result = (TestObj) dao.find_(x, testObj); test(result.equals(testObj), "User with 'testObjDAO.read.*' permission can use 'find_' method."); } catch (Throwable t) { test(false, "User with 'testObj.read.*' permission using 'find_' method should not throw an exception."); t.printStackTrace(); } } private void AuthenticatedDAO_ContextMethods_AuthorizedUser_put_create(X x) { // Create the decorated DAO to test. DAO testObjDAO = new MDAO(TestObj.getOwnClassInfo()); ProxyDAO dao = new AuthenticatedDAO("testObj", testObjDAO); try { TestObj testObj = new TestObj.Builder(x).setId("123").build(); TestObj result = (TestObj) dao.put_(x, testObj); test(result.equals(testObj), "User with 'testObjDAO.create' permission can use 'put_' method to create a new object."); } catch (Throwable t) { test(false, "User with 'testObj.create' permission using 'put_' method to create a new object should not throw an exception."); t.printStackTrace(); } } private void AuthenticatedDAO_ContextMethods_AuthorizedUser_put_update(X x) { // Create the decorated DAO to test. DAO testObjDAO = new MDAO(TestObj.getOwnClassInfo()); ProxyDAO dao = new AuthenticatedDAO("testObj", testObjDAO); // Create an object to try to update. TestObj testObj = new TestObj.Builder(x).setId("123").setDescription("Initial").build(); testObjDAO.put(testObj); try { testObj.setDescription("Updated value"); TestObj result = (TestObj) dao.put_(x, testObj); test(result.equals(testObj), "User with 'testObjDAO.update.*' permission can use 'put_' method to update an existing object."); } catch (Throwable t) { test(false, "User with 'testObj.update.*' permission using 'put_' method to update an existing object should not throw an exception."); t.printStackTrace(); } } private void AuthenticatedDAO_ContextMethods_AuthorizedUser_remove(X x) { // Create the decorated DAO to test. DAO testObjDAO = new MDAO(TestObj.getOwnClassInfo()); ProxyDAO dao = new AuthenticatedDAO("testObj", testObjDAO); // Create an object to try to remove. TestObj testObj = new TestObj.Builder(x).setId("123").build(); testObjDAO.put(testObj); try { TestObj result = (TestObj) dao.remove_(x, testObj); test(result.equals(testObj), "User with 'testObj.remove.*' permission can use 'remove_' method to remove an existing object."); TestObj findResult = (TestObj) testObjDAO.find(testObj.getId()); assert findResult == null; } catch (Throwable t) { test(false, "User with 'testObj.remove.*' permission using 'remove_' method to remove an existing object should not throw an exception."); t.printStackTrace(); } } private void AuthenticatedDAO_ContextMethods_AuthorizedUser_removeAll(X x) { // Create the decorated DAO to test. DAO testObjDAO = new MDAO(TestObj.getOwnClassInfo()); ProxyDAO dao = new AuthenticatedDAO("testObj", testObjDAO); // Create an object to try to remove. TestObj testObj = new TestObj.Builder(x).setId("123").build(); testObjDAO.put(testObj); try { dao.removeAll_(x, 0, 1000, null, null); ArraySink sink = new ArraySink(); testObjDAO.select(sink); List arr = sink.getArray(); test(arr.size() == 0, "User with 'testObj.delete.* permission should be able to use 'removeAll_' method to remove all existing objects."); } catch (Throwable t) { test(false, "User with 'testObj.delete' permission using 'removeAll_' method to remove all existing objects should not throw an exception."); t.printStackTrace(); } } private void AuthenticatedDAO_ContextMethods_AuthorizedUser_select(X x) { // Create the decorated DAO to test. DAO testObjDAO = new MDAO(TestObj.getOwnClassInfo()); ProxyDAO dao = new AuthenticatedDAO("testObj", testObjDAO); // Create an object to try to select. TestObj testObj = new TestObj.Builder(x).setId("123").build(); testObjDAO.put(testObj); try { ArraySink sink = new ArraySink(); ArraySink result = (ArraySink) dao.select_(x, sink, 0, 1000, null, null); List arr = result.getArray(); test(arr.size() == 1 && arr.get(0).equals(testObj), "User with 'testObjDAO.read.*' permission can use 'select_' method."); } catch (Throwable t) { test(false, "User with 'testObj.read.*' permission using 'select_' method should not throw an exception."); t.printStackTrace(); } } }
Fixing mocking test
src/foam/dao/AuthenticatedDAOTest.java
Fixing mocking test
<ide><path>rc/foam/dao/AuthenticatedDAOTest.java <ide> userDAO_.put(testUser_); <ide> <ide> // Mock the groupDAO. <del> x = TestUtils.mockDAO(x, "groupDAO"); <del> DAO groupDAO = (DAO) x.get("groupDAO"); <add> x = TestUtils.mockDAO(x, "localGroupDAO"); <add> DAO groupDAO = (DAO) x.get("localGroupDAO"); <ide> <ide> // Put a group in the groupDAO with permission to read, update, and delete the testObjDAO. <ide> Permission adminPermissions[] = new Permission[5];
JavaScript
mit
777d50d313ae55587cf0c51d8a06bd45b480b71c
0
viatsyshyn/grunt-jsbuild3
/* * emp.ria-grunt-jsbuild3 * https://code.google.com/p/emp-ria/ * * Copyright (c) 2013 Volodymyt Iatsyshyn * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { var build_number = grunt.option("build") || '0'; var build_tag = grunt.option("tag") || '0.0'; var pkg = grunt.file.readJSON('package.json'); pkg.version = [build_tag, build_number].join('.') || pkg.version; // Project configuration. grunt.initConfig({ pkg: pkg, jshint: { all: [ 'Gruntfile.js', 'tasks/*.js', '<%= nodeunit.tests %>', ], options: { jshintrc: '.jshintrc', }, }, jsbuild3: { options: { config: 'test/jsbuild.json' }, all: {} }, // Before generating any new files, remove any previously-created files. clean: { tests: ['tmp'], }, // Unit tests. nodeunit: { tests: ['test/*_test.js'], }, replace: { version: { src: 'package.json', // source files array (supports minimatch) dest: 'package.json', // destination directory or file replacements: [{ from: '0.0.0', // string replacement to: pkg.version }] } } }); // Actually load this plugin's task(s). grunt.loadTasks('tasks'); // These plugins provide necessary tasks. grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); grunt.loadNpmTasks('grunt-text-replace'); // Whenever the "test" task is run, first clean the "tmp" dir, then run this // plugin's task(s), then test the result. grunt.registerTask('test', ['clean', 'nodeunit']); // By default, lint and run all tests. grunt.registerTask('default', ['jshint', 'test']); };
Gruntfile.js
/* * emp.ria-grunt-jsbuild3 * https://code.google.com/p/emp-ria/ * * Copyright (c) 2013 Volodymyt Iatsyshyn * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { var build_number = grunt.option("build") || '0'; var build_tag = grunt.option("tag") || '0.0'; var pkg = grunt.file.readJSON('package.json'); pkg.version = [build_tag, build_number].join('.') || pkg.version; // Project configuration. grunt.initConfig({ pkg: pkg, jshint: { all: [ 'Gruntfile.js', 'tasks/*.js', '<%= nodeunit.tests %>', ], options: { jshintrc: '.jshintrc', }, }, jsbuild3: { options: { config: 'test/jsbuild.json' }, all: {} }, // Before generating any new files, remove any previously-created files. clean: { tests: ['tmp'], }, // Unit tests. nodeunit: { tests: ['test/*_test.js'], }, replace: { version: { src: 'package.json', // source files array (supports minimatch) dest: 'package.json', // destination directory or file replacements: [{ from: '0.0.0', // string replacement to: pkg.version }] } } }); // Actually load this plugin's task(s). grunt.loadTasks('tasks'); // These plugins provide necessary tasks. grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); grunt.loadNpmTasks('grunt-text-replace'); // Whenever the "test" task is run, first clean the "tmp" dir, then run this // plugin's task(s), then test the result. grunt.registerTask('test', ['clean', 'jsbuild3', 'nodeunit']); // By default, lint and run all tests. grunt.registerTask('default', ['jshint', 'test']); };
fixed tests
Gruntfile.js
fixed tests
<ide><path>runtfile.js <ide> <ide> // Whenever the "test" task is run, first clean the "tmp" dir, then run this <ide> // plugin's task(s), then test the result. <del> grunt.registerTask('test', ['clean', 'jsbuild3', 'nodeunit']); <add> grunt.registerTask('test', ['clean', 'nodeunit']); <ide> <ide> // By default, lint and run all tests. <ide> grunt.registerTask('default', ['jshint', 'test']);
Java
mit
4245655a8d9e4c6f946c11f95c58c9c113cb0291
0
ybrs/Rhombus,ybrs/Rhombus,Pardot/Rhombus,Pardot/Rhombus
package com.pardot.analyticsservice; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.pardot.analyticsservice.cassandra.cobject.*; import com.pardot.analyticsservice.helpers.TestHelpers; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import javax.annotation.Nullable; import java.io.IOException; import java.util.*; /** * Pardot, An ExactTarget Company * User: robrighter * Date: 4/9/13 */ public class CObjectCQLGeneratorTest extends TestCase { public class ShardListMock implements CObjectShardList { List<Long> result; public ShardListMock(List<Long> result){ this.result = result; } @Override public List<Long> getShardIdList(CDefinition def, SortedMap<String, String> indexValues, CObjectOrdering ordering, @Nullable UUID start, @Nullable UUID end) { return result; } } public class Subject extends CObjectCQLGenerator { public void testMakeStaticTableCreate() throws CObjectParseException, IOException { String json = TestHelpers.readFileToString(this.getClass(), "CObjectCQLGeneratorTestData.js"); CDefinition def = CDefinition.fromJsonString(json); String cql = Subject.makeStaticTableCreate(def); String expected = "CREATE TABLE \"testtype\" (id timeuuid PRIMARY KEY, filtered int,data1 varchar,data2 varchar,data3 varchar,instance bigint,type int,foreignid bigint);"; assertEquals(expected, cql); } public void testMakeWideTableCreate() throws CObjectParseException, IOException { String json = TestHelpers.readFileToString(this.getClass(), "CObjectCQLGeneratorTestData.js"); CDefinition def = CDefinition.fromJsonString(json); String cql1 = Subject.makeWideTableCreate(def, def.getIndexes().get("foreignid")); String expected1 = "CREATE TABLE \"testtype__foreignid\" (id timeuuid, shardid bigint, filtered int,data1 varchar,data2 varchar,data3 varchar,instance bigint,type int,foreignid bigint, PRIMARY KEY ((shardid, foreignid),id) );"; assertEquals(expected1, cql1); String cql2 = Subject.makeWideTableCreate(def, def.getIndexes().get("instance:type")); String expected2 = "CREATE TABLE \"testtype__instance_type\" (id timeuuid, shardid bigint, filtered int,data1 varchar,data2 varchar,data3 varchar,instance bigint,type int,foreignid bigint, PRIMARY KEY ((shardid, instance, type),id) );"; assertEquals(expected2, cql2); String cql3 = Subject.makeWideTableCreate(def, def.getIndexes().get("foreignid:instance:type")); String expected3 = "CREATE TABLE \"testtype__foreignid_instance_type\" (id timeuuid, shardid bigint, filtered int,data1 varchar,data2 varchar,data3 varchar,instance bigint,type int,foreignid bigint, PRIMARY KEY ((shardid, foreignid, instance, type),id) );"; assertEquals(expected3, cql3); } public void testMakeCQLforInsert() throws CQLGenerationException, CObjectParseException, IOException { String json = TestHelpers.readFileToString(this.getClass(), "CObjectCQLGeneratorTestData.js"); CDefinition def = CDefinition.fromJsonString(json); Map<String, String> data = TestHelpers.getTestObject(0); UUID uuid = UUID.fromString("ada375b0-a2d9-11e2-99a3-3f36d3955e43"); CQLStatementIterator result = Subject.makeCQLforInsert(def,data,uuid,1,0); List<String> actual = toList(result); assertEquals("Should generate CQL statements for the static table plus all indexes including the filtered index", 6, actual.size()); //static table assertEquals("INSERT INTO \"testtype\" (id, filtered, data1, data2, data3, instance, type, foreignid) VALUES (ada375b0-a2d9-11e2-99a3-3f36d3955e43, 1, 'This is data one', 'This is data two', 'This is data three', 222222, 5, 777) USING TIMESTAMP 1;", actual.get(0)); assertEquals("INSERT INTO \"testtype__instance_type\" (id, shardid, filtered, data1, data2, data3, instance, type, foreignid) VALUES (ada375b0-a2d9-11e2-99a3-3f36d3955e43, 160, 1, 'This is data one', 'This is data two', 'This is data three', 222222, 5, 777) USING TIMESTAMP 1;", actual.get(1)); assertEquals("INSERT INTO \"__shardindex\" (tablename, indexvalues, shardid, targetrowkey) VALUES ('testtype__instance_type', '222222:5', 160, '160:222222:5') USING TIMESTAMP 1;", actual.get(2)); assertEquals("INSERT INTO \"testtype__foreignid_instance_type\" (id, shardid, filtered, data1, data2, data3, instance, type, foreignid) VALUES (ada375b0-a2d9-11e2-99a3-3f36d3955e43, 160, 1, 'This is data one', 'This is data two', 'This is data three', 222222, 5, 777) USING TIMESTAMP 1;",actual.get(3)); assertEquals("INSERT INTO \"__shardindex\" (tablename, indexvalues, shardid, targetrowkey) VALUES ('testtype__foreignid_instance_type', '777:222222:5', 160, '160:777:222222:5') USING TIMESTAMP 1;", actual.get(4)); assertEquals("INSERT INTO \"testtype__foreignid\" (id, shardid, filtered, data1, data2, data3, instance, type, foreignid) VALUES (ada375b0-a2d9-11e2-99a3-3f36d3955e43, 1, 1, 'This is data one', 'This is data two', 'This is data three', 222222, 5, 777) USING TIMESTAMP 1;",actual.get(5)); //foreign has shard strategy None so we dont expect an insert into the shard index table //test with ttl result = Subject.makeCQLforInsert(def,data,uuid,1,20); actual = toList(result); assertEquals("INSERT INTO \"testtype\" (id, filtered, data1, data2, data3, instance, type, foreignid) VALUES (ada375b0-a2d9-11e2-99a3-3f36d3955e43, 1, 'This is data one', 'This is data two', 'This is data three', 222222, 5, 777) USING TIMESTAMP 1 AND TTL 20;", actual.get(0)); } public void testMakeCQLforCreate() throws CObjectParseException, IOException { String json = TestHelpers.readFileToString(this.getClass(), "CObjectCQLGeneratorTestData.js"); CDefinition def = CDefinition.fromJsonString(json); CQLStatementIterator actual = Subject.makeCQLforCreate(def); assertEquals("Should generate CQL statements for the static table plus all indexes", 4, actual.size()); } public void testMakeCQLforGet() throws CObjectParseException,CObjectParseException, CQLGenerationException, IOException { String json = TestHelpers.readFileToString(this.getClass(), "CObjectCQLGeneratorTestData.js"); CDefinition def = CDefinition.fromJsonString(json); //Static Table Get CQLStatementIterator actual = Subject.makeCQLforGet(def,UUID.fromString("ada375b0-a2d9-11e2-99a3-3f36d3955e43")); assertEquals("Static gets should return bounded query iterator", true,actual.isBounded()); assertEquals("Static gets should return an iterator with 1 statement", 1,actual.size()); String expected = "SELECT * FROM \"testtype\" WHERE id = ada375b0-a2d9-11e2-99a3-3f36d3955e43;"; assertEquals("Should generate proper CQL for static table get by ID",expected,toList(actual).get(0)); CObjectShardList shardIdLists = new ShardListMock(Arrays.asList(1L,2L,3L,4L,5L)); //Wide table using shardIdList and therefore bounded TreeMap<String,String> indexkeys = Maps.newTreeMap(); indexkeys.put("foreignid","777"); indexkeys.put("type", "5"); indexkeys.put("instance", "222222"); actual = Subject.makeCQLforGet(shardIdLists, def, indexkeys, 10); expected = "SELECT * FROM \"testtype__foreignid_instance_type\" WHERE shardid = 1 AND foreignid = 777 AND instance = 222222 AND type = 5 AND id <"; assertEquals(expected, actual.next().substring(0,131)); expected = "SELECT * FROM \"testtype__foreignid_instance_type\" WHERE shardid = 2 AND foreignid = 777 AND instance = 222222 AND type = 5 AND id <"; assertEquals(expected, actual.next().substring(0,131)); assertEquals("Should be bounded query list", true, actual.isBounded()); //Wide table exclusive slice bounded query should not use shard list indexkeys = Maps.newTreeMap(); indexkeys.put("foreignid","777"); indexkeys.put("type", "5"); indexkeys.put("instance", "222222"); UUID start = UUID.fromString("a8a2abe0-a251-11e2-bcbb-adf1a79a327f"); UUID stop = UUID.fromString("ada375b0-a2d9-11e2-99a3-3f36d3955e43"); actual = Subject.makeCQLforGet(shardIdLists, def, indexkeys, CObjectOrdering.DESCENDING, start, stop,10, false); expected = "SELECT * FROM \"testtype__foreignid_instance_type\" WHERE shardid = 160 AND foreignid = 777 AND instance = 222222 AND type = 5 AND id > a8a2abe0-a251-11e2-bcbb-adf1a79a327f AND id < ada375b0-a2d9-11e2-99a3-3f36d3955e43 ORDER BY id DESC LIMIT 10 ALLOW FILTERING;"; assertEquals("Should generate proper CQL for wide table get by index values",expected,actual.next()); assertTrue("Should be bounded query iterator", actual.isBounded()); assertTrue("Should be none remaining in the iterator", !actual.hasNext()); //wide table inclusive slice ascending bounded start = UUID.fromString("b4c10d80-15f0-11e0-8080-808080808080"); // 1/1/2011 long startd = 1293918439000L; stop = UUID.fromString("2d87f48f-34c2-11e1-7f7f-7f7f7f7f7f7f"); //1/1/2012 long endd = 1325454439000L; actual = Subject.makeCQLforGet(shardIdLists, def, indexkeys,CObjectOrdering.ASCENDING, start, stop,10, true); assertEquals("Should be proper size for range", 13, actual.size()); //All of 2011 plus the first month of 2012 expected = "SELECT * FROM \"testtype__foreignid_instance_type\" WHERE shardid = 133 AND foreignid = 777 AND instance = 222222 AND type = 5 AND id >= b4c10d80-15f0-11e0-8080-808080808080 AND id <= 2d87f48f-34c2-11e1-7f7f-7f7f7f7f7f7f ORDER BY id ASC LIMIT 10 ALLOW FILTERING;"; assertEquals("Should generate proper CQL for wide table get by index values",expected,actual.next()); expected = "SELECT * FROM \"testtype__foreignid_instance_type\" WHERE shardid = 134 AND foreignid = 777 AND instance = 222222 AND type = 5 AND id >= b4c10d80-15f0-11e0-8080-808080808080 AND id <= 2d87f48f-34c2-11e1-7f7f-7f7f7f7f7f7f ORDER BY id ASC LIMIT 10 ALLOW FILTERING;"; assertEquals("Should generate proper CQL for wide table get by index values",expected,actual.next()); expected = "SELECT * FROM \"testtype__foreignid_instance_type\" WHERE shardid = 135 AND foreignid = 777 AND instance = 222222 AND type = 5 AND id >= b4c10d80-15f0-11e0-8080-808080808080 AND id <= 2d87f48f-34c2-11e1-7f7f-7f7f7f7f7f7f ORDER BY id ASC LIMIT 5 ALLOW FILTERING;"; assertTrue("Should have next when hinted less than the limit",actual.hasNext(5)); assertEquals("Should generate proper Limit adjustment when given the amount hint",expected,actual.next()); assertTrue("Should have no next when hinted more than or equal to the limit",!actual.hasNext(10)); //wide table inclusive slice descending bounded start = UUID.fromString("b4c10d80-15f0-11e0-8080-808080808080"); // 1/1/2011 long startd = 1293918439000L; stop = UUID.fromString("2d87f48f-34c2-11e1-7f7f-7f7f7f7f7f7f"); //1/1/2012 long endd = 1325454439000L; actual = Subject.makeCQLforGet(shardIdLists, def, indexkeys,CObjectOrdering.DESCENDING, start, stop,10, true); assertEquals("Descending: Should be proper size for range", 13, actual.size()); //All of 2011 plus the first month of 2012 expected = "SELECT * FROM \"testtype__foreignid_instance_type\" WHERE shardid = 145 AND foreignid = 777 AND instance = 222222 AND type = 5 AND id >= b4c10d80-15f0-11e0-8080-808080808080 AND id <= 2d87f48f-34c2-11e1-7f7f-7f7f7f7f7f7f ORDER BY id DESC LIMIT 10 ALLOW FILTERING;"; assertEquals("Descending: Should generate proper CQL for wide table get by index values",expected,actual.next()); expected = "SELECT * FROM \"testtype__foreignid_instance_type\" WHERE shardid = 144 AND foreignid = 777 AND instance = 222222 AND type = 5 AND id >= b4c10d80-15f0-11e0-8080-808080808080 AND id <= 2d87f48f-34c2-11e1-7f7f-7f7f7f7f7f7f ORDER BY id DESC LIMIT 10 ALLOW FILTERING;"; assertEquals("Descending: Should generate proper CQL for wide table get by index values",expected,actual.next()); expected = "SELECT * FROM \"testtype__foreignid_instance_type\" WHERE shardid = 143 AND foreignid = 777 AND instance = 222222 AND type = 5 AND id >= b4c10d80-15f0-11e0-8080-808080808080 AND id <= 2d87f48f-34c2-11e1-7f7f-7f7f7f7f7f7f ORDER BY id DESC LIMIT 5 ALLOW FILTERING;"; assertTrue("Descending: Should have next when hinted less than the limit",actual.hasNext(5)); assertEquals("Descending: Should generate proper Limit adjustment when given the amount hint",expected,actual.next()); assertTrue("Should have no next when hinted more than or equal to the limit",!actual.hasNext(10)); } public void testMakeCQLforDelete() throws CObjectParseException,CObjectParseException, CQLGenerationException, IOException { String json = TestHelpers.readFileToString(this.getClass(), "CObjectCQLGeneratorTestData.js"); CDefinition def = CDefinition.fromJsonString(json); Map<String, String> data = TestHelpers.getTestObject(0); UUID uuid = UUID.fromString("ada375b0-a2d9-11e2-99a3-3f36d3955e43"); CQLStatementIterator result = Subject.makeCQLforDelete(def,uuid,data,111); String expected; expected = "DELETE FROM testtype USING TIMESTAMP 111 WHERE id = ada375b0-a2d9-11e2-99a3-3f36d3955e43;"; assertEquals(expected,result.next()); expected = "DELETE FROM testtype__instance_type USING TIMESTAMP 111 WHERE id = ada375b0-a2d9-11e2-99a3-3f36d3955e43 AND shardid = 160 AND instance = 222222 AND type = 5;"; assertEquals(expected,result.next()); expected = "DELETE FROM testtype__foreignid_instance_type USING TIMESTAMP 111 WHERE id = ada375b0-a2d9-11e2-99a3-3f36d3955e43 AND shardid = 160 AND foreignid = 777 AND instance = 222222 AND type = 5;"; assertEquals(expected,result.next()); expected = "DELETE FROM testtype__foreignid USING TIMESTAMP 111 WHERE id = ada375b0-a2d9-11e2-99a3-3f36d3955e43 AND shardid = 1 AND foreignid = 777;"; assertEquals(expected,result.next()); assertTrue(!result.hasNext()); } } public static List<String> toList(CQLStatementIterator i){ List<String> ret = Lists.newArrayList(); if(!i.isBounded()){ return ret; } while(i.hasNext()){ ret.add(i.next()); } return ret; } /** * Create the test case * * @param testName name of the test case */ public CObjectCQLGeneratorTest( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( CObjectCQLGeneratorTest.class ); } public void testMakeStaticTableCreate() throws CObjectParseException, IOException { Subject s = new Subject(); s.testMakeStaticTableCreate(); } public void testMakeWideTableCreate() throws CObjectParseException, IOException { Subject s = new Subject(); s.testMakeWideTableCreate(); } public void testMakeCQLforCreate() throws CObjectParseException, IOException { Subject s = new Subject(); s.testMakeCQLforCreate(); } public void testMakeCQLforInsert() throws CQLGenerationException, CObjectParseException, IOException { Subject s = new Subject(); s.testMakeCQLforInsert(); } public void testMakeCQLforGet() throws CQLGenerationException, CObjectParseException, IOException { Subject s = new Subject(); s.testMakeCQLforGet(); } public void testMakeCQLforDelete() throws CQLGenerationException, CObjectParseException, IOException { Subject s = new Subject(); s.testMakeCQLforDelete(); } }
src/test/java/com/pardot/analyticsservice/CObjectCQLGeneratorTest.java
package com.pardot.analyticsservice; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.pardot.analyticsservice.cassandra.cobject.*; import com.pardot.analyticsservice.helpers.TestHelpers; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import javax.annotation.Nullable; import java.io.IOException; import java.util.*; /** * Pardot, An ExactTarget Company * User: robrighter * Date: 4/9/13 */ public class CObjectCQLGeneratorTest extends TestCase { public class ShardListMock implements CObjectShardList { List<Long> result; public ShardListMock(List<Long> result){ this.result = result; } @Override public List<Long> getShardIdList(CDefinition def, SortedMap<String, String> indexValues, CObjectOrdering ordering, @Nullable UUID start, @Nullable UUID end) { return result; } } public class Subject extends CObjectCQLGenerator { public void testMakeStaticTableCreate() throws CObjectParseException, IOException { String json = TestHelpers.readFileToString(this.getClass(), "CObjectCQLGeneratorTestData.js"); CDefinition def = CDefinition.fromJsonString(json); String cql = Subject.makeStaticTableCreate(def); String expected = "CREATE TABLE \"testtype\" (id timeuuid PRIMARY KEY, filtered int,data1 varchar,data2 varchar,data3 varchar,instance bigint,type int,foreignid bigint);"; assertEquals(expected, cql); } public void testMakeWideTableCreate() throws CObjectParseException, IOException { String json = TestHelpers.readFileToString(this.getClass(), "CObjectCQLGeneratorTestData.js"); CDefinition def = CDefinition.fromJsonString(json); String cql1 = Subject.makeWideTableCreate(def, def.getIndexes().get("foreignid")); String expected1 = "CREATE TABLE \"testtype__foreignid\" (id timeuuid, shardid bigint, filtered int,data1 varchar,data2 varchar,data3 varchar,instance bigint,type int,foreignid bigint, PRIMARY KEY ((shardid, foreignid),id) );"; assertEquals(expected1, cql1); String cql2 = Subject.makeWideTableCreate(def, def.getIndexes().get("instance:type")); String expected2 = "CREATE TABLE \"testtype__instance_type\" (id timeuuid, shardid bigint, filtered int,data1 varchar,data2 varchar,data3 varchar,instance bigint,type int,foreignid bigint, PRIMARY KEY ((shardid, instance, type),id) );"; assertEquals(expected2, cql2); String cql3 = Subject.makeWideTableCreate(def, def.getIndexes().get("foreignid:instance:type")); String expected3 = "CREATE TABLE \"testtype__foreignid_instance_type\" (id timeuuid, shardid bigint, filtered int,data1 varchar,data2 varchar,data3 varchar,instance bigint,type int,foreignid bigint, PRIMARY KEY ((shardid, foreignid, instance, type),id) );"; assertEquals(expected3, cql3); } public void testMakeCQLforInsert() throws CQLGenerationException, CObjectParseException, IOException { String json = TestHelpers.readFileToString(this.getClass(), "CObjectCQLGeneratorTestData.js"); CDefinition def = CDefinition.fromJsonString(json); Map<String, String> data = TestHelpers.getTestObject(0); UUID uuid = UUID.fromString("ada375b0-a2d9-11e2-99a3-3f36d3955e43"); CQLStatementIterator result = Subject.makeCQLforInsert(def,data,uuid,1,0); List<String> actual = toList(result); assertEquals("Should generate CQL statements for the static table plus all indexes including the filtered index", 6, actual.size()); //static table assertEquals("INSERT INTO \"testtype\" (id, filtered, data1, data2, data3, instance, type, foreignid) VALUES (ada375b0-a2d9-11e2-99a3-3f36d3955e43, 1, 'This is data one', 'This is data two', 'This is data three', 222222, 5, 777) USING TIMESTAMP 1;", actual.get(0)); assertEquals("INSERT INTO \"testtype__instance_type\" (id, shardid, filtered, data1, data2, data3, instance, type, foreignid) VALUES (ada375b0-a2d9-11e2-99a3-3f36d3955e43, 160, 1, 'This is data one', 'This is data two', 'This is data three', 222222, 5, 777) USING TIMESTAMP 1;", actual.get(1)); assertEquals("INSERT INTO \"__shardindex\" (tablename, indexvalues, shardid, targetrowkey) VALUES ('testtype__instance_type', '222222:5', 160, '160:222222:5') USING TIMESTAMP 1;", actual.get(2)); assertEquals("INSERT INTO \"testtype__foreignid_instance_type\" (id, shardid, filtered, data1, data2, data3, instance, type, foreignid) VALUES (ada375b0-a2d9-11e2-99a3-3f36d3955e43, 160, 1, 'This is data one', 'This is data two', 'This is data three', 222222, 5, 777) USING TIMESTAMP 1;",actual.get(3)); assertEquals("INSERT INTO \"__shardindex\" (tablename, indexvalues, shardid, targetrowkey) VALUES ('testtype__foreignid_instance_type', '777:222222:5', 160, '160:777:222222:5') USING TIMESTAMP 1;", actual.get(4)); assertEquals("INSERT INTO \"testtype__foreignid\" (id, shardid, filtered, data1, data2, data3, instance, type, foreignid) VALUES (ada375b0-a2d9-11e2-99a3-3f36d3955e43, 1, 1, 'This is data one', 'This is data two', 'This is data three', 222222, 5, 777) USING TIMESTAMP 1;",actual.get(5)); //foreign has shard strategy None so we dont expect an insert into the shard index table //test with ttl result = Subject.makeCQLforInsert(def,data,uuid,1,20); actual = toList(result); assertEquals("INSERT INTO \"testtype\" (id, filtered, data1, data2, data3, instance, type, foreignid) VALUES (ada375b0-a2d9-11e2-99a3-3f36d3955e43, 1, 'This is data one', 'This is data two', 'This is data three', 222222, 5, 777) USING TIMESTAMP 1 AND TTL 20;", actual.get(0)); } public void testMakeCQLforCreate() throws CObjectParseException, IOException { String json = TestHelpers.readFileToString(this.getClass(), "CObjectCQLGeneratorTestData.js"); CDefinition def = CDefinition.fromJsonString(json); CQLStatementIterator actual = Subject.makeCQLforCreate(def); assertEquals("Should generate CQL statements for the static table plus all indexes", 4, actual.size()); } public void testMakeCQLforGet() throws CObjectParseException,CObjectParseException, CQLGenerationException, IOException { String json = TestHelpers.readFileToString(this.getClass(), "CObjectCQLGeneratorTestData.js"); CDefinition def = CDefinition.fromJsonString(json); //Static Table Get CQLStatementIterator actual = Subject.makeCQLforGet(def,UUID.fromString("ada375b0-a2d9-11e2-99a3-3f36d3955e43")); assertEquals("Static gets should return bounded query iterator", true,actual.isBounded()); assertEquals("Static gets should return an iterator with 1 statement", 1,actual.size()); String expected = "SELECT * FROM \"testtype\" WHERE id = ada375b0-a2d9-11e2-99a3-3f36d3955e43;"; assertEquals("Should generate proper CQL for static table get by ID",expected,toList(actual).get(0)); CObjectShardList shardIdLists = new ShardListMock(Arrays.asList(1L,2L,3L,4L,5L)); //Wide table using shardIdList and therefore bounded TreeMap<String,String> indexkeys = Maps.newTreeMap(); indexkeys.put("foreignid","777"); indexkeys.put("type", "5"); indexkeys.put("instance", "222222"); actual = Subject.makeCQLforGet(shardIdLists, def, indexkeys, 10); expected = "SELECT * FROM \"testtype__foreignid_instance_type\" WHERE shardid = 1 AND foreignid = 777 AND instance = 222222 AND type = 5 AND id <"; assertEquals(expected, actual.next().substring(0,131)); expected = "SELECT * FROM \"testtype__foreignid_instance_type\" WHERE shardid = 2 AND foreignid = 777 AND instance = 222222 AND type = 5 AND id <"; assertEquals(expected, actual.next().substring(0,131)); assertEquals("Should be bounded query list", true, actual.isBounded()); //Wide table exclusive slice bounded query should not use shard list indexkeys = Maps.newTreeMap(); indexkeys.put("foreignid","777"); indexkeys.put("type", "5"); indexkeys.put("instance", "222222"); UUID start = UUID.fromString("a8a2abe0-a251-11e2-bcbb-adf1a79a327f"); UUID stop = UUID.fromString("ada375b0-a2d9-11e2-99a3-3f36d3955e43"); actual = Subject.makeCQLforGet(shardIdLists, def, indexkeys, CObjectOrdering.DESCENDING, start, stop,10, false); expected = "SELECT * FROM \"testtype__foreignid_instance_type\" WHERE shardid = 160 AND foreignid = 777 AND instance = 222222 AND type = 5 AND id > a8a2abe0-a251-11e2-bcbb-adf1a79a327f AND id < ada375b0-a2d9-11e2-99a3-3f36d3955e43 ORDER BY id DESC LIMIT 10 ALLOW FILTERING;"; assertEquals("Should generate proper CQL for wide table get by index values",expected,actual.next()); assertTrue("Should be bounded query iterator", actual.isBounded()); assertTrue("Should be none remaining in the iterator", !actual.hasNext()); //wide table inclusive slice ascending bounded start = UUID.fromString("b4c10d80-15f0-11e0-8080-808080808080"); // 1/1/2011 long startd = 1293918439000L; stop = UUID.fromString("2d87f48f-34c2-11e1-7f7f-7f7f7f7f7f7f"); //1/1/2012 long endd = 1325454439000L; actual = Subject.makeCQLforGet(shardIdLists, def, indexkeys,CObjectOrdering.ASCENDING, start, stop,10, true); assertEquals("Should be proper size for range", 13, actual.size()); //All of 2011 plus the first month of 2012 expected = "SELECT * FROM \"testtype__foreignid_instance_type\" WHERE shardid = 133 AND foreignid = 777 AND instance = 222222 AND type = 5 AND id >= b4c10d80-15f0-11e0-8080-808080808080 AND id <= 2d87f48f-34c2-11e1-7f7f-7f7f7f7f7f7f ORDER BY id ASC LIMIT 10 ALLOW FILTERING;"; assertEquals("Should generate proper CQL for wide table get by index values",expected,actual.next()); expected = "SELECT * FROM \"testtype__foreignid_instance_type\" WHERE shardid = 134 AND foreignid = 777 AND instance = 222222 AND type = 5 AND id >= b4c10d80-15f0-11e0-8080-808080808080 AND id <= 2d87f48f-34c2-11e1-7f7f-7f7f7f7f7f7f ORDER BY id ASC LIMIT 10 ALLOW FILTERING;"; assertEquals("Should generate proper CQL for wide table get by index values",expected,actual.next()); expected = "SELECT * FROM \"testtype__foreignid_instance_type\" WHERE shardid = 135 AND foreignid = 777 AND instance = 222222 AND type = 5 AND id >= b4c10d80-15f0-11e0-8080-808080808080 AND id <= 2d87f48f-34c2-11e1-7f7f-7f7f7f7f7f7f ORDER BY id ASC LIMIT 5 ALLOW FILTERING;"; assertTrue("Should have next when hinted less than the limit",actual.hasNext(5)); assertEquals("Should generate proper Limit adjustment when given the amount hint",expected,actual.next()); assertTrue("Should have no next when hinted more than or equal to the limit",!actual.hasNext(10)); //wide table inclusive slice descending bounded start = UUID.fromString("b4c10d80-15f0-11e0-8080-808080808080"); // 1/1/2011 long startd = 1293918439000L; stop = UUID.fromString("2d87f48f-34c2-11e1-7f7f-7f7f7f7f7f7f"); //1/1/2012 long endd = 1325454439000L; actual = Subject.makeCQLforGet(shardIdLists, def, indexkeys,CObjectOrdering.DESCENDING, start, stop,10, true); assertEquals("Descending: Should be proper size for range", 13, actual.size()); //All of 2011 plus the first month of 2012 expected = "SELECT * FROM \"testtype__foreignid_instance_type\" WHERE shardid = 145 AND foreignid = 777 AND instance = 222222 AND type = 5 AND id >= b4c10d80-15f0-11e0-8080-808080808080 AND id <= 2d87f48f-34c2-11e1-7f7f-7f7f7f7f7f7f ORDER BY id DESC LIMIT 10 ALLOW FILTERING;"; assertEquals("Descending: Should generate proper CQL for wide table get by index values",expected,actual.next()); expected = "SELECT * FROM \"testtype__foreignid_instance_type\" WHERE shardid = 144 AND foreignid = 777 AND instance = 222222 AND type = 5 AND id >= b4c10d80-15f0-11e0-8080-808080808080 AND id <= 2d87f48f-34c2-11e1-7f7f-7f7f7f7f7f7f ORDER BY id DESC LIMIT 10 ALLOW FILTERING;"; assertEquals("Descending: Should generate proper CQL for wide table get by index values",expected,actual.next()); expected = "SELECT * FROM \"testtype__foreignid_instance_type\" WHERE shardid = 143 AND foreignid = 777 AND instance = 222222 AND type = 5 AND id >= b4c10d80-15f0-11e0-8080-808080808080 AND id <= 2d87f48f-34c2-11e1-7f7f-7f7f7f7f7f7f ORDER BY id DESC LIMIT 5 ALLOW FILTERING;"; assertTrue("Descending: Should have next when hinted less than the limit",actual.hasNext(5)); assertEquals("Descending: Should generate proper Limit adjustment when given the amount hint",expected,actual.next()); assertTrue("Should have no next when hinted more than or equal to the limit",!actual.hasNext(10)); } public void testMakeCQLforDelete() throws CObjectParseException,CObjectParseException, CQLGenerationException, IOException { String json = TestHelpers.readFileToString(this.getClass(), "CObjectCQLGeneratorTestData.js"); CDefinition def = CDefinition.fromJsonString(json); Map<String, String> data = TestHelpers.getTestObject(0); UUID uuid = UUID.fromString("ada375b0-a2d9-11e2-99a3-3f36d3955e43"); CQLStatementIterator result = Subject.makeCQLforDelete(def,uuid,data,111); String expected; expected = "DELETE FROM testtype USING TIMESTAMP 111 WHERE id = ada375b0-a2d9-11e2-99a3-3f36d3955e43;"; assertEquals(expected,result.next()); expected = "DELETE FROM testtype__instance_type USING TIMESTAMP 111 WHERE id = ada375b0-a2d9-11e2-99a3-3f36d3955e43 AND shardid = 160 instance = 222222 AND type = 5;"; assertEquals(expected,result.next()); expected = "DELETE FROM testtype__foreignid_instance_type USING TIMESTAMP 111 WHERE id = ada375b0-a2d9-11e2-99a3-3f36d3955e43 AND shardid = 160 foreignid = 777 AND instance = 222222 AND type = 5;"; assertEquals(expected,result.next()); expected = "DELETE FROM testtype__foreignid USING TIMESTAMP 111 WHERE id = ada375b0-a2d9-11e2-99a3-3f36d3955e43 AND shardid = 1 foreignid = 777;"; assertEquals(expected,result.next()); assertTrue(!result.hasNext()); } } public static List<String> toList(CQLStatementIterator i){ List<String> ret = Lists.newArrayList(); if(!i.isBounded()){ return ret; } while(i.hasNext()){ ret.add(i.next()); } return ret; } /** * Create the test case * * @param testName name of the test case */ public CObjectCQLGeneratorTest( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( CObjectCQLGeneratorTest.class ); } public void testMakeStaticTableCreate() throws CObjectParseException, IOException { Subject s = new Subject(); s.testMakeStaticTableCreate(); } public void testMakeWideTableCreate() throws CObjectParseException, IOException { Subject s = new Subject(); s.testMakeWideTableCreate(); } public void testMakeCQLforCreate() throws CObjectParseException, IOException { Subject s = new Subject(); s.testMakeCQLforCreate(); } public void testMakeCQLforInsert() throws CQLGenerationException, CObjectParseException, IOException { Subject s = new Subject(); s.testMakeCQLforInsert(); } public void testMakeCQLforGet() throws CQLGenerationException, CObjectParseException, IOException { Subject s = new Subject(); s.testMakeCQLforGet(); } public void testMakeCQLforDelete() throws CQLGenerationException, CObjectParseException, IOException { Subject s = new Subject(); s.testMakeCQLforDelete(); } }
Fix unit tests to reflect additional AND on delte that was missing
src/test/java/com/pardot/analyticsservice/CObjectCQLGeneratorTest.java
Fix unit tests to reflect additional AND on delte that was missing
<ide><path>rc/test/java/com/pardot/analyticsservice/CObjectCQLGeneratorTest.java <ide> <ide> expected = "DELETE FROM testtype USING TIMESTAMP 111 WHERE id = ada375b0-a2d9-11e2-99a3-3f36d3955e43;"; <ide> assertEquals(expected,result.next()); <del> expected = "DELETE FROM testtype__instance_type USING TIMESTAMP 111 WHERE id = ada375b0-a2d9-11e2-99a3-3f36d3955e43 AND shardid = 160 instance = 222222 AND type = 5;"; <del> assertEquals(expected,result.next()); <del> expected = "DELETE FROM testtype__foreignid_instance_type USING TIMESTAMP 111 WHERE id = ada375b0-a2d9-11e2-99a3-3f36d3955e43 AND shardid = 160 foreignid = 777 AND instance = 222222 AND type = 5;"; <del> assertEquals(expected,result.next()); <del> expected = "DELETE FROM testtype__foreignid USING TIMESTAMP 111 WHERE id = ada375b0-a2d9-11e2-99a3-3f36d3955e43 AND shardid = 1 foreignid = 777;"; <add> expected = "DELETE FROM testtype__instance_type USING TIMESTAMP 111 WHERE id = ada375b0-a2d9-11e2-99a3-3f36d3955e43 AND shardid = 160 AND instance = 222222 AND type = 5;"; <add> assertEquals(expected,result.next()); <add> expected = "DELETE FROM testtype__foreignid_instance_type USING TIMESTAMP 111 WHERE id = ada375b0-a2d9-11e2-99a3-3f36d3955e43 AND shardid = 160 AND foreignid = 777 AND instance = 222222 AND type = 5;"; <add> assertEquals(expected,result.next()); <add> expected = "DELETE FROM testtype__foreignid USING TIMESTAMP 111 WHERE id = ada375b0-a2d9-11e2-99a3-3f36d3955e43 AND shardid = 1 AND foreignid = 777;"; <ide> assertEquals(expected,result.next()); <ide> assertTrue(!result.hasNext()); <ide>
Java
apache-2.0
f923a8ee8f19e2c408f4ae4f0172c3f35844de0d
0
EmmyLua/IntelliJ-EmmyLua,EmmyLua/IntelliJ-EmmyLua,tangzx/IntelliJ-EmmyLua,tangzx/IntelliJ-EmmyLua,tangzx/IntelliJ-EmmyLua,EmmyLua/IntelliJ-EmmyLua,tangzx/IntelliJ-EmmyLua,EmmyLua/IntelliJ-EmmyLua
/* * Copyright (c) 2017. tangzx([email protected]) * * 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.tang.intellij.lua.codeInsight; import com.intellij.codeInsight.editorActions.BackspaceHandlerDelegate; import com.intellij.lang.ASTNode; import com.intellij.openapi.editor.Editor; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiTreeUtil; import com.tang.intellij.lua.comment.psi.LuaDocTypes; import com.tang.intellij.lua.comment.psi.api.LuaComment; import org.jetbrains.annotations.NotNull; /** * * Created by tangzx on 2016/12/28. */ public class LuaBackspaceHandlerDelegate extends BackspaceHandlerDelegate { @Override public void beforeCharDeleted(char c, @NotNull PsiFile psiFile, @NotNull Editor editor) { } @Override public boolean charDeleted(char c, @NotNull PsiFile psiFile, @NotNull Editor editor) { if (c == '-') { // 一口气删了 --- int offset = editor.getCaretModel().getOffset(); PsiElement element = psiFile.findElementAt(offset); if (element != null) { ASTNode node = element.getNode(); IElementType type = node.getElementType(); if (type == LuaDocTypes.DASHES) { int end = node.getStartOffset() + node.getTextLength(); int start = node.getStartOffset(); if (offset == end - 1 && node.getTextLength() == 3) { //确保是在 --- 后面删的 LuaComment comment = PsiTreeUtil.getParentOfType(element, LuaComment.class); assert comment != null; //if (comment.getNode().getStartOffset() < start) //如果有两行以上的 --- 则把换行符一起删了 // start = start - 1; editor.getDocument().deleteString(start, offset); editor.getCaretModel().moveToOffset(start); } } } } return false; } }
src/main/java/com/tang/intellij/lua/codeInsight/LuaBackspaceHandlerDelegate.java
/* * Copyright (c) 2017. tangzx([email protected]) * * 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.tang.intellij.lua.codeInsight; import com.intellij.codeInsight.editorActions.BackspaceHandlerDelegate; import com.intellij.lang.ASTNode; import com.intellij.openapi.editor.Editor; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiTreeUtil; import com.tang.intellij.lua.comment.psi.LuaDocTypes; import com.tang.intellij.lua.comment.psi.api.LuaComment; import org.jetbrains.annotations.NotNull; /** * * Created by tangzx on 2016/12/28. */ public class LuaBackspaceHandlerDelegate extends BackspaceHandlerDelegate { @Override public void beforeCharDeleted(char c, @NotNull PsiFile psiFile, @NotNull Editor editor) { } @Override public boolean charDeleted(char c, @NotNull PsiFile psiFile, @NotNull Editor editor) { if (c == '-') { // 一口气删了 --- int offset = editor.getCaretModel().getOffset(); PsiElement element = psiFile.findElementAt(offset); if (element != null) { ASTNode node = element.getNode(); IElementType type = node.getElementType(); if (type == LuaDocTypes.DASHES) { int end = node.getStartOffset() + node.getTextLength(); int start = node.getStartOffset(); if (offset == end - 1 && node.getTextLength() == 3) { //确保是在 --- 后面删的 LuaComment comment = PsiTreeUtil.getParentOfType(element, LuaComment.class); assert comment != null; if (comment.getNode().getStartOffset() < start) //如果有两行以上的 --- 则把换行符一起删了 start = start - 1; editor.getDocument().deleteString(start, offset); editor.getCaretModel().moveToOffset(start); } } } } return false; } }
LuaBackspaceHandlerDelegate
src/main/java/com/tang/intellij/lua/codeInsight/LuaBackspaceHandlerDelegate.java
LuaBackspaceHandlerDelegate
<ide><path>rc/main/java/com/tang/intellij/lua/codeInsight/LuaBackspaceHandlerDelegate.java <ide> LuaComment comment = PsiTreeUtil.getParentOfType(element, LuaComment.class); <ide> assert comment != null; <ide> <del> if (comment.getNode().getStartOffset() < start) //如果有两行以上的 --- 则把换行符一起删了 <del> start = start - 1; <add> //if (comment.getNode().getStartOffset() < start) //如果有两行以上的 --- 则把换行符一起删了 <add> // start = start - 1; <ide> <ide> editor.getDocument().deleteString(start, offset); <ide> editor.getCaretModel().moveToOffset(start);
Java
mit
80046be30b5913949133cf0a6960ff506dc82067
0
trujunzhang/IEATTA-ANDROID,trujunzhang/IEATTA-ANDROID
package org.wikipedia.analytics; import android.net.Uri; import android.util.Log; //import com.github.kevinsawicki.http.HttpRequest; import org.json.JSONException; import org.json.JSONObject; import org.ieatta.IEATTAApp; import org.wikipedia.concurrency.SaneAsyncTask; /** * Base class for all various types of events that are logged to EventLogging. * * Each Schema has its own class, and has its own constructor that makes it easy * to call from everywhere without having to duplicate param info at all places. * Updating schemas / revisions is also easier this way. */ public class EventLoggingEvent { private static final String EVENTLOG_URL_PROD = "https://meta.wikimedia.org/beacon/event"; private static final String EVENTLOG_URL_DEV = "http://deployment.wikimedia.beta.wmflabs.org/beacon/event"; private static final String EVENTLOG_URL = IEATTAApp.getInstance().isPreBetaRelease() ? EVENTLOG_URL_DEV : EVENTLOG_URL_PROD; private final JSONObject data; private final String userAgent; /** * Create an EventLoggingEvent that logs to a given revision of a given schema with * the gven data payload. * * @param schema Schema name (as specified on meta.wikimedia.org) * @param revID Revision of the schema to log to * @param wiki DBName (enwiki, dewiki, etc) of the wiki in which we are operating * @param userAgent User-Agent string to use for this request * @param eventData Data for the actual event payload. Considered to be * */ public EventLoggingEvent(String schema, int revID, String wiki, String userAgent, JSONObject eventData) { data = new JSONObject(); try { data.put("schema", schema); data.put("revision", revID); data.put("wiki", wiki); data.put("event", eventData); } catch (JSONException e) { throw new RuntimeException(e); } this.userAgent = userAgent; } /** * Log the current event. * * Returns immediately after queueing the network request in the background. */ public void log() { // new LogEventTask(data).execute(); } // private class LogEventTask extends SaneAsyncTask<Integer> { // private final JSONObject data; // LogEventTask(JSONObject data) { // this.data = data; // } // // @Override // public Integer performTask() throws Throwable { // String elUrl = EVENTLOG_URL; // String dataURL = Uri.parse(elUrl) // .buildUpon().query(data.toString()) // .build().toString(); // return HttpRequest.get(dataURL).header("User-Agent", userAgent).code(); // } // // @Override // public void onCatch(Throwable caught) { // // Do nothing bad. EL data is ok to lose. // Log.d(Funnel.ANALYTICS_TAG, "Lost EL data: " + data.toString()); // } // } }
app/src/main/java/org/wikipedia/analytics/EventLoggingEvent.java
package org.wikipedia.analytics; import android.net.Uri; import android.util.Log; import com.github.kevinsawicki.http.HttpRequest; import org.json.JSONException; import org.json.JSONObject; import org.ieatta.IEATTAApp; import org.wikipedia.concurrency.SaneAsyncTask; /** * Base class for all various types of events that are logged to EventLogging. * * Each Schema has its own class, and has its own constructor that makes it easy * to call from everywhere without having to duplicate param info at all places. * Updating schemas / revisions is also easier this way. */ public class EventLoggingEvent { private static final String EVENTLOG_URL_PROD = "https://meta.wikimedia.org/beacon/event"; private static final String EVENTLOG_URL_DEV = "http://deployment.wikimedia.beta.wmflabs.org/beacon/event"; private static final String EVENTLOG_URL = IEATTAApp.getInstance().isPreBetaRelease() ? EVENTLOG_URL_DEV : EVENTLOG_URL_PROD; private final JSONObject data; private final String userAgent; /** * Create an EventLoggingEvent that logs to a given revision of a given schema with * the gven data payload. * * @param schema Schema name (as specified on meta.wikimedia.org) * @param revID Revision of the schema to log to * @param wiki DBName (enwiki, dewiki, etc) of the wiki in which we are operating * @param userAgent User-Agent string to use for this request * @param eventData Data for the actual event payload. Considered to be * */ public EventLoggingEvent(String schema, int revID, String wiki, String userAgent, JSONObject eventData) { data = new JSONObject(); try { data.put("schema", schema); data.put("revision", revID); data.put("wiki", wiki); data.put("event", eventData); } catch (JSONException e) { throw new RuntimeException(e); } this.userAgent = userAgent; } /** * Log the current event. * * Returns immediately after queueing the network request in the background. */ public void log() { new LogEventTask(data).execute(); } private class LogEventTask extends SaneAsyncTask<Integer> { private final JSONObject data; LogEventTask(JSONObject data) { this.data = data; } @Override public Integer performTask() throws Throwable { String elUrl = EVENTLOG_URL; String dataURL = Uri.parse(elUrl) .buildUpon().query(data.toString()) .build().toString(); return HttpRequest.get(dataURL).header("User-Agent", userAgent).code(); } @Override public void onCatch(Throwable caught) { // Do nothing bad. EL data is ok to lose. Log.d(Funnel.ANALYTICS_TAG, "Lost EL data: " + data.toString()); } } }
IEATTA for Android.
app/src/main/java/org/wikipedia/analytics/EventLoggingEvent.java
IEATTA for Android.
<ide><path>pp/src/main/java/org/wikipedia/analytics/EventLoggingEvent.java <ide> <ide> import android.net.Uri; <ide> import android.util.Log; <del>import com.github.kevinsawicki.http.HttpRequest; <add>//import com.github.kevinsawicki.http.HttpRequest; <ide> import org.json.JSONException; <ide> import org.json.JSONObject; <ide> import org.ieatta.IEATTAApp; <ide> * Returns immediately after queueing the network request in the background. <ide> */ <ide> public void log() { <del> new LogEventTask(data).execute(); <add>// new LogEventTask(data).execute(); <ide> } <ide> <del> private class LogEventTask extends SaneAsyncTask<Integer> { <del> private final JSONObject data; <del> LogEventTask(JSONObject data) { <del> this.data = data; <del> } <del> <del> @Override <del> public Integer performTask() throws Throwable { <del> String elUrl = EVENTLOG_URL; <del> String dataURL = Uri.parse(elUrl) <del> .buildUpon().query(data.toString()) <del> .build().toString(); <del> return HttpRequest.get(dataURL).header("User-Agent", userAgent).code(); <del> } <del> <del> @Override <del> public void onCatch(Throwable caught) { <del> // Do nothing bad. EL data is ok to lose. <del> Log.d(Funnel.ANALYTICS_TAG, "Lost EL data: " + data.toString()); <del> } <del> } <add>// private class LogEventTask extends SaneAsyncTask<Integer> { <add>// private final JSONObject data; <add>// LogEventTask(JSONObject data) { <add>// this.data = data; <add>// } <add>// <add>// @Override <add>// public Integer performTask() throws Throwable { <add>// String elUrl = EVENTLOG_URL; <add>// String dataURL = Uri.parse(elUrl) <add>// .buildUpon().query(data.toString()) <add>// .build().toString(); <add>// return HttpRequest.get(dataURL).header("User-Agent", userAgent).code(); <add>// } <add>// <add>// @Override <add>// public void onCatch(Throwable caught) { <add>// // Do nothing bad. EL data is ok to lose. <add>// Log.d(Funnel.ANALYTICS_TAG, "Lost EL data: " + data.toString()); <add>// } <add>// } <ide> }
Java
apache-2.0
1c10b2d92869669298fbd335b73a8a8cae66e34d
0
racker/java-service-registry-client
package com.rackspacecloud.client.service_registry.curator; import com.netflix.curator.utils.ThreadUtils; import com.netflix.curator.x.discovery.ServiceCacheBuilder; import com.netflix.curator.x.discovery.ServiceDiscovery; import com.netflix.curator.x.discovery.ServiceInstance; import com.netflix.curator.x.discovery.ServiceProviderBuilder; import com.netflix.curator.x.discovery.strategies.RoundRobinStrategy; import com.rackspacecloud.client.service_registry.Client; import com.rackspacecloud.client.service_registry.HeartBeater; import com.rackspacecloud.client.service_registry.PaginationOptions; import com.rackspacecloud.client.service_registry.SessionCreateResponse; import com.rackspacecloud.client.service_registry.events.client.ClientEvent; import com.rackspacecloud.client.service_registry.events.client.HeartbeatAckEvent; import com.rackspacecloud.client.service_registry.events.client.HeartbeatErrorEvent; import com.rackspacecloud.client.service_registry.events.client.HeartbeatEventListener; import com.rackspacecloud.client.service_registry.events.client.HeartbeatStoppedEvent; import com.rackspacecloud.client.service_registry.objects.Service; import com.rackspacecloud.client.service_registry.objects.Session; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; 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.MissingResourceException; import java.util.Set; public class RSRServiceDiscoveryImpl<T> implements ServiceDiscovery<T> { public static final String DISCOVERY = "discovery"; private static final String NAME = "name"; private static final String ADDRESS = "address"; private static final String PORT = "port"; private static final String REG_TIME = "regtime"; private static final String SVC_TYPE = "svcType"; private static final String SSL_PORT = "sslPort"; private static final String URI_SPEC = "uriSpec"; private final Client client; private final Class<T> typeClass; private final String typeTag; private final Method convert; private volatile Session session; private volatile HeartBeater heartbeater; private final HeartbeatEventListener heartbeatEventListener; private final Map<String, ServiceInstance> services = new HashMap<String, ServiceInstance>(); // needs synchronized public RSRServiceDiscoveryImpl(Client client, Class<T> type) { // deep validation has already been done. try { Method m = type.getMethod("convert", Service.class); m.setAccessible(true); convert = m; } catch (NoSuchMethodException ex) { throw new MissingResourceException("Class does not implement static convert() method", type.getName(), "convert"); } catch (Exception ex) { throw new MissingResourceException(ex.getMessage(), type.getName(), "convert"); } this.client = client; this.typeClass = type; this.typeTag = Utils.sanitizeTag(type.getName()); this.heartbeatEventListener = new CuratorHeartbeatEventListener(); } public void start() throws Exception { // create a session. keep in mind that session ids are ephemeral and may change frequently. getSession(); } public void registerService(ServiceInstance<T> service) throws Exception { List<String> tags = new ArrayList<String>(); tags.add(typeTag); tags.add(service.getName()); tags.add("curator-x-discovery"); Service fsService = client.getServicesClient().create( service.getId(), getSession().getId(), tags, getMetadata(service)); services.put(service.getId(), service); } public void updateService(ServiceInstance<T> service) throws Exception { unregisterService(service); registerService(service); } public void unregisterService(ServiceInstance<T> service) throws Exception { client.getServicesClient().delete(service.getId()); services.remove(service.getId()); } public ServiceCacheBuilder<T> serviceCacheBuilder() { return new RSRServiceCacheBuilderImpl<T>(this) .threadFactory(ThreadUtils.newThreadFactory("RSRServiceCache")); // todo: whither 'name'? } /** return all distinct names registered by this discovery type. */ public Collection<String> queryForNames() throws Exception { Set<String> names = new HashSet<String>(); PaginationOptions options = new PaginationOptions(100, null); List<Service> services = null; // todo: use a set to avoid duplicates. do { // todo: it would be better to do: // services = client.getServicesClient().list(options, typeTag); // but there are some validation problems (the tag is allowed to be written, but not queried on). services = client.getServicesClient().list(options); for (Service service : services) { options = options.withMarker(service.getId()); // this conditional can be removed when the above operation works. if (!service.getTags().contains(typeTag)) { continue; } String name = service.getMetadata().get(NAME); if (!names.contains(name)) { names.add(name); } } } while (services != null && services.size() > 1); return names; } /** return all instances registered to this particular name for this discovery type */ public Collection<ServiceInstance<T>> queryForInstances(String name) throws Exception { List<ServiceInstance<T>> serviceInstances = new ArrayList<ServiceInstance<T>>(); PaginationOptions options = new PaginationOptions(100, null); List<Service> services = null; // todo: use a set to avoid duplicates. do { services = client.getServicesClient().list(options); for (Service service : services) { if (service.getTags().contains(typeTag) && service.getMetadata().get(NAME).equals(name)) { // does the job of the serializer in the curator code (theirs is just a json marshaller anyway). serviceInstances.add(convert(service)); } options = options.withMarker(service.getId()); } } while (services != null && services.size() > 1); return serviceInstances; } public ServiceInstance<T> queryForInstance(String name, String id) throws Exception { return (ServiceInstance<T>) convert.invoke(typeClass, client.getServicesClient().get(id)); } public ServiceProviderBuilder<T> serviceProviderBuilder() { return new RSRServiceProviderBuilderImpl<T>(this) // todo: what about these pieces? //.refreshPaddingMs(1000) //.serviceName("foo") .providerStrategy(new RoundRobinStrategy<T>()) .threadFactory(ThreadUtils.newThreadFactory("RSRServiceProvider")); } public void close() throws IOException { if (this.heartbeater != null) { this.heartbeater.removeEventListener(this.heartbeatEventListener); this.heartbeater.stop(); } this.session = null; } // // helpers // public Client getClient() { return client; } public String getType() { return typeTag; } public ServiceInstance<T> convert(Service service) throws Exception { return (ServiceInstance<T>) convert.invoke(typeClass, service); } private synchronized Session getSession() throws Exception { if (this.session == null) { Map<String, String> sessionMeta = new HashMap<String, String>(); sessionMeta.put(DISCOVERY, typeTag); SessionCreateResponse res = client.getSessionsClient().create(30, sessionMeta); heartbeater = res.getHeartbeater(); heartbeater.addEventListener(this.heartbeatEventListener); heartbeater.start(); this.session = res.getSession(); } return session; } private synchronized void registerAll() throws Exception { for (ServiceInstance svc : services.values()) { registerService(svc); } } private static Map<String, String> getMetadata(ServiceInstance service) { Map<String, String> map = new HashMap<String, String>(); map.put(NAME, service.getName()); map.put(ADDRESS, service.getAddress()); if (service.getPort() != null) map.put(PORT, service.getPort().toString()); map.put(REG_TIME, Long.toString(service.getRegistrationTimeUTC())); map.put(SVC_TYPE, service.getServiceType().name()); if (service.getSslPort() != null) map.put(SSL_PORT, service.getSslPort().toString()); if (service.getUriSpec() != null) map.put(URI_SPEC, service.getUriSpec().build()); // what else? for (Field f : getMetaFields(service.getPayload().getClass())) { try { f.setAccessible(true); map.put(f.getName(), f.get(service.getPayload()).toString()); } catch (Exception ex) { // todo: log } } return map; } private static Collection<Field> getMetaFields(Class cls) { List<Field> allFields = new ArrayList<Field>(); List<Field> metaFields = new ArrayList<Field>(); for (Field f : cls.getDeclaredFields()) allFields.add(f); for (Field f : cls.getFields()) allFields.add(f); for (Field f : allFields) { for (Annotation a : f.getAnnotations()) { if (a.annotationType().equals(Meta.class)) { metaFields.add(f); } } } return metaFields; } private class CuratorHeartbeatEventListener extends HeartbeatEventListener { private void clearSession(ClientEvent event) { ((HeartBeater)event.getSource()).removeEventListener(this); RSRServiceDiscoveryImpl.this.session = null; RSRServiceDiscoveryImpl.this.heartbeater = null; } @Override public void onAck(HeartbeatAckEvent ack) { // do nothing. } @Override public void onStopped(HeartbeatStoppedEvent stopped) { // session was stopped cleanly. clearSession(stopped); if (stopped.isError()) { try { registerAll(); } catch (Exception ex) { // depends on what the exception policy is. } } } @Override public void onError(HeartbeatErrorEvent error) { clearSession(error); if (error.isError()) { try { registerAll(); } catch (Exception ex) { // depends on what the exception policy is. } } } } }
src/main/java/com/rackspacecloud/client/service_registry/curator/RSRServiceDiscoveryImpl.java
package com.rackspacecloud.client.service_registry.curator; import com.netflix.curator.utils.ThreadUtils; import com.netflix.curator.x.discovery.ServiceCacheBuilder; import com.netflix.curator.x.discovery.ServiceDiscovery; import com.netflix.curator.x.discovery.ServiceInstance; import com.netflix.curator.x.discovery.ServiceProviderBuilder; import com.netflix.curator.x.discovery.strategies.RoundRobinStrategy; import com.rackspacecloud.client.service_registry.Client; import com.rackspacecloud.client.service_registry.HeartBeater; import com.rackspacecloud.client.service_registry.PaginationOptions; import com.rackspacecloud.client.service_registry.SessionCreateResponse; import com.rackspacecloud.client.service_registry.events.client.ClientEvent; import com.rackspacecloud.client.service_registry.events.client.HeartbeatAckEvent; import com.rackspacecloud.client.service_registry.events.client.HeartbeatErrorEvent; import com.rackspacecloud.client.service_registry.events.client.HeartbeatEventListener; import com.rackspacecloud.client.service_registry.events.client.HeartbeatStoppedEvent; import com.rackspacecloud.client.service_registry.objects.Service; import com.rackspacecloud.client.service_registry.objects.Session; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; 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.MissingResourceException; import java.util.Set; public class RSRServiceDiscoveryImpl<T> implements ServiceDiscovery<T> { public static final String DISCOVERY = "discovery"; private static final String NAME = "name"; private static final String ADDRESS = "address"; private static final String PORT = "port"; private static final String REG_TIME = "regtime"; private static final String SVC_TYPE = "svcType"; private static final String SSL_PORT = "sslPort"; private static final String URI_SPEC = "uriSpec"; private final Client client; private final Class<T> typeClass; private final String typeTag; private final Method convert; private volatile Session session; private volatile HeartBeater heartbeater; private final HeartbeatEventListener heartbeatEventListener; private final Map<String, ServiceInstance> services = new HashMap<String, ServiceInstance>(); // needs synchronized public RSRServiceDiscoveryImpl(Client client, Class<T> type) { // deep validation has already been done. try { Method m = type.getMethod("convert", Service.class); m.setAccessible(true); convert = m; } catch (NoSuchMethodException ex) { throw new MissingResourceException("Class does not implement static convert() method", type.getName(), "convert"); } catch (Exception ex) { throw new MissingResourceException(ex.getMessage(), type.getName(), "convert"); } this.client = client; this.typeClass = type; this.typeTag = Utils.sanitizeTag(type.getName()); this.heartbeatEventListener = new CuratorHeartbeatEventListener(); } public void start() throws Exception { // create a session. keep in mind that session ids are ephemeral and may change frequently. getSession(); } public void registerService(ServiceInstance<T> service) throws Exception { List<String> tags = new ArrayList<String>(); tags.add(typeTag); tags.add(service.getName()); tags.add("curator-x-discovery"); Service fsService = client.getServicesClient().create( service.getId(), getSession().getId(), tags, getMetadata(service)); services.put(service.getId(), service); } public void updateService(ServiceInstance<T> service) throws Exception { unregisterService(service); registerService(service); } public void unregisterService(ServiceInstance<T> service) throws Exception { client.getServicesClient().delete(service.getId()); services.remove(service.getId()); } public ServiceCacheBuilder<T> serviceCacheBuilder() { return new RSRServiceCacheBuilderImpl<T>(this) .threadFactory(ThreadUtils.newThreadFactory("RSRServiceCache")); // todo: whither 'name'? } /** return all distinct names registered by this discovery type. */ public Collection<String> queryForNames() throws Exception { Set<String> names = new HashSet<String>(); PaginationOptions options = new PaginationOptions(100, null); List<Service> services = null; // todo: use a set to avoid duplicates. do { // todo: it would be better to do: // services = client.getServicesClient().list(options, typeTag); // but there are some validation problems (the tag is allowed to be written, but not queried on). services = client.getServicesClient().list(options); for (Service service : services) { options = options.withMarker(service.getId()); // this conditional can be removed when the above operation works. if (!service.getTags().contains(typeTag)) { continue; } String name = service.getMetadata().get(NAME); if (!names.contains(name)) { names.add(name); } } } while (services != null && services.size() > 1); return names; } /** return all instances registered to this particular name for this discovery type */ public Collection<ServiceInstance<T>> queryForInstances(String name) throws Exception { List<ServiceInstance<T>> serviceInstances = new ArrayList<ServiceInstance<T>>(); PaginationOptions options = new PaginationOptions(100, null); List<Service> services = null; // todo: use a set to avoid duplicates. do { services = client.getServicesClient().list(options); for (Service service : services) { if (service.getTags().contains(typeTag) && service.getMetadata().get(NAME).equals(name)) { // does the job of the serializer in the curator code (theirs is just a json marshaller anyway). serviceInstances.add(convert(service)); } options = options.withMarker(service.getId()); } } while (services != null && services.size() > 1); return serviceInstances; } public ServiceInstance<T> queryForInstance(String name, String id) throws Exception { return (ServiceInstance<T>) convert.invoke(typeClass, client.getServicesClient().get(id)); } public ServiceProviderBuilder<T> serviceProviderBuilder() { return new RSRServiceProviderBuilderImpl<T>(this) // todo: what about these pieces? //.refreshPaddingMs(1000) //.serviceName("foo") .providerStrategy(new RoundRobinStrategy<T>()) .threadFactory(ThreadUtils.newThreadFactory("RSRServiceProvider")); } public void close() throws IOException { if (this.session != null && this.heartbeater != null) { this.heartbeater.removeEventListener(this.heartbeatEventListener); this.heartbeater.stop(); } } // // helpers // public Client getClient() { return client; } public String getType() { return typeTag; } public ServiceInstance<T> convert(Service service) throws Exception { return (ServiceInstance<T>) convert.invoke(typeClass, service); } private synchronized Session getSession() throws Exception { if (this.session == null) { Map<String, String> sessionMeta = new HashMap<String, String>(); sessionMeta.put(DISCOVERY, typeTag); SessionCreateResponse res = client.getSessionsClient().create(30, sessionMeta); heartbeater = res.getHeartbeater(); heartbeater.addEventListener(this.heartbeatEventListener); heartbeater.start(); this.session = res.getSession(); } return session; } private synchronized void registerAll() throws Exception { for (ServiceInstance svc : services.values()) { registerService(svc); } } private static Map<String, String> getMetadata(ServiceInstance service) { Map<String, String> map = new HashMap<String, String>(); map.put(NAME, service.getName()); map.put(ADDRESS, service.getAddress()); if (service.getPort() != null) map.put(PORT, service.getPort().toString()); map.put(REG_TIME, Long.toString(service.getRegistrationTimeUTC())); map.put(SVC_TYPE, service.getServiceType().name()); if (service.getSslPort() != null) map.put(SSL_PORT, service.getSslPort().toString()); if (service.getUriSpec() != null) map.put(URI_SPEC, service.getUriSpec().build()); // what else? for (Field f : getMetaFields(service.getPayload().getClass())) { try { f.setAccessible(true); map.put(f.getName(), f.get(service.getPayload()).toString()); } catch (Exception ex) { // todo: log } } return map; } private static Collection<Field> getMetaFields(Class cls) { List<Field> allFields = new ArrayList<Field>(); List<Field> metaFields = new ArrayList<Field>(); for (Field f : cls.getDeclaredFields()) allFields.add(f); for (Field f : cls.getFields()) allFields.add(f); for (Field f : allFields) { for (Annotation a : f.getAnnotations()) { if (a.annotationType().equals(Meta.class)) { metaFields.add(f); } } } return metaFields; } private class CuratorHeartbeatEventListener extends HeartbeatEventListener { private void clearSession(ClientEvent event) { ((HeartBeater)event.getSource()).removeEventListener(this); RSRServiceDiscoveryImpl.this.session = null; RSRServiceDiscoveryImpl.this.heartbeater = null; } @Override public void onAck(HeartbeatAckEvent ack) { // do nothing. } @Override public void onStopped(HeartbeatStoppedEvent stopped) { // session was stopped cleanly. clearSession(stopped); if (stopped.isError()) { try { registerAll(); } catch (Exception ex) { // depends on what the exception policy is. } } } @Override public void onError(HeartbeatErrorEvent error) { clearSession(error); if (error.isError()) { try { registerAll(); } catch (Exception ex) { // depends on what the exception policy is. } } } } }
don't worry about the session when closing.
src/main/java/com/rackspacecloud/client/service_registry/curator/RSRServiceDiscoveryImpl.java
don't worry about the session when closing.
<ide><path>rc/main/java/com/rackspacecloud/client/service_registry/curator/RSRServiceDiscoveryImpl.java <ide> } <ide> <ide> public void close() throws IOException { <del> if (this.session != null && this.heartbeater != null) { <add> if (this.heartbeater != null) { <ide> this.heartbeater.removeEventListener(this.heartbeatEventListener); <ide> this.heartbeater.stop(); <ide> } <add> this.session = null; <ide> } <ide> <ide> //
JavaScript
mit
48353646de7ea5f56298c616fda77114e2250bbd
0
ligoj/plugin-prov,ligoj/plugin-prov,ligoj/plugin-prov,ligoj/plugin-prov
/* * Licensed under MIT (https://github.com/ligoj/ligoj/blob/master/LICENSE) */ /*jshint esversion: 6*/ define(function () { var current = { /** * Current quote. */ model: null, /** * Usage rate templates */ usageTemplates: {}, contextDonut: null, /** * Enable resource type. */ types: ['instance', 'storage', 'support', 'database'], /** * Show the members of the given group */ configure: function (subscription) { current.model = subscription; current.cleanup(); $('.loader-wrapper').addClass('hidden'); require(['text!../main/service/prov/menu.html'], function (menu) { _('service-prov-menu').empty().remove(); _('extra-menu').append($(Handlebars.compile(menu)(current.$messages))); current.initOdometer(); current.optimizeModel(); current.initializeForm(); current.initializeUpload(); _('subscribe-configuration-prov').removeClass('hide'); $('.provider').text(current.model.node.name); _('name-prov').val(current.model.configuration.name); var now = moment(); $('.prov-export-instances-inline').attr('href', REST_PATH + 'service/prov/' + subscription.id + '/ligoj-prov-instances-inline-storage-' + subscription.id + '-' + now.format('YYYY-MM-DD') + '.csv'); $('.prov-export-instances-split').attr('href', REST_PATH + 'service/prov/' + subscription.id + '/ligoj-prov-split-' + subscription.id + '-' + now.format('YYYY-MM-DD') + '.csv'); }); }, /** * Cleanup the UI component cache. */ cleanup: function () { delete current.contextDonut; delete current.d3Arc; delete current.d3Gauge; $(current.types).each(function (_i, type) { delete current[type + 'Table']; }); }, unload: function () { // Clean the shared menu _('service-prov-menu').empty().remove(); current.cleanup(); }, /** * Reload the model */ reload: function () { // Clear the table var $instances = _('prov-instances').DataTable(); var $storages = _('prov-storages').DataTable(); $instances.clear().draw(); $storages.clear().draw(); $.ajax({ dataType: 'json', url: REST_PATH + 'subscription/' + current.model.subscription + '/configuration', type: 'GET', success: function (data) { current.model = data; current.optimizeModel(); var configuration = data.configuration; $instances.rows.add(configuration.instances).draw(); $storages.rows.add(configuration.storages).draw(); _('quote-location').select2('data', configuration.location); $('.location-wrapper').html(current.locationMap(configuration.location)); _('quote-usage').select2('data', configuration.usage); _('quote-support').select2('data', configuration.supports); _('quote-license').select2('data', configuration.license ? { id: configuration.license, text: current.formatLicense(configuration.license) } : null); } }); }, /** * Request to refresh the cost and trigger a global update as needed */ refreshCost: function () { $.ajax({ type: 'PUT', url: REST_PATH + 'service/prov/' + current.model.subscription + '/refresh', dataType: 'json', success: current.reloadAsNeed }); }, /** * Reload the whole quote if the new cost is different from the previous one. * @param {object} newCost The new cost. * @param {function} forceUpdateUi When true, the UI is always refreshed, even when the cost has not been updated. */ reloadAsNeed: function (newCost, forceUpdateUi) { var dirty = true; if (newCost.min !== current.model.configuration.cost.min || newCost.max !== current.model.configuration.cost.max) { // The cost has been updated current.model.configuration.cost = newCost; notifyManager.notify(current.$messages['service:prov:refresh-needed']); dirty = false; current.reload(); } else { // The cost still the same notifyManager.notify(current.$messages['service:prov:refresh-no-change']); } if (dirty && forceUpdateUi) { current.updateUiCost(); } }, /** * Render Provisioning management link. */ renderFeatures: function (subscription) { // Add quote configuration link var result = current.$super('renderServiceLink')('calculator', '#/home/project/' + subscription.project + '/subscription/' + subscription.id, 'service:prov:manage'); // Help result += current.$super('renderServiceHelpLink')(subscription.parameters, 'service:prov:help'); return result; }, /** * Display the cost of the quote. */ renderDetailsFeatures: function (subscription) { if (subscription.data.quote && (subscription.data.quote.cost.min || subscription.data.quote.cost.max)) { var price = current.formatCost(subscription.data.quote.cost, null, null, true); return '<span data-toggle="tooltip" title="' + current.$messages['service:prov:cost-title'] + ' : ' + price + '" class="price label label-default">' + price + '</span>'; } }, /** * Render provisioning details : cpu, ram, nbVm, storages. */ renderDetailsKey: function (subscription) { var quote = subscription.data.quote; var resources = []; if (quote.nbInstances) { resources.push('<span class="sub-item">' + current.$super('icon')('server', 'service:prov:nb-instances') + quote.nbInstances + ' VM</span>'); } if (quote.nbDatabases) { resources.push('<span class="sub-item">' + current.$super('icon')('database', 'service:prov:nb-databases') + quote.nbDatabases + ' DB</span>'); } if (quote.nbInstances || quote.nbDatabases) { resources.push('<span class="sub-item">' + current.$super('icon')('bolt', 'service:prov:total-cpu') + quote.totalCpu + ' ' + current.$messages['service:prov:cpu'] + '</span>'); resources.push('<span class="sub-item">' + current.$super('icon')('microchip', 'service:prov:total-ram') + current.formatRam(quote.totalRam) + '</span>'); } if (quote.nbPublicAccess) { resources.push('<span class="sub-item">' + current.$super('icon')('globe', 'service:prov:nb-public-access') + quote.nbPublicAccess + '</span>'); } if (quote.totalStorage) { resources.push('<span class="sub-item">' + current.$super('icon')('fas fa-hdd', 'service:prov:total-storage') + current.formatStorage(quote.totalStorage) + '</span>'); } return current.$super('generateCarousel')(subscription, [ ['name', quote.name], ['service:prov:resources', resources.join(', ')], ['service:prov:location', current.$super('icon')('map-marker-alt', 'service:prov:location') + current.locationToHtml(quote.location, true)] ], 1); }, /** * Format instance type details. */ formatInstanceType: function (name, mode, qi) { var type = qi ? qi.price.type : {}; name = type ? type.name : name; if (mode !== 'display' || (typeof type.id === 'undefined')) { // Use only the name return name; } // Instance type details are available var details = type.description ? type.description.replace(/"/g, '') + '<br>' : ''; details += '<i class=\'fas fa-bolt fa-fw\'></i> '; details += type.cpuRate ? '<i class=\'' + current.rates[type.cpuRate] + '\'></i> ' : ''; if (type.cpu) { details += '#' + type.cpu; details += ' ' + current.formatConstant(type.constant); } else { details += current.$messages['service:prov:instance-custom']; } if (type.ram) { details += '<br><i class=\'fas fa-microchip fa-fw\'></i> '; details += type.ramRate ? '<i class=\'' + current.rates[type.ramRate] + '\'></i> ' : ''; details += current.formatRam(type.ram); } if (type.storageRate) { details += '<br><i class=\'far fa-hdd fa-fw\'></i> '; details += type.ramRate ? '<i class=\'' + current.rates[type.storageRate] + '\'></i>' : ''; // TODO Add instance storage } if (type.networkRate) { details += '<br><i class=\'fas fa-globe fa-fw\'></i> '; details += type.ramRate ? '<i class=\'' + current.rates[type.networkRate] + '\'></i>' : ''; // TODO Add memory type } return '<u class="details-help" data-toggle="popover" title="' + name + '" data-content="' + details + '">' + name + '</u>'; }, formatStorageType: function (name, mode, qs) { var type = qs ? qs.price.type : {}; name = type ? type.name : name; if (mode !== 'display' || (typeof type.id === 'undefined')) { // Use only the name return name; } // Storage type details are available var details = type.description ? type.description.replace(/"/g, '') + '<br>' : ''; details += '<i class=\'far fa-hdd fa-fw\'></i> '; details += formatManager.formatSize((type.minimal || 1) * 1024 * 1024 * 1024, 3) + ' - '; details += type.maximal ? formatManager.formatSize(type.maximal * 1024 * 1024 * 1024, 3) : '∞'; if (type.latency) { details += '<br><i class=\'fas fa-fw fa-stopwatch\'></i> <i class=\'' + current.rates[type.latency] + '\'></i>'; } if (type.iops) { details += '<br><i class=\'' + current.storageOptimized.iops + '\'></i> ' + type.iops + ' IOPS'; } if (type.throughput) { details += '<br><i class=\'' + current.storageOptimized.throughput + '\'></i> ' + type.throughput + ' MB/s'; } if (type.durability9) { var nines = '9'.repeat(type.durability9); nines = type.durability9 < 3 ? '0'.repeat(3 - type.durability9) : nines; details += '<br><i class=\'far fa-fw fa-gem\'></i> ' + nines.substring(0, 2) + '.' + nines.substring(2) + '%'; } if (type.availability) { details += '<br><i class=\'fas fa-fw fa-thumbs-up\'></i> ' + type.availability + '%'; } return '<u class="details-help" data-toggle="popover" title="' + name + '" data-content="' + details + '">' + name + '</u>'; }, /** * Format instance term detail */ formatInstanceTerm: function (name, mode, qi) { var term = qi ? qi.price.term : null; name = term ? term.name : name; if (mode === 'sort' || (term && typeof term.id === 'undefined')) { // Use only the name return name; } // Instance details are available var details = '<i class=\'fas fa-clock\'></i> '; if (term && term.period) { details += term.period + ' months period'; } else { details = 'on demand, hourly (or less) billing period'; } if (qi.price.initialCost) { details += '<br/>Initial cost: $' + qi.price.initialCost; } return '<u class="details-help" data-toggle="popover" title="' + name + '" data-content="' + details + '">' + name + '</u>'; }, /** * Format instance quantity */ formatQuantity: function (quantity, mode, instance) { var min = typeof instance === 'undefined' ? quantity : (instance.minQuantity || 0); if (mode === 'sort' || mode === 'filter' || typeof instance === 'undefined') { return min; } var max = instance.maxQuantity; if (typeof max !== 'number') { return min + '+'; } if (max === min) { return min; } // A range return min + '-' + max; }, /** * Format the constant CPU. */ formatConstant: function (constant) { return current.$messages[constant === true ? 'service:prov:cpu-constant' : 'service:prov:cpu-variable']; }, /** * Format the cost. * @param {number} cost The cost value. May contains "min" and "max" attributes. * @param {String|jQuery} mode Either 'sort' for a raw value, either a JQuery container for advanced format with "odometer". Otherwise will be simple format. * @param {object} obj The optional cost object taking precedence over the cost parameter. May contains "min" and "max" attributes. * @param {boolean} noRichText When true, the cost will be in plain text, no HTML markup. * @return The formated cost. */ formatCost: function (cost, mode, obj, noRichText) { if (mode === 'sort' || mode === 'filter') { return cost; } var formatter = current.formatCostText; var $cost = $(); if (mode instanceof jQuery) { // Odomoter format formatter = current.formatCostOdometer; $cost = mode; } // Computation part obj = (typeof obj === 'undefined' || obj === null) ? cost : obj; if (typeof obj.cost === 'undefined' && typeof obj.min !== 'number') { // Standard cost $cost.find('.cost-min').addClass('hidden'); return formatter(cost, true, $cost, noRichText, cost && cost.unbound); } // A floating cost var min = obj.cost || obj.min || 0; var max = typeof obj.maxCost === 'number' ? obj.maxCost : obj.max; var unbound = (min !== max) || obj.unbound || (cost && cost.unbound) || (obj.minQuantity != obj.maxQuantity); if ((typeof max !== 'number') || max === min) { // Max cost is equal to min cost, no range $cost.find('.cost-min').addClass('hidden'); return formatter(min, true, $cost, noRichText, unbound); } // Max cost, is different, display a range return formatter(min, false, $cost, noRichText) + '-' + formatter(max, true, $cost, noRichText, unbound); }, /** * Configure Odometer components */ initOdometer: function () { var $cost = $('.cost'); var weightUnit = '<span class="cost-weight"></span><span class="cost-unit"></span>'; $cost.append('<span class="cost-min hidden"><span class="odo-wrapper cost-value"></span>' + weightUnit + '<span class="cost-separator">-</span></span>'); $cost.append('<span class="cost-max"><span class="odo-wrapper cost-value"></span>' + weightUnit + '</span>'); require(['../main/service/prov/lib/odometer'], function (Odometer) { // Odometer component current.registerOdometer(Odometer, $('#service-prov-menu').find('.odo-wrapper')); current.updateUiCost(); }); }, registerOdometer: function (Odometer, $container) { $container.each(function () { new Odometer({ el: $(this)[0], theme: 'minimal', duration: 0 }).render(); }); }, formatCostOdometer: function (cost, isMax, $cost, noRichTest, unbound) { if (isMax) { formatManager.formatCost(cost, 3, '$', 'cost-unit', function (value, weight, unit) { var $wrapper = $cost.find('.cost-max'); $wrapper.find('.cost-value').html(value); $wrapper.find('.cost-weight').html(weight + ((cost.unbound || unbound) ? '+' : '')); $wrapper.find('.cost-unit').html(unit); }); } else { formatManager.formatCost(cost, 3, '$', 'cost-unit', function (value, weight, unit) { var $wrapper = $cost.find('.cost-min').removeClass('hidden'); $wrapper.find('.cost-value').html(value); $wrapper.find('.cost-weight').html(weight); $wrapper.find('.cost-unit').html(unit); }); } }, formatCostText: function (cost, isMax, _i, noRichText, unbound) { return formatManager.formatCost(cost, 3, '$', noRichText === true ? '' : 'cost-unit') + (unbound ? '+' : ''); }, /** * Format the memory size. */ formatRam: function (sizeMB, mode, instance) { if (mode === 'sort' || mode === 'filter') { return sizeMB; } if (mode === 'display' && instance) { return current.formatEfficiency(sizeMB, instance.price.type.ram, function (value) { return formatManager.formatSize(value * 1024 * 1024, 3); }); } return formatManager.formatSize(sizeMB * 1024 * 1024, 3); }, /** * Format the memory size. */ formatCpu: function (value, mode, instance) { if (mode === 'display' && instance) { return current.formatEfficiency(value, instance.price.type.cpu); } return value; }, /** * Format the efficiency of a data depending on the rate against the maximum value. * @param value {number} Current value. * @param max {number} Maximal value. * @param formatter {function} Option formatter function of the value. * @returns {string} The value to display containing the rate. */ formatEfficiency: function (value, max, formatter) { var fullClass = null; max = max || value || 1; if (value === 0) { value = max; } else if (max / 2.0 > value) { fullClass = 'far fa-circle text-danger'; } else if (max / 1.65 > value) { fullClass = 'fas fa-adjust fa-rotate-270 text-danger'; } else if (max / 1.5 > value) { fullClass = 'fas fa-adjust fa-rotate-270 text-warning'; } else if (max / 1.3 > value) { fullClass = 'fas fa-circle text-primary'; } else if (max / 1.01 > value) { fullClass = 'fas fa-circle text-success'; } var rate = Math.round(value * 100 / max); return (formatter ? formatter(value) : value) + (fullClass ? '<span class="efficiency pull-right"><i class="' + fullClass + '" data-toggle="tooltip" title="' + Handlebars.compile(current.$messages['service:prov:usage-partial'])((formatter ? [formatter(value), formatter(max), rate] : [value, max, rate])) + '"></i></span>' : ''); }, /** * Format the storage size. */ formatStorage: function (sizeGB, mode, data) { if (mode === 'sort' || mode === 'filter') { return sizeGB; } if (data && data.price.type.minimal > sizeGB) { // Enable efficiency display return current.formatEfficiency(sizeGB, data.price.type.maximal, function (value) { return formatManager.formatSize(value * 1024 * 1024 * 1024, 3); }); } // No efficiency rendering can be done return formatManager.formatSize(sizeGB * 1024 * 1024 * 1024, 3); }, /** * Format the storage size to html markup. * @param {object} qs Quote storage with price, type and size. * @param {boolean} showName When true, the type name is displayed. Default is false. * @return {string} The HTML markup representing the quote storage : type and flags. */ formatStorageHtml: function (qs, showName) { var type = qs.price.type; return (showName === true ? type.name + ' ' : '') + current.formatStorageLatency(type.latency) + (type.optimized ? ' ' + current.formatStorageOptimized(type.optimized) : '') + ' ' + formatManager.formatSize(qs.size * 1024 * 1024 * 1024, 3) + ((qs.size < type.minimal) ? ' (' + formatManager.formatSize(type.minimal * 1024 * 1024 * 1024, 3) + ')' : ''); }, /** * Format the storage price to html markup. * @param {object} qs Quote storage with price, type and size. * @return {string} The HTML markup representing the quote storage : cost, type and flags. */ formatStoragePriceHtml: function (qs) { return current.formatStorageHtml(qs, false) + ' ' + qs.price.type.name + '<span class="pull-right text-small">' + current.formatCost(qs.cost) + '<span class="cost-unit">/m</span></span>'; }, /** * Format an attached storages */ formatQiStorages: function (instance, mode) { // Compute the sum var storages = instance.storages; var sum = 0; if (storages) { storages.forEach(storage => sum += storage.size); } if (mode === 'display') { // Need to build a Select2 tags markup return '<input type="text" class="storages-tags" data-instance="' + instance.id + '" autocomplete="off" name="storages-tags">'; } return sum; }, /** * OS key to markup/label mapping. */ os: { 'linux': ['Linux', 'fab fa-linux fa-fw'], 'windows': ['Windows', 'fab fa-windows fa-fw'], 'suse': ['SUSE', 'icon-suse fa-fw'], 'rhel': ['Red Hat Enterprise', 'icon-redhat fa-fw'], 'centos': ['CentOS', 'icon-centos fa-fw'], 'debian': ['Debian', 'icon-debian fa-fw'], 'fedora': ['Fedora', 'icon-fedora fa-fw'], 'ubuntu': ['Ubuntu', 'icon-ubuntu fa-fw'] }, /** * Engine key to markup/label mapping. */ databaseEngines: { 'MYSQL': ['MySQL', 'icon-mysql'], 'ORACLE': ['Oracle', 'icon-oracle'], 'MARIADB': ['MariaDB', 'icon-mariadb'], 'AURORA MYSQL': ['Aurora MySQL', 'icon-aws'], 'AURORA POSTGRESQL': ['Aurora PostgreSQL', 'icon-aws'], 'POSTGRESQL': ['PostgreSQL', 'icon-postgres'], 'SQL SERVER': ['SQL Server', 'icon-mssql'], }, /** * Internet Access key to markup/label mapping. */ internet: { 'public': ['Public', 'fas fa-globe fa-fw'], 'private': ['Private', 'fas fa-lock fa-fw'], 'private_nat': ['NAT', 'fas fa-low-vision fa-fw'] }, /** * Rate name (identifier) to class mapping. Classes are ditributed across 5 values. */ rates: { 'worst': 'far fa-star text-danger fa-fw', 'low': 'fas fa-star-half text-danger fa-fw', 'medium': 'fas fa-star-half fa-fw', 'good': 'fas fa-star text-primary fa-fw', 'best': 'fas fa-star text-success fa-fw', 'invalid': 'fas fa-ban fa-fw' }, /** * Rate name (identifier) to class mapping. Classes are ditributed across 3 values. */ rates3: { 'low': 'far fa-star-half fa-fw', 'medium': 'far fa-star text-success fa-fw', 'good': 'fas fa-star text-success fa-fw', 'invalid': 'fas fa-ban fa-fw' }, /** * Storage optimized key to markup/label mapping. */ storageOptimized: { 'throughput': 'fas fa-angle-double-right fa-fw', 'durability': 'fas fa-archive fa-fw', 'iops': 'fas fa-bolt fa-fw' }, /** * Support access type key to markup/label mapping. */ supportAccessType: { 'technical': 'fas fa-wrench fa-fw', 'billing': 'fas fa-dollar-sign fa-fw', 'all': 'fas fa-users fa-fw' }, /** * Return the HTML markup from the OS key name. */ formatOs: function (os, mode, clazz) { var cfg = current.os[(os.id || os || 'linux').toLowerCase()] || current.os.linux; if (mode === 'sort' || mode === 'filter') { return cfg[0]; } clazz = cfg[1] + (typeof clazz === 'string' ? clazz : ''); return '<i class="' + clazz + '" data-toggle="tooltip" title="' + cfg[0] + '"></i>' + (mode === 'display' ? '' : ' ' + cfg[0]); }, /** * Return the HTML markup from the Internet privacy key name. */ formatInternet: function (internet, mode, clazz) { var cfg = (internet && current.internet[(internet.id || internet).toLowerCase()]) || current.internet.public || 'public'; if (mode === 'sort') { return cfg[0]; } clazz = cfg[1] + (typeof clazz === 'string' ? clazz : ''); return '<i class="' + clazz + '" data-toggle="tooltip" title="' + cfg[0] + '"></i>' + (mode === 'display' ? '' : ' ' + cfg[0]); }, formatUsageTemplate: function (usage, mode) { if (usage) { // TODO } else { usage = current.model.configuration.usage || { rate: 100, duration: 1, name: '<i>default</i>' }; } if (mode === 'display') { var tooltip = current.$messages.name + ': ' + usage.name; tooltip += '<br>' + current.$messages['service:prov:usage-rate'] + ': ' + (usage.rate || 100) + '%'; tooltip += '<br>' + current.$messages['service:prov:usage-duration'] + ': ' + (usage.duration || 1) + ' month(s)'; tooltip += '<br>' + current.$messages['service:prov:usage-start'] + ': ' + (usage.start || 0) + ' month(s)'; return '<span data-toggle="tooltip" title="' + tooltip + '">' + usage.name + '</span>'; } return usage.text || usage.name; }, formatLocation: function (location, mode, data) { var conf = current.model.configuration; var obj; if (location) { if (location.id) { obj = location; } else { obj = conf.locationsById[location]; } } else if (data.price && data.price.location) { obj = conf.locationsById[data.price.location]; } else if (data.quoteInstance && data.quoteInstance.price.location) { obj = conf.locationsById[data.quoteInstance.price.location]; } else if (data.quoteDatabase && data.quoteDatabase.price.location) { obj = conf.locationsById[data.quoteDatabase.price.location]; } else { obj = current.model.configuration.location; } if (mode === 'display') { return current.locationToHtml(obj, false, true); } return obj ? obj.name : ''; }, /** * Return the HTML markup from the quote instance model. */ formatQuoteInstance: function (quoteInstance) { return quoteInstance.name; }, /** * Return the HTML markup from the support level. */ formatSupportLevel: function (level, mode, clazz) { var id = level ? (level.id || level).toLowerCase() : ''; if (id) { var text = current.$messages['service:prov:support-level-' + id]; clazz = current.rates3[id] + (typeof clazz === 'string' ? clazz : ''); if (mode === 'sort' || mode === 'filter') { return text; } return '<i class="' + clazz + '" data-toggle="tooltip" title="' + text + '"></i>' + (mode ? ' ' + text : ''); } return ''; }, /** * Return the HTML markup from the support seats. */ formatSupportSeats: function (seats, mode) { if (mode === 'sort' || mode === 'filter') { return seats || 0; } return seats ? seats : '∞'; }, /** * Return the HTML markup from the storage latency. */ formatStorageLatency: function (latency, mode, clazz) { var id = latency ? (latency.id || latency).toLowerCase() : 'invalid'; var text = id && current.$messages['service:prov:storage-latency-' + id]; if (mode === 'sort' || mode === 'filter') { return text; } clazz = current.rates[id] + (typeof clazz === 'string' ? clazz : ''); return '<i class="' + clazz + '" data-toggle="tooltip" title="' + text + '"></i>' + (mode ? ' ' + text : ''); }, /** * Return the HTML markup from the storage optimized. */ formatStorageOptimized: function (optimized, withText, clazz) { if (optimized) { var id = (optimized.id || optimized).toLowerCase(); var text = current.$messages['service:prov:storage-optimized-' + id]; clazz = current.storageOptimized[id] + (typeof clazz === 'string' ? clazz : ''); return '<i class="' + clazz + '" data-toggle="tooltip" title="' + text + '"></i>' + (withText ? ' ' + text : ''); } }, /** * Return the HTML markup from the support access type. */ formatSupportAccess: function (type, mode) { if (type) { var id = (type.id || type).toLowerCase(); var text = current.$messages['service:prov:support-access-' + id]; if (mode === 'sort' || mode === 'filter') { return text; } var clazz = current.supportAccessType[id]; return '<i class="' + clazz + '" data-toggle="tooltip" title="' + text + '"></i>' + (mode === 'display' ? '' : (' ' + text)); } }, /** * Associate the storages to the instances */ optimizeModel: function () { var conf = current.model.configuration; var i, qi; // Instances conf.instancesById = {}; conf.instanceCost = 0; var instances = conf.instances; for (i = 0; i < instances.length; i++) { qi = instances[i]; // Optimize id access conf.instancesById[qi.id] = qi; conf.instanceCost += qi.cost; } // Databases conf.databasesById = {}; conf.databaseCost = 0; var databases = conf.databases; for (i = 0; i < databases.length; i++) { qi = databases[i]; // Optimize id access conf.databasesById[qi.id] = qi; conf.databaseCost += qi.cost; } // Storage conf.storagesById = {}; conf.storageCost = 0; var storages = conf.storages; for (i = 0; i < storages.length; i++) { var qs = storages[i]; conf.storageCost += qs.cost; current.attachStorage(qs, 'instance', qs.quoteInstance, true); current.attachStorage(qs, 'database', qs.quoteDatabase, true); // Optimize id access conf.storagesById[qs.id] = qs; } // Locations conf.locationsById = {}; var locations = conf.locations; for (i = 0; i < locations.length; i++) { var loc = locations[i]; // Optimize id access conf.locationsById[loc.name] = loc; } // Support conf.supportsById = {}; conf.supportCost = 0; var supports = conf.supports; for (i = 0; i < supports.length; i++) { var qs2 = supports[i]; // Optimize id access conf.supportsById[qs2.id] = qs2; conf.supportCost += qs2.cost; } current.initializeTerraformStatus(); current.updateUiCost(); }, /** * Refresh the Terraform status embedded in the quote. */ initializeTerraformStatus: function () { if (current.model.configuration.terraformStatus) { current.updateTerraformStatus(current.model.configuration.terraformStatus, true); if (typeof current.model.configuration.terraformStatus.end === 'undefined') { // At least one snapshot is pending: track it setTimeout(function () { // Poll the unfinished snapshot current.pollStart('terraform-' + current.model.subscription, current.model.subscription, current.synchronizeTerraform); }, 10); } } else { _('prov-terraform-status').addClass('invisible'); current.enableTerraform(); } }, /** * Return the query parameter name to use to filter some other inputs. */ toQueryName: function (type, $item) { var id = $item.attr('id'); return id.indexOf(type + '-') === 0 && id.substring((type + '-').length); }, /** * Return the memory query parameter value to use to filter some other inputs. */ toQueryValueRam: function (value) { return (current.cleanInt(value) || 0) * parseInt(_('instance-ram-unit').find('li.active').data('value'), 10); }, /** * Return the constant CPU query parameter value to use to filter some other inputs. */ toQueryValueConstant: function (value) { return value === 'constant' ? true : (value === 'variable' ? false : null); }, /** * Disable the create/update button * @return the related button. */ disableCreate: function ($popup) { return $popup.find('input[type="submit"]').attr('disabled', 'disabled').addClass('disabled'); }, /** * Enable the create/update button * @return the related button. */ enableCreate: function ($popup) { return $popup.find('input[type="submit"]').removeAttr('disabled').removeClass('disabled'); }, /** * Checks there is at least one instance matching to the requirement. * Uses the current "this" jQuery context to get the UI context. */ checkResource: function () { var $form = $(this).closest('[data-prov-type]'); var queries = []; var type = $form.attr('data-prov-type'); var popupType = (type == 'instance' || type == 'database') ? 'generic' : type; var $popup = _('popup-prov-' + popupType); // Build the query $form.find('.resource-query').filter(function () { return $(this).closest('[data-exclusive]').length === 0 || $(this).closest('[data-exclusive]').attr('data-exclusive') === type; }).each(function () { current.addQuery(type, $(this), queries); if (type === 'database') { // Also include the instance inputs current.addQuery('instance', $(this), queries); } }); // Check the availability of this instance for these requirements current.disableCreate($popup); $.ajax({ dataType: 'json', url: REST_PATH + 'service/prov/' + current.model.subscription + '/' + type + '-lookup/?' + queries.join('&'), type: 'GET', success: function (suggest) { current[type + 'SetUiPrice'](suggest); if (suggest && (suggest.price || ($.isArray(suggest) && suggest.length))) { // The resource is valid, enable the create current.enableCreate($popup); } }, error: function () { current.enableCreate($popup); } }); }, addQuery(type, $item, queries) { var value = current.getResourceValue($item); var queryParam = value && current.toQueryName(type, $item); if (queryParam) { value = $item.is('[type="checkbox"]') ? $item.is(':checked') : value; var toValue = current['toQueryValue' + queryParam.capitalize()]; value = toValue ? toValue(value, $item) : value; if (value || value === false) { // Add as query queries.push(queryParam + '=' + encodeURIComponent(value)); } } }, getResourceValue: function ($item) { var value = ''; if ($item.is('.input-group-btn')) { value = $item.find('li.active').data('value'); } else if ($item.prev().is('.select2-container')) { var data = ($item.select2('data') || {}); value = $item.is('.named') ? data.name || (data.data && data.data.name) : (data.id || $item.val()); } else if ($item.is('[type="number"]')) { value = parseInt(current.cleanData($item.val()) || "0", 10); } else if (!$item.is('.select2-container')) { value = current.cleanData($item.val()); } return value; }, /** * Set the current storage price. * @param {object|Array} Quote or prices */ storageSetUiPrice: function (quote) { if (quote && (($.isArray(quote) && quote.length) || quote.price)) { var suggests = quote; if (!$.isArray(quote)) { // Single price suggests = [quote]; } for (var i = 0; i < suggests.length; i++) { suggests[i].id = suggests[i].id || suggests[i].price.id; } var suggest = suggests[0]; _('storage-price').select2('destroy').select2({ data: suggests, formatSelection: current.formatStoragePriceHtml, formatResult: current.formatStoragePriceHtml }).select2('data', suggest); } else { _('storage-price').select2('data', null); } current.updateInstanceCompatible(_('storage-price').select2('data')); }, /** * Depending on the current storage type, enable/disable the instance selection */ updateInstanceCompatible: function (suggest) { if (suggest && suggest.price && suggest.price.type.instanceCompatible === false) { // Disable _('storage-instance').select2('data', null).select2('disable'); _('storage-instance').prev('.select2-container').find('.select2-chosen').text(current.$messages['service:prov:cannot-attach-instance']); } else { // Enable _('storage-instance').select2('enable'); if (_('storage-instance').select2('data') === null) { _('storage-instance').prev('.select2-container').find('.select2-chosen').text(current.$messages['service:prov:no-attached-instance']); } } }, /** * Set the current instance/database price. */ genericSetUiPrice: function (quote) { if (quote && quote.price) { var suggests = [quote]; _('instance-price').select2('destroy').select2({ data: suggests, formatSelection: function (qi) { return qi.price.type.name + ' (' + current.formatCost(qi.cost, null, null, true) + '/m)'; }, formatResult: function (qi) { return qi.price.type.name + ' (' + current.formatCost(qi.cost, null, null, true) + '/m)'; } }).select2('data', quote); _('instance-term').select2('data', quote.price.term).val(quote.price.term.id); } else { _('instance-price').select2('data', null); } }, /** * Set the current instance price. */ instanceSetUiPrice: function (quote) { current.genericSetUiPrice(quote); }, /** * Set the current instance price. */ databaseSetUiPrice: function (quote) { current.genericSetUiPrice(quote); }, /** * Set the current support price. */ supportSetUiPrice: function (quote) { if (quote && (($.isArray(quote) && quote.length) || quote.price)) { var suggests = quote; if (!$.isArray(quote)) { // Single price suggests = [quote]; } for (var i = 0; i < suggests.length; i++) { suggests[i].id = suggests[i].id || suggests[i].price.id; } var suggest = suggests[0]; _('support-price').select2('destroy').select2({ data: suggests, formatSelection: function (qi) { return qi.price.type.name + ' (' + current.formatCost(qi.cost, null, null, true) + '/m)'; }, formatResult: function (qi) { return qi.price.type.name + ' (' + current.formatCost(qi.cost, null, null, true) + '/m)'; } }).select2('data', suggest); } else { _('support-price').select2('data', null); } }, /** * Initialize data tables and popup event : delete and details */ initializeDataTableEvents: function (type) { var oSettings = current[type + 'NewTable'](); var popupType = (type == 'instance' || type == 'database') ? 'generic' : type; var $table = _('prov-' + type + 's'); $.extend(oSettings, { data: current.model.configuration[type + 's'] || [], dom: 'Brt<"row"<"col-xs-6"i><"col-xs-6"p>>', destroy: true, stateSave: true, stateDuration: 0, stateLoadCallback: function (settings, callback) { try { return JSON.parse(localStorage.getItem('service:prov/' + type)); } catch (e) { // Ignore the state error log callback(null); } }, stateLoadParams: function (settings, data) { if (data && data.search && data.search.search) { // Restore the filter input $table.closest('[data-prov-type]').find('.subscribe-configuration-prov-search').val(data.search.search); } }, stateSaveCallback: function (settings, data) { try { localStorage.setItem('service:prov/' + type, JSON.stringify(data)); } catch (e) { // Ignore the state error log } }, searching: true, createdRow: (nRow, data) => $(nRow).attr('data-id', data.id), buttons: [{ extend: 'colvis', postfixButtons: ['colvisRestore'], columns: ':not(.noVis)', columnText: (dt, idx) => dt.settings()[0].aoColumns[idx].sTitle }], columnDefs: [{ targets: 'noVisDefault', visible: false }], language: { buttons: { colvis: '<i class="fas fa-cog"></i>', colvisRestore: current.$messages['restore-visibility'] } }, }); oSettings.columns.splice(0, 0, { data: 'name', className: 'truncate' }); oSettings.columns.push( { data: 'cost', className: 'truncate hidden-xs', render: current.formatCost }, { data: null, width: '32px', orderable: false, render: function () { var links = '<a class="update" data-toggle="modal" data-target="#popup-prov-' + popupType + '"><i class="fas fa-pencil-alt" data-toggle="tooltip" title="' + current.$messages.update + '"></i></a>'; return links + '<a class="delete"><i class="fas fa-trash-alt" data-toggle="tooltip" title="' + current.$messages.delete + '"></i></a>'; } }); var dataTable = $table.dataTable(oSettings); $table.on('click', '.delete', function () { // Delete a single row/item var resource = dataTable.fnGetData($(this).closest('tr')[0]); $.ajax({ type: 'DELETE', url: REST_PATH + 'service/prov/' + type + '/' + resource.id, success: function (updatedCost) { current.defaultCallback(type, updatedCost); } }); }).on('click', '.delete-all', function () { // Delete all items $.ajax({ type: 'DELETE', url: REST_PATH + 'service/prov/' + current.model.subscription + '/' + type, success: function (updatedCost) { current.defaultCallback(type, updatedCost); } }); }); current[type + 'Table'] = dataTable; }, /** * Initialize data tables and popup event : delete and details */ initializePopupEvents: function (type) { // Resource edition pop-up var popupType = (type == 'instance' || type == 'database') ? 'generic' : type; var $popup = _('popup-prov-' + popupType); $popup.on('shown.bs.modal', function () { var inputType = (type == 'instance' || type == 'database') ? 'instance' : type; _(inputType + '-name').trigger('focus'); }).on('submit', function (e) { e.preventDefault(); var dynaType = $(this).closest('[data-prov-type]').attr('data-prov-type'); current.save(dynaType); }).on('show.bs.modal', function (event) { var $source = $(event.relatedTarget); var $tr = $source.closest('tr'); var dynaType = $source.closest('[data-prov-type]').attr('data-prov-type'); var $table = _('prov-' + dynaType + 's'); var quote = ($tr.length && $table.dataTable().fnGetData($tr[0])) || {}; $(this).attr('data-prov-type', dynaType) .find('input[type="submit"]') .removeClass('btn-primary btn-success') .addClass(quote.id ? 'btn-primary' : 'btn-success'); $popup.find('.old-required').removeClass('old-required').attr('required', 'required'); $popup.find('[data-exclusive]').not('[data-exclusive="' + dynaType + '"]').find(':required').addClass('old-required').removeAttr('required'); if (quote.id) { current.enableCreate($popup); } else { current.disableCreate($popup); } current.model.quote = quote; current.toUi(dynaType, quote); }); }, initializeUpload: function () { var $popup = _('popup-prov-instance-import'); _('csv-headers-included').on('change', function () { if ($(this).is(':checked')) { // Useless input headers _('csv-headers').closest('.form-group').addClass('hidden'); } else { _('csv-headers').closest('.form-group').removeClass('hidden'); } }); $popup.on('shown.bs.modal', function () { _('csv-file').trigger('focus'); }).on('show.bs.modal', function () { $('.import-summary').addClass('hidden'); }).on('submit', function (e) { // Avoid useless empty optional inputs _('instance-usage-upload-name').val((_('instance-usage-upload').select2('data') || {}).name || null); _('csv-headers-included').val(_('csv-headers-included').is(':checked') ? 'true' : 'false'); $popup.find('input[type="text"]').not('[readonly]').not('.select2-focusser').not('[disabled]').filter(function () { return $(this).val() === ''; }).attr('disabled', 'disabled').attr('readonly', 'readonly').addClass('temp-disabled').closest('.select2-container').select2('enable', false); $(this).ajaxSubmit({ url: REST_PATH + 'service/prov/' + current.model.subscription + '/upload', type: 'POST', dataType: 'json', beforeSubmit: function () { // Reset the summary current.disableCreate($popup); validationManager.reset($popup); validationManager.mapping.DEFAULT = 'csv-file'; $('.import-summary').html('Processing...'); $('.loader-wrapper').removeClass('hidden'); }, success: function () { $popup.modal('hide'); // Refresh the data current.reload(); }, complete: function () { $('.loader-wrapper').addClass('hidden'); $('.import-summary').html('').addClass('hidden'); // Restore the optional inputs $popup.find('input.temp-disabled').removeAttr('disabled').removeAttr('readonly').removeClass('temp-disabled').closest('.select2-container').select2('enable', true); current.enableCreate($popup); } }); e.preventDefault(); return false; }); }, initializeForm: function () { // Global datatables filter $('.subscribe-configuration-prov-search').on('keyup', function (event) { if (event.which !== 16 && event.which !== 91) { var table = current[$(this).closest('[data-prov-type]').attr('data-prov-type') + 'Table']; if (table) { table.fnFilter($(this).val()); current.updateUiCost(); } } }); $('input.resource-query').not('[type="number"]').on('change', current.checkResource); $('input.resource-query[type="number"]').on('keyup', function (event) { if (event.which !== 16 && event.which !== 91) { $.proxy(current.checkResource, $(this))(); } }); $(current.types).each(function (_i, type) { current.initializeDataTableEvents(type); if (type !== 'database') { current.initializePopupEvents(type); } }); $('.quote-name').text(current.model.configuration.name); _('popup-prov-update').on('shown.bs.modal', function () { _('quote-name').trigger('focus'); }).on('submit', function (e) { e.preventDefault(); current.updateQuote({ name: _('quote-name').val(), description: _('quote-description').val() }); }).on('show.bs.modal', function () { _('quote-name').val(current.model.configuration.name); _('quote-description').val(current.model.configuration.description || ''); }); $('.cost-refresh').on('click', current.refreshCost); $('#instance-min-quantity, #instance-max-quantity').on('change', current.updateAutoScale); // Related instance of the storage _('storage-instance').select2({ formatSelection: current.formatQuoteInstance, formatResult: current.formatQuoteInstance, placeholder: current.$messages['service:prov:no-attached-instance'], allowClear: true, escapeMarkup: function (m) { return m; }, data: function () { return { results: current.model.configuration.instances }; } }); $('.support-access').select2({ formatSelection: current.formatSupportAccess, formatResult: current.formatSupportAccess, allowClear: true, placeholder: 'None', escapeMarkup: m => m, data: [{ id: 'technical', text: 'technical' }, { id: 'billing', text: 'billing' }, { id: 'all', text: 'all' }] }); _('support-level').select2({ formatSelection: current.formatSupportLevel, formatResult: current.formatSupportLevel, allowClear: true, placeholder: 'None', escapeMarkup: m => m, data: [{ id: 'LOW', text: 'LOW' }, { id: 'MEDIUM', text: 'MEDIUM' }, { id: 'GOOD', text: 'GOOD' }] }); _('instance-os').select2({ formatSelection: current.formatOs, formatResult: current.formatOs, escapeMarkup: m => m, data: [{ id: 'LINUX', text: 'LINUX' }, { id: 'WINDOWS', text: 'WINDOWS' }, { id: 'SUSE', text: 'SUSE' }, { id: 'RHEL', text: 'RHEL' }, { id: 'CENTOS', text: 'CENTOS' }, { id: 'DEBIAN', text: 'DEBIAN' }, { id: 'UBUNTU', text: 'UBUNTU' }, { id: 'FEDORA', text: 'FEDORA' }] }); _('instance-software').select2(current.genericSelect2(current.$messages['service:prov:software-none'], current.defaultToText, function () { return 'instance-software/' + _('instance-os').val(); })); _('database-engine').select2(current.genericSelect2(null, current.formatDatabaseEngine, 'database-engine')); _('database-edition').select2(current.genericSelect2(current.$messages['service:prov:database-edition'], current.defaultToText, function () { return 'database-edition/' + _('database-engine').val(); })); _('instance-internet').select2({ formatSelection: current.formatInternet, formatResult: current.formatInternet, formatResultCssClass: function (data) { if (data.id === 'PRIVATE_NAT' && _('instance-internet').closest('[data-prov-type]').attr('data-prov-type') === 'database') { return 'hidden'; } }, escapeMarkup: m => m, data: [{ id: 'PUBLIC', text: 'PUBLIC' }, { id: 'PRIVATE', text: 'PRIVATE' }, { id: 'PRIVATE_NAT', text: 'PRIVATE_NAT' }] }); _('storage-optimized').select2({ placeholder: current.$messages['service:prov:no-requirement'], allowClear: true, formatSelection: current.formatStorageOptimized, formatResult: current.formatStorageOptimized, escapeMarkup: m => m, data: [{ id: 'THROUGHPUT', text: 'THROUGHPUT' }, { id: 'IOPS', text: 'IOPS' }, { id: 'DURABILITY', text: 'DURABILITY' }] }); _('storage-latency').select2({ placeholder: current.$messages['service:prov:no-requirement'], allowClear: true, formatSelection: current.formatStorageLatency, formatResult: current.formatStorageLatency, escapeMarkup: m => m, data: [{ id: 'BEST', text: 'BEST' }, { id: 'GOOD', text: 'GOOD' }, { id: 'MEDIUM', text: 'MEDIUM' }, { id: 'LOW', text: 'LOW' }, { id: 'WORST', text: 'WORST' }] }); // Memory unit, CPU constant/variable selection _('popup-prov-generic').on('click', '.input-group-btn li', function () { var $select = $(this).closest('.input-group-btn'); $select.find('li.active').removeClass('active'); var $active = $(this).addClass('active').find('a'); $select.find('.btn span:first-child').html($active.find('i').length ? $active.find('i').prop('outerHTML') : $active.html()); // Also trigger the change of the value _('instance-cpu').trigger('keyup'); }); _('instance-term').select2(current.instanceTermSelect2(false)); _('storage-price').on('change', e => current.updateInstanceCompatible(e.added)); current.initializeTerraform(); current.initializeLocation(); current.initializeUsage(); current.initializeLicense(); current.initializeRamAdjustedRate(); }, /** * Configure RAM adjust rate. */ initializeRamAdjustedRate: function () { require(['jquery-ui'], function () { var handle = $('#quote-ram-adjust-handle'); $('#quote-ram-adjust').slider({ min: 50, max: 150, animate: true, step: 5, value: current.model.configuration.ramAdjustedRate, create: function () { handle.text($(this).slider('value') + '%'); }, slide: (_, ui) => handle.text(ui.value + '%'), change: function (event, slider) { current.updateQuote({ ramAdjustedRate: slider.value }, 'ramAdjustedRate', true); } }); }); }, /** * Configure Terraform. */ initializeTerraform: function () { _('prov-terraform-download').attr('href', REST_PATH + 'service/prov/' + current.model.subscription + '/terraform-' + current.model.subscription + '.zip'); _('prov-terraform-status').find('.terraform-logs a').attr('href', REST_PATH + 'service/prov/' + current.model.subscription + '/terraform.log'); _('popup-prov-terraform') .on('shown.bs.modal', () => _('terraform-cidr').trigger('focus')) .on('show.bs.modal', function () { if (_('terraform-key-name').val() === "") { _('terraform-key-name').val(current.$parent.model.pkey); } // Target platform current.updateTerraformTarget(); }).on('submit', current.terraform); _('popup-prov-terraform-destroy') .on('shown.bs.modal', () => _('terraform-confirm-destroy').trigger('focus')) .on('show.bs.modal', function () { current.updateTerraformTarget(); _('terraform-destroy-confirm').val('').trigger('change'); $('.terraform-destroy-alert').html(Handlebars.compile(current.$messages['service:prov:terraform:destroy-alert'])(current.$parent.model.pkey)); }).on('submit', function () { // Delete only when exact match if (_('terraform-destroy-confirm').val() === current.$parent.model.pkey) { current.terraformDestroy(); } }); // Live state ot Terraform destroy buttons _('terraform-destroy-confirm').on('change keyup', function () { if (_('terraform-destroy-confirm').val() === current.$parent.model.pkey) { _('popup-prov-terraform-destroy').find('input[type="submit"]').removeClass('disabled'); } else { _('popup-prov-terraform-destroy').find('input[type="submit"]').addClass('disabled'); } }) // render the dashboard current.$super('requireTool')(current.$parent, current.model.node.id, function ($tool) { var $dashboard = _('prov-terraform-status').find('.terraform-dashboard'); if ($tool && $tool.dashboardLink) { $dashboard.removeClass('hidden').find('a').attr('href', $tool.dashboardLink(current.model)); } else { $dashboard.addClass('hidden'); } }); }, /** * Configure location. */ initializeLocation: function () { _('quote-location').select2(current.locationSelect2(false)).select2('data', current.model.configuration.location).on('change', function (event) { if (event.added) { current.updateQuote({ location: event.added }, 'location'); $('.location-wrapper').html(current.locationMap(event.added)); } }); $('.location-wrapper').html(current.locationMap(current.model.configuration.location)); _('instance-location').select2(current.locationSelect2(current.$messages['service:prov:default'])); _('storage-location').select2(current.locationSelect2(current.$messages['service:prov:default'])); }, /** * Configure usage. */ initializeUsage: function () { _('popup-prov-usage').on('shown.bs.modal', function () { _('usage-name').trigger('focus'); }).on('submit', function (e) { e.preventDefault(); current.saveOrUpdateUsage({ name: _('usage-name').val(), rate: parseInt(_('usage-rate').val() || '100', 10), duration: parseInt(_('usage-duration').val() || '1', 10), start: parseInt(_('usage-start').val() || '0', 10) }, _('usage-old-name').val()); }).on('show.bs.modal', function (event) { current.enableCreate(_('popup-prov-usage')); if ($(event.relatedTarget).is('.btn-success')) { // Create mode _('usage-old-name').val(''); _('usage-name').val(''); _('usage-rate').val(100); _('usage-duration').val(1); _('usage-start').val(0); } else { // Update mode var usage = event.relatedTarget; _('usage-old-name').val(usage.name); _('usage-name').val(usage.name); _('usage-rate').val(usage.rate); _('usage-duration').val(usage.duration); _('usage-start').val(usage.start || 0); } validationManager.reset($(this)); validationManager.mapping.name = 'usage-name'; validationManager.mapping.rate = 'usage-rate'; validationManager.mapping.duration = 'usage-duration'; validationManager.mapping.start = 'usage-start'; _('usage-rate').trigger('change'); }); $('.usage-inputs input').on('change', current.synchronizeUsage); $('.usage-inputs input').on('keyup', current.synchronizeUsage); _('prov-usage-delete').click(() => current.deleteUsage(_('usage-old-name').val())); // Usage rate template var usageTemplates = [ { id: 29, text: moment().day(1).format('dddd') + ' - ' + moment().day(5).format('dddd') + ', 8h30 - 18h30' }, { id: 35, text: moment().day(1).format('dddd') + ' - ' + moment().day(5).format('dddd') + ', 8h00 - 20h00' }, { id: 100, text: current.$messages['service:prov:usage-template-full'] } ]; for (var i = 0; i < usageTemplates.length; i++) { current.usageTemplates[usageTemplates[i].id] = usageTemplates[i]; } _('usage-template').select2({ placeholder: 'Template', allowClear: true, formatSelection: current.formatUsageTemplate, formatResult: current.formatUsageTemplate, escapeMarkup: m => m, data: usageTemplates }); _('instance-usage-upload').select2(current.usageSelect2(current.$messages['service:prov:default'])); _('quote-usage').select2(current.usageSelect2(current.$messages['service:prov:usage-100'])) .select2('data', current.model.configuration.usage) .on('change', function (event) { current.updateQuote({ usage: event.added || null }, 'usage', true); }); var $usageSelect2 = _('quote-usage').data('select2'); if (typeof $usageSelect2.originalSelect === 'undefined') { $usageSelect2.originalSelect = $usageSelect2.onSelect; } $usageSelect2.onSelect = (function (fn) { return function (data, options) { if (options) { var $target = $(options.target).closest('.prov-usage-select2-action'); if ($target.is('.update')) { // Update action _('quote-usage').select2('close'); _('popup-prov-usage').modal('show', data); return; } } return fn.apply(this, arguments); }; })($usageSelect2.originalSelect); _('instance-usage').select2(current.usageSelect2(current.$messages['service:prov:default'])); }, /** * Configure license. */ initializeLicense: function () { _('instance-license').select2(current.genericSelect2(current.$messages['service:prov:default'], current.formatLicense, function () { return _('instance-license').closest('[data-prov-type]').attr('data-prov-type') === 'instance' ? 'instance-license/' + _('instance-os').val() : ('database-license/' + _('database-engine').val()) })); _('quote-license').select2(current.genericSelect2(current.$messages['service:prov:license-included'], current.formatLicense, () => 'instance-license/WINDOWS')) .select2('data', current.model.configuration.license ? { id: current.model.configuration.license, text: current.formatLicense(current.model.configuration.license) } : null) .on('change', function (event) { current.updateQuote({ license: event.added || null }, 'license', true); }); }, formatLicense: function (license) { return license.text || current.$messages['service:prov:license-' + license.toLowerCase()] || license; }, synchronizeUsage: function () { var $input = $(this); var id = $input.attr('id'); var val = $input.val(); var percent; // [1-100] if (val) { val = parseInt(val, 10); if (id === 'usage-month') { percent = val / 7.32; } else if (id === 'usage-week') { percent = val / 1.68; } else if (id === 'usage-day') { percent = val / 0.24; } else if (id === 'usage-template') { percent = _('usage-template').select2('data').id; } else { percent = val; } if (id !== 'usage-day') { _('usage-day').val(Math.ceil(percent * 0.24)); } if (id !== 'usage-month') { _('usage-month').val(Math.ceil(percent * 7.32)); } if (id !== 'usage-week') { _('usage-week').val(Math.ceil(percent * 1.68)); } if (id !== 'usage-rate') { _('usage-rate').val(Math.ceil(percent)); } if (id !== 'usage-template') { _('usage-template').select2('data', current.usageTemplates[Math.ceil(percent)] || current.usageTemplates[Math.ceil(percent - 1)] || null); } current.updateD3UsageRate(percent); } }, /** * Location Select2 configuration. */ locationSelect2: function (placeholder) { return current.genericSelect2(placeholder, current.locationToHtml, 'location', null, current.orderByName, 100); }, /** * Order the array items by their 'text' */ orderByName: function (data) { return data.sort(function (a, b) { a = a.text.toLowerCase(); b = b.text.toLowerCase(); if (a > b) { return 1; } if (a < b) { return -1; } return 0; }); }, /** * Usage Select2 configuration. */ usageSelect2: function (placeholder) { return current.genericSelect2(placeholder, current.usageToText, 'usage', function (usage) { return usage.name + '<span class="select2-usage-summary pull-right"><span class="x-small">(' + usage.rate + '%) </span>' + '<a class="update prov-usage-select2-action"><i data-toggle="tooltip" title="' + current.$messages.update + '" class="fas fa-fw fa-pencil-alt"></i><a></span>'; }); }, /** * Price term Select2 configuration. */ instanceTermSelect2: function () { return current.genericSelect2(current.$messages['service:prov:default'], current.defaultToText, 'instance-price-term'); }, /** * Generic Ajax Select2 configuration. * @param path {string|function} Either a string, either a function returning a relative path suffix to 'service/prov/$subscription/$path' */ genericSelect2: function (placeholder, renderer, path, rendererResult, orderCallback, pageSize) { pageSize = pageSize || 15; return { formatSelection: renderer, formatResult: rendererResult || renderer, escapeMarkup: m => m, allowClear: placeholder !== false, placeholder: placeholder ? placeholder : null, formatSearching: () => current.$messages.loading, ajax: { url: () => REST_PATH + 'service/prov/' + current.model.subscription + '/' + (typeof path === 'function' ? path() : path), dataType: 'json', data: function (term, page) { return { 'search[value]': term, // search term 'q': term, // search term 'rows': pageSize, 'page': page, 'start': (page - 1) * pageSize, 'filters': '{}', 'sidx': 'name', 'length': pageSize, 'columns[0][name]': 'name', 'order[0][column]': 0, 'order[0][dir]': 'asc', 'sord': 'asc' }; }, results: function (data, page) { var result = []; $((typeof data.data === 'undefined') ? data : data.data).each(function (_, item) { if (typeof item === 'string') { item = { id: item, text: renderer(item) }; } else { item.text = renderer(item); } result.push(item); }); if (orderCallback) { orderCallback(result); } return { more: data.recordsFiltered > page * pageSize, results: result }; } } }; }, /** * Interval identifiers for polling */ polling: {}, /** * Stop the timer for polling */ pollStop: function (key) { if (current.polling[key]) { clearInterval(current.polling[key]); } delete current.polling[key]; }, /** * Timer for the polling. */ pollStart: function (key, id, synchronizeFunction) { current.polling[key] = setInterval(function () { synchronizeFunction(key, id); }, 1000); }, /** * Get the new Terraform status. */ synchronizeTerraform: function (key, subscription) { current.pollStop(key); current.polling[key] = '-'; $.ajax({ dataType: 'json', url: REST_PATH + 'service/prov/' + subscription + '/terraform', type: 'GET', success: function (status) { current.updateTerraformStatus(status); if (status.end) { return; } // Continue polling for this Terraform current.pollStart(key, subscription, current.synchronizeTerraform); } }); }, /** * Update the Terraform status. */ updateTerraformStatus: function (status, reset) { if (status.end) { // Stop the polling, update the buttons current.enableTerraform(); } else { current.disableTerraform(); } require(['../main/service/prov/terraform'], function (terraform) { terraform[reset ? 'reset' : 'update'](status, _('prov-terraform-status'), current.$messages); }); }, enableTerraform: function () { _('prov-terraform-execute').enable(); }, disableTerraform: function () { _('prov-terraform-execute').disable(); }, /** * Update the Terraform target data. */ updateTerraformTarget: function () { var target = ['<strong>' + current.$messages.node + '</strong>&nbsp;' + current.$super('toIcon')(current.model.node, null, null, true) + ' ' + current.$super('getNodeName')(current.model.node)]; target.push('<strong>' + current.$messages.project + '</strong>&nbsp;' + current.$parent.model.pkey); $.each(current.model.parameters, function (parameter, value) { target.push('<strong>' + current.$messages[parameter] + '</strong>&nbsp;' + value); }); $('.terraform-target').html(target.join('<br>')); }, /** * Execute the terraform destroy */ terraformDestroy: function () { current.terraformAction(_('popup-prov-terraform-destroy'), {}, 'DELETE'); }, /** * Execute the terraform action. * @param {jQuery} $popup The JQuery popup source to hide on success. * @param {Number} context The Terraform context. * @param {Number} method The REST method. */ terraformAction: function ($popup, context, method) { var subscription = current.model.subscription; current.disableTerraform(); // Complete the Terraform inputs var data = { context: context } $.ajax({ type: method, url: REST_PATH + 'service/prov/' + subscription + '/terraform', dataType: 'json', data: JSON.stringify(data), contentType: 'application/json', success: function () { notifyManager.notify(current.$messages['service:prov:terraform:started']); setTimeout(function () { // Poll the unfinished Terraform current.pollStart('terraform-' + subscription, subscription, current.synchronizeTerraform); }, 10); $popup.modal('hide'); current.updateTerraformStatus({}, true); }, error: () => current.enableTerraform() }); }, /** * Execute the terraform deployment */ terraform: function () { current.terraformAction(_('popup-prov-terraform'), { 'key_name': _('terraform-key-name').val(), 'private_subnets': '"' + $.map(_('terraform-private-subnets').val().split(','), s => s.trim()).join('","') + '"', 'public_subnets': '"' + $.map(_('terraform-public-subnets').val().split(','), s => s.trim()).join('","') + '"', 'public_key': _('terraform-public-key').val(), 'cidr': _('terraform-cidr').val() }, 'POST'); }, /** * Update the auto-scale flag from the provided quantities. */ updateAutoScale: function () { var min = _('instance-min-quantity').val(); min = min && parseInt(min, 10); var max = _('instance-max-quantity').val(); max = max && parseInt(max, 10); if (min && max !== '' && min > max) { max = min; _('instance-max-quantity').val(min); } _('instance-auto-scale').prop('checked', (min !== max)); }, /** * Update the quote's details. If the total cost is updated, the quote will be updated. * @param {object} data The optional data overriding the on from the model. * @param {String} property The optional highlighted updated property name. Used for the feedback UI. * @param {function } forceUpdateUi When true, the UI is always refreshed, even when the cost has not been updated. */ updateQuote: function (data, property, forceUpdateUi) { var conf = current.model.configuration; var $popup = _('popup-prov-update'); current.disableCreate($popup); // Build the new data var jsonData = $.extend({ name: conf.name, description: conf.description, location: conf.location, license: conf.license, ramAdjustedRate: conf.ramAdjustedRate || 100, usage: conf.usage }, data || {}); jsonData.location = jsonData.location.name || jsonData.location; if (jsonData.license) { jsonData.license = jsonData.license.id || jsonData.license; } if (jsonData.usage) { jsonData.usage = jsonData.usage.name; } else { delete jsonData.usage; } // Check the changes if (conf.name === jsonData.name && conf.description === jsonData.description && (conf.location && conf.location.name) === jsonData.location && (conf.usage && conf.usage.name) === jsonData.usage && conf.license === jsonData.license && conf.ramAdjustedRate === jsonData.ramAdjustedRate) { // No change return; } $.ajax({ type: 'PUT', url: REST_PATH + 'service/prov/' + current.model.subscription, dataType: 'json', contentType: 'application/json', data: JSON.stringify(jsonData), beforeSend: () => $('.loader-wrapper').removeClass('hidden'), complete: () => $('.loader-wrapper').addClass('hidden'), success: function (newCost) { // Update the UI $('.quote-name').text(jsonData.name); // Commit to the model conf.name = jsonData.name; conf.description = jsonData.description; conf.location = data.location || conf.location; conf.usage = data.usage || conf.usage; conf.license = jsonData.license; conf.ramAdjustedRate = jsonData.ramAdjustedRate; // UI feedback $popup.modal('hide'); // Handle updated cost if (property) { current.reloadAsNeed(newCost, forceUpdateUi); } else if (forceUpdateUi) { current.updateUiCost(); } }, error: function () { // Restore the old property value if (property) { notifyManager.notifyDanger(Handlebars.compile(current.$messages['service:prov:' + property + '-failed'])(data[property].name)); _('quote-' + property).select2('data', current.model.configuration[property]); } current.enableCreate($popup); } }); }, /** * Delete an usage by its name. * @param {string} name The usage name to delete. */ deleteUsage: function (name) { var conf = current.model.configuration; var $popup = _('popup-prov-usage'); current.disableCreate($popup); $.ajax({ type: 'DELETE', url: REST_PATH + 'service/prov/' + current.model.subscription + '/usage/' + encodeURIComponent(name), dataType: 'json', contentType: 'application/json', success: function (newCost) { // Commit to the model if (conf.usage && conf.usage.name === name) { // Update the usage of the quote delete conf.usage; _('prov-usage').select2('data', null); } // UI feedback notifyManager.notify(Handlebars.compile(current.$messages.deleted)(name)); $popup.modal('hide'); // Handle updated cost current.reloadAsNeed(newCost); }, error: () => current.enableCreate($popup) }); }, /** * Update a quote usage. * @param {string} name The usage data to persist. * @param {string} oldName The optional old name. Required for 'update' mode. * @param {function } forceUpdateUi When true, the UI is always refreshed, even when the cost has not been updated. */ saveOrUpdateUsage: function (data, oldName, forceUpdateUi) { var conf = current.model.configuration; var $popup = _('popup-prov-usage'); current.disableCreate($popup); $.ajax({ type: oldName ? 'PUT' : 'POST', url: REST_PATH + 'service/prov/' + current.model.subscription + '/usage' + (oldName ? '/' + encodeURIComponent(oldName) : ''), dataType: 'json', contentType: 'application/json', data: JSON.stringify(data), success: function (newCost) { // Commit to the model if (conf.usage && conf.usage.name === oldName) { // Update the usage of the quote conf.usage.name = data.name; conf.usage.rate = data.rate; data.id = 0; _('quote-usage').select2('data', data); forceUpdateUi = true; } // UI feedback notifyManager.notify(Handlebars.compile(current.$messages[data.id ? 'updated' : 'created'])(data.name)); $popup.modal('hide'); // Handle updated cost if (newCost.tota) { current.reloadAsNeed(newCost.total, forceUpdateUi); } }, error: () => current.enableCreate($popup) }); }, locationMap: function (location) { if (location.longitude) { // https://www.google.com/maps/place/33%C2%B048'00.0%22S+151%C2%B012'00.0%22E/@-33.8,151.1978113,3z // http://www.google.com/maps/place/49.46800006494457,17.11514008755796/@49.46800006494457,17.11514008755796,17z // html += '<a href="https://maps.google.com/?q=' + location.latitude + ',' + location.longitude + '" target="_blank"><i class="fas fa-location-arrow"></i></a> '; return '<a href="http://www.google.com/maps/place/' + location.latitude + ',' + location.longitude + '/@' + location.latitude + ',' + location.longitude + ',3z" target="_blank"><i class="fas fa-location-arrow"></i></a> '; } else { return ''; } }, /** * Location html renderer. */ locationToHtml: function (location, map, short) { var id = location.name; var subRegion = location.subRegion && (current.$messages[location.subRegion] || location.subRegion); var m49 = location.countryM49 && current.$messages.m49[parseInt(location.countryM49, 10)]; var placement = subRegion || (location.placement && current.$messages[location.placement]) || location.placement; var html = map === true ? current.locationMap(location) : ''; if (location.countryA2) { var a2 = (location.countryA2 === 'UK' ? 'GB' : location.countryA2).toLowerCase(); var tooltip = m49 || id; var img = '<img class="flag-icon prov-location-flag" src="' + current.$path + 'flag-icon-css/flags/4x3/' + a2 + '.svg" alt=""'; if (short === true) { // Only flag tooltip += (placement && placement !== html) ? '<br>Placement: ' + placement : ''; tooltip += '<br>Id: ' + id; return '<u class="details-help" data-toggle="popover" data-content="' + tooltip + '" title="' + location.name + '">' + img + '></u>'; } html += img + ' title="' + location.name + '">'; } html += m49 || id; html += (placement && placement !== html) ? ' <span class="small">(' + placement + ')</span>' : ''; html += (subRegion || m49) ? '<span class="prov-location-api">' + id + '</span>' : id; return html; }, /** * Location text renderer. */ usageToText: function (usage) { return usage.text || (usage.name + '<span class="pull-right">(' + usage.rate + '%)<span>'); }, /** * Price term text renderer. */ defaultToText: function (term) { return term.text || term.name || term; }, /** * Redraw an resource table row from its identifier * @param {String} type Resource type : 'instance', 'storage'. * @param {number|Object} resourceOrId Quote resource or its identifier. */ redrawResource: function (type, resourceOrId) { var id = resourceOrId && (resourceOrId.id || resourceOrId); if (id) { // The instance is valid _('prov-' + type + 's').DataTable().rows((_, data) => data.id === id).invalidate().draw(); } }, storageCommitToModel: function (data, model) { model.size = parseInt(data.size, 10); model.latency = data.latency; model.optimized = data.optimized; // Update the attachment current.attachStorage(model, 'instance', data.quoteInstance); current.attachStorage(model, 'database', data.quoteDatabase); }, supportCommitToModel: function (data, model) { model.seats = parseInt(data.seats, 10); model.level = data.level; model.accessApi = data.accessApi; model.accessPhone = data.accessPhone; model.accessChat = data.accessChat; model.accessEmail = data.accessEmail; }, genericCommitToModel: function (data, model) { model.cpu = parseFloat(data.cpu, 10); model.ram = parseInt(data.ram, 10); model.internet = data.internet; model.minQuantity = parseInt(data.minQuantity, 10); model.maxQuantity = data.maxQuantity ? parseInt(data.maxQuantity, 10) : null; model.constant = data.constant; }, instanceCommitToModel: function (data, model) { current.genericCommitToModel(data, model); model.maxVariableCost = parseFloat(data.maxVariableCost, 10); model.ephemeral = data.ephemeral; model.os = data.os; }, databaseCommitToModel: function (data, model) { current.genericCommitToModel(data, model); model.engine = data.engine; model.edition = data.edition; }, storageUiToData: function (data) { data.size = current.cleanInt(_('storage-size').val()); delete data.quoteInstance; delete data.quoteDatabase; if (_('storage-instance').select2('data')) { if (_('storage-instance').select2('data').type === 'database') { data.quoteDatabase = (_('storage-instance').select2('data') || {}).id; } else { data.quoteInstance = (_('storage-instance').select2('data') || {}).id; } } data.optimized = _('storage-optimized').val(); data.latency = _('storage-latency').val(); data.type = _('storage-price').select2('data').price.type.name; }, supportUiToData: function (data) { data.seats = current.cleanInt(_('support-seats').val()); data.accessApi = (_('support-access-api').select2('data') || {}).id || null; data.accessEmail = (_('support-access-email').select2('data') || {}).id || null; data.accessPhone = (_('support-access-phone').select2('data') || {}).id || null; data.accessChat = (_('support-access-chat').select2('data') || {}).id || null; data.level = (_('support-level').select2('data') || {}).id || null; data.type = _('support-price').select2('data').price.type.name; }, genericUiToData: function (data) { data.cpu = current.cleanFloat(_('instance-cpu').val()); data.ram = current.toQueryValueRam(_('instance-ram').val()); data.internet = _('instance-internet').val().toLowerCase(); data.minQuantity = current.cleanInt(_('instance-min-quantity').val()) || 0; data.maxQuantity = current.cleanInt(_('instance-max-quantity').val()) || null; data.license = _('instance-license').val().toLowerCase() || null; data.constant = current.toQueryValueConstant(_('instance-constant').find('li.active').data('value')); data.price = _('instance-price').select2('data').price.id; }, instanceUiToData: function (data) { current.genericUiToData(data) data.maxVariableCost = current.cleanFloat(_('instance-max-variable-cost').val()); data.ephemeral = _('instance-ephemeral').is(':checked'); data.os = _('instance-os').val().toLowerCase(); data.software = _('instance-software').val().toLowerCase() || null; }, databaseUiToData: function (data) { current.genericUiToData(data) data.engine = _('database-engine').val().toUpperCase(); data.edition = _('database-edition').val().toUpperCase() || null; }, cleanFloat: function (data) { data = current.cleanData(data); return data && parseFloat(data, 10); }, cleanInt: function (data) { data = current.cleanData(data); return data && parseInt(data, 10); }, cleanData: function (data) { return (typeof data === 'string') ? data.replace(',', '.').replace(' ', '') || null : data; }, /** * Fill the popup from the model * @param {string} type, The entity type (instance/storage) * @param {Object} model, the entity corresponding to the quote. */ toUi: function (type, model) { var popupType = (type == 'instance' || type == 'database') ? 'generic' : type; var inputType = (type == 'instance' || type == 'database') ? 'instance' : type; var $popup = _('popup-prov-' + popupType); validationManager.reset($popup); _(inputType + '-name').val(model.name || current.findNewName(current.model.configuration[type + 's'], type)); _(inputType + '-description').val(model.description || ''); _(inputType + '-location').select2('data', model.location || null); _(inputType + '-usage').select2('data', model.usage || null); $popup.attr('data-prov-type', type); current[type + 'ToUi'](model); $.proxy(current.checkResource, $popup)(); }, /** * Fill the instance popup with given entity or default values. * @param {Object} quote, the entity corresponding to the quote. */ genericToUi: function (quote) { current.adaptRamUnit(quote.ram || 2048); _('instance-cpu').val(quote.cpu || 1); _('instance-constant').find('li.active').removeClass('active'); _('instance-min-quantity').val((typeof quote.minQuantity === 'number') ? quote.minQuantity : (quote.id ? 0 : 1)); _('instance-max-quantity').val((typeof quote.maxQuantity === 'number') ? quote.maxQuantity : (quote.id ? '' : 1)); var license = (quote.id && (quote.license || quote.price.license)) || null; _('instance-license').select2('data', license ? { id: license, text: current.formatLicense(license) } : null); if (quote.constant === true) { _('instance-constant').find('li[data-value="constant"]').addClass('active'); } else if (quote.constant === false) { _('instance-constant').find('li[data-value="variable"]').addClass('active'); } else { _('instance-constant').find('li:first-child').addClass('active'); } }, /** * Fill the instance popup with given entity or default values. * @param {Object} quote, the entity corresponding to the quote. */ instanceToUi: function (quote) { current.genericToUi(quote); _('instance-max-variable-cost').val(quote.maxVariableCost || null); _('instance-ephemeral').prop('checked', quote.ephemeral); _('instance-os').select2('data', current.select2IdentityData((quote.id && (quote.os || quote.price.os)) || 'LINUX')); _('instance-internet').select2('data', current.select2IdentityData(quote.internet || 'PUBLIC')); current.updateAutoScale(); current.instanceSetUiPrice(quote); }, /** * Fill the database popup with given entity or default values. * @param {Object} quote, the entity corresponding to the quote. */ databaseToUi: function (quote) { current.genericToUi(quote); _('database-engine').select2('data', current.select2IdentityData(quote.engine || 'MYSQL')); _('database-edition').select2('data', current.select2IdentityData(quote.edition || null)); _('instance-internet').select2('data', current.select2IdentityData(quote.internet || 'PRIVATE')); current.instanceSetUiPrice(quote); }, /** * Fill the support popup with given entity or default values. * @param {Object} quote, the entity corresponding to the quote. */ supportToUi: function (quote) { _('support-seats').val(quote.id ? quote.seats || null : 1); _('support-level').select2('data', current.select2IdentityData(quote.level || null)); // Access types _('support-access-api').select2('data', quote.accessApi || null); _('support-access-email').select2('data', quote.accessEmail || null); _('support-access-phone').select2('data', quote.accessPhone || null); _('support-access-chat').select2('data', quote.accessChat || null); current.supportSetUiPrice(quote); }, /** * Fill the storage popup with given entity. * @param {Object} model, the entity corresponding to the quote. */ storageToUi: function (quote) { _('storage-size').val((quote && quote.size) || '10'); _('storage-latency').select2('data', current.select2IdentityData((quote.latency) || null)); _('storage-optimized').select2('data', current.select2IdentityData((quote.optimized) || null)); _('storage-instance').select2('data', quote.quoteInstance || quote.quoteDatabase || null); current.storageSetUiPrice(quote); }, /** * Auto select the right RAM unit depending on the RAM amount. * @param {int} ram, the RAM value in MB. */ adaptRamUnit: function (ram) { _('instance-ram-unit').find('li.active').removeClass('active'); if (ram && ram >= 1024 && (ram / 1024) % 1 === 0) { // Auto select GB _('instance-ram-unit').find('li:last-child').addClass('active'); _('instance-ram').val(ram / 1024); } else { // Keep MB _('instance-ram-unit').find('li:first-child').addClass('active'); _('instance-ram').val(ram); } _('instance-ram-unit').find('.btn span:first-child').text(_('instance-ram-unit').find('li.active a').text()); }, select2IdentityData: function (id) { return id && { id: id, text: id }; }, /** * Save a storage or an instance in the database from the corresponding popup. Handle the cost delta, update the model, then the UI. * @param {string} type Resource type to save. */ save: function (type) { var popupType = (type == 'instance' || type == 'database') ? 'generic' : type; var inputType = (type == 'instance' || type == 'database') ? 'instance' : type; var $popup = _('popup-prov-' + popupType); // Build the playload for API service var suggest = { price: _(inputType + '-price').select2('data'), usage: _(inputType + '-usage').select2('data'), location: _(inputType + '-location').select2('data') }; var data = { id: current.model.quote.id, name: _(inputType + '-name').val(), description: _(inputType + '-description').val(), location: (suggest.location || {}).name, usage: (suggest.usage || {}).name, subscription: current.model.subscription }; // Complete the data from the UI and backup the price context current[type + 'UiToData'](data); // Trim the data current.$main.trimObject(data); current.disableCreate($popup); $.ajax({ type: data.id ? 'PUT' : 'POST', url: REST_PATH + 'service/prov/' + type, dataType: 'json', contentType: 'application/json', data: JSON.stringify(data), success: function (updatedCost) { current.saveAndUpdateCosts(type, updatedCost, data, suggest.price, suggest.usage, suggest.location); $popup.modal('hide'); }, error: () => current.enableCreate($popup) }); }, /** * Commit to the model the saved data (server side) and update the computed cost. * @param {string} type Resource type to save. * @param {string} updatedCost The new updated cost with identifier, total cost, resource cost and related resources costs. * @param {object} data The original data sent to the back-end. * @param {object} price The last know price suggest replacing the current price. When undefined, the original price is used. * @param {object} usage The last provided usage. * @param {object} location The last provided usage. * @return {object} The updated or created model. */ saveAndUpdateCosts: function (type, updatedCost, data, price, usage, location) { var conf = current.model.configuration; // Update the model var qx = conf[type + 'sById'][updatedCost.id] || { id: updatedCost.id, cost: 0 }; // Common data qx.price = (price || current.model.quote || qx).price; qx.name = data.name; qx.description = data.description; qx.location = location; qx.usage = usage; // Specific data current[type + 'CommitToModel'](data, qx); // With related cost, other UI table need to be updated current.defaultCallback(type, updatedCost, qx); return qx; }, /** * Update the D3 instance types bar chart. * @param {object} usage */ updateInstancesBarChart: function (usage) { require(['d3', '../main/service/prov/lib/stacked'], function (d3, d3Bar) { var numDataItems = usage.timeline.length; var data = []; for (var i = 0; i < numDataItems; i++) { data.push({ date: usage.timeline[i].date, instance: usage.timeline[i].instance, storage: usage.timeline[i].storage, database: usage.timeline[i].database, support: usage.timeline[i].support }); } if (usage.cost) { $("#prov-barchart").removeClass('hidden'); if (typeof current.d3Bar === 'undefined') { current.d3Bar = d3Bar; d3Bar.create("#prov-barchart .prov-barchart-svg", false, parseInt(d3.select('#prov-barchart').style('width')), 150, data, (d, bars) => { // Tooltip of barchart var tooltip = current.$messages['service:prov:date'] + ': ' + d.x; tooltip += '<br/>' + current.$messages['service:prov:total'] + ': ' + current.formatCost(bars.reduce((cost, bar) => cost + bar.height0, 0)); current.types.forEach(type => { var cost = bars.filter(bar => bar.cluster === type); if (cost.length && cost[0].height0) { tooltip += '<br/><span' + (d.cluster === type ? ' class="strong">' : '>') + current.$messages['service:prov:' + type] + ': ' + current.formatCost(cost[0].height0) + '</span>'; } }); return '<span class="tooltip-text">' + tooltip + '</span>'; }, d => { // Hover of barchart -> update sunburst and global cost current.filterDate = d && d['x-index']; current.updateUiCost(); }, (d, bars, clicked) => { // Hover of barchart -> update sunburst and global cost current.fixedDate = clicked && d && d['x-index']; current.updateUiCost(); }, d => current.formatCost(d, null, null, true)); $(window).off('resize.barchart').resize('resize.barchart', () => current.d3Bar.resize(parseInt(d3.select('#prov-barchart').style('width')))); } else { d3Bar.update(data); } } else { $("#prov-barchart").addClass('hidden'); } }); }, /** * Update the total cost of the quote. */ updateUiCost: function () { var conf = current.model.configuration; // Compute the new capacity and costs var usage = current.computeUsage(); // Update the global counts var filtered = usage.cost !== conf.cost.min; if (filtered) { // Filtered cost current.formatCost({ min: usage.cost, max: usage.cost, unbound: usage.unbound > 0 }, $('.cost')); } else { // Full cost current.formatCost(conf.cost, $('.cost')); } if (typeof current.filterDate !== 'number' && typeof current.fixedDate !== 'number') { // Do not update itself current.updateInstancesBarChart(usage); } // Instance summary var $instance = $('.nav-pills [href="#tab-instance"] .prov-resource-counter'); $instance.find('.odo-wrapper').text(usage.instance.nb || 0); $instance.find('.odo-wrapper-unbound').text((usage.instance.min > usage.instance.nb || usage.instance.unbound) ? '+' : ''); var $summary = $('.nav-pills [href="#tab-instance"] .summary> .badge'); if (usage.instance.cpu.available) { $summary.removeClass('hidden'); $summary.filter('.cpu').find('span').text(usage.instance.cpu.available); $summary.filter('.ram').find('span').text(current.formatRam(usage.instance.ram.available).replace('</span>', '').replace('<span class="unit">', '')); if (usage.instance.publicAccess) { $summary.filter('.internet').removeClass('hidden').find('span').text(usage.instance.publicAccess); } else { $summary.filter('.internet').addClass('hidden') } } else { $summary.addClass('hidden'); } // Database summary var $database = $('.nav-pills [href="#tab-database"] .prov-resource-counter'); $database.find('.odo-wrapper').text(usage.database.nb || 0); $database.find('.odo-wrapper-unbound').text((usage.database.min > usage.database.nb || usage.database.unbound) ? '+' : ''); $summary = $('.nav-pills [href="#tab-database"] .summary> .badge'); if (usage.database.cpu.available) { $summary.removeClass('hidden'); $summary.filter('.cpu').find('span').text(usage.database.cpu.available); $summary.filter('.ram').find('span').text(current.formatRam(usage.database.ram.available).replace('</span>', '').replace('<span class="unit">', '')); if (usage.database.publicAccess) { $summary.filter('.internet').removeClass('hidden').find('span').text(usage.database.publicAccess); } else { $summary.filter('.internet').addClass('hidden'); } var $engines = $summary.filter('[data-engine]').addClass('hidden'); Object.keys(usage.database.engines).forEach(engine => $engines.filter('[data-engine="' + engine + '"]').removeClass('hidden').find('span').text(usage.database.engines[engine])); } else { $summary.addClass('hidden'); } // Storage summary var $storage = $('.nav-pills [href="#tab-storage"] .prov-resource-counter'); $storage.find('.odo-wrapper').text(usage.storage.nb || 0); $summary = $('.nav-pills [href="#tab-storage"] .summary> .badge.size'); if (usage.storage.available) { $summary.removeClass('hidden'); $summary.text(current.formatStorage(usage.storage.available)); } else { $summary.addClass('hidden'); } // Support summary $('.nav-pills [href="#tab-support"] .prov-resource-counter').text(usage.support.nb || ''); $summary = $('.nav-pills [href="#tab-support"] .summary'); if (usage.support.first) { $summary.removeClass('hidden').find('.support-first').text(usage.support.first).attr("title", usage.support.first); if (usage.support.more) { $summary.find('.support-more').removeClass('hidden').text(usage.support.more); } else { $summary.find('.support-more').addClass('hidden'); } } else { $summary.addClass('hidden'); } // Update the gauge : reserved / available require(['d3', '../main/service/prov/lib/gauge'], function (d3) { if (typeof current.d3Gauge === 'undefined' && usage.cost) { current.d3Gauge = d3; d3.select('#prov-gauge').call(d3.liquidfillgauge, 1, { textColor: '#FF4444', textVertPosition: 0.6, waveAnimateTime: 600, waveHeight: 0.9, textSize: 1.5, backgroundColor: '#e0e0e0' }); $(function () { current.updateGauge(d3, usage); }); } else { current.updateGauge(d3, usage); } }); // Update the sunburst total resource capacity require(['d3', '../main/service/prov/lib/sunburst'], function (d3, sunburst) { if (usage.cost) { sunburst.init('#prov-sunburst', current.toD3(usage), function (data) { var tooltip; if (data.type === 'latency') { tooltip = 'Latency: ' + current.formatStorageLatency(data.name, true); } else if (data.type === 'os') { tooltip = current.formatOs(data.name, true, ' fa-2x'); } else if (data.type === 'instance') { var instance = conf.instancesById[data.name]; tooltip = 'Name: ' + instance.name + '</br>Type: ' + instance.price.type.name + '</br>OS: ' + current.formatOs(instance.price.os, true) + '</br>Term: ' + instance.price.term.name + '</br>Usage: ' + (instance.usage ? instance.usage.name : ('(default) ' + (conf.usage ? conf.usage.name : '100%'))); } else if (data.type === 'storage') { var storage = conf.storagesById[data.name]; tooltip = 'Name: ' + storage.name + '</br>Type: ' + storage.price.type.name + '</br>Latency: ' + current.formatStorageLatency(storage.price.type.latency, true) + '</br>Optimized: ' + storage.price.type.optimized; } else if (data.type === 'support') { var support = conf.supportsById[data.name]; tooltip = 'Name: ' + support.name + '</br>Type: ' + support.price.type.name; } else if (data.type === 'database') { var database = conf.databasesById[data.name]; tooltip = 'Name: ' + database.name + '</br>Type: ' + database.price.type.name + '</br>Engine: ' + current.formatDatabaseEngine(database.price.engine, true) + (database.price.edition ? '/' + database.price.edition : '') + '</br>Term: ' + database.price.term.name + '</br>Usage: ' + (database.usage ? database.usage.name : ('(default) ' + (conf.usage ? conf.usage.name : '100%'))); } else { tooltip = data.name; } return '<span class="tooltip-text">' + tooltip + '<br/>Cost: ' + current.formatCost(data.size || data.value) + '</span>'; }); _('prov-sunburst').removeClass('hidden'); } else { _('prov-sunburst').addClass('hidden'); } }); }, /** * Update the gauge value depending on the computed usage. */ updateGauge: function (d3, usage) { if (d3.select('#prov-gauge').on('valueChanged') && usage.costNoSupport) { var weightCost = 0; if (usage.instance.cpu.available) { weightCost += usage.instance.cost * 0.8 * usage.instance.cpu.reserved / usage.instance.cpu.available; } if (usage.instance.ram.available) { weightCost += usage.instance.cost * 0.2 * usage.instance.ram.reserved / usage.instance.ram.available; } if (usage.database.cpu.available) { weightCost += usage.database.cost * 0.8 * usage.database.cpu.reserved / usage.database.cpu.available; } if (usage.database.ram.available) { weightCost += usage.database.cost * 0.2 * usage.database.ram.reserved / usage.database.ram.available; } if (usage.storage.available) { weightCost += usage.storage.cost * usage.storage.reserved / usage.storage.available; } _('prov-gauge').removeClass('hidden'); // Weight average of average... d3.select('#prov-gauge').on('valueChanged')(Math.floor(weightCost * 100 / usage.costNoSupport)); } else { $('#prov-gauge').addClass('hidden'); } }, getFilteredData: function (type) { var result = []; if (current[type + 'Table'] && current[type + 'Table'].fnSettings().oPreviousSearch.sSearch) { var data = _('prov-' + type + 's').DataTable().rows({ filter: 'applied' }).data(); for (var index = 0; index < data.length; index++) { result.push(data[index]); } } else { result = current.model.configuration[type + 's'] || {}; } if (type === 'instance' && (typeof current.filterDate === 'number' || typeof current.fixedDate === 'number')) { var usage = (current.model.configuration.usage || {}); var date = typeof current.filterDate === 'number' ? current.filterDate : current.fixedDate; return result.filter(qi => ((qi.usage || usage).start || 0) <= date); } return result; }, /** * Compute the global resource usage of this quote and the available capacity. Only minimal quantities are considered and with minimal to 1. * Maximal quantities is currently ignored. */ computeUsage: function () { var conf = current.model.configuration; var nb = 0; var i, t, qi, cost; // Timeline var timeline = []; var defaultUsage = conf.usage || { rate: 100, start: 0 }; var duration = 36; var date = moment().startOf('month'); for (i = 0; i < 36; i++) { timeline.push({ cost: 0, month: date.month(), year: date.year(), date: date.format('MM/YYYY'), instance: 0, storage: 0, support: 0, database: 0 }); date.add(1, 'months'); } // Instance statistics var publicAccess = 0; var instances = current.getFilteredData('instance'); var ramAvailable = 0; var ramReserved = 0; var cpuAvailable = 0; var cpuReserved = 0; var instanceCost = 0; var ramAdjustedRate = conf.ramAdjustedRate / 100; var minInstances = 0; var maxInstancesUnbound = false; var enabledInstances = {}; for (i = 0; i < instances.length; i++) { qi = instances[i]; cost = qi.cost.min || qi.cost || 0; nb = qi.minQuantity || 1; minInstances += nb; maxInstancesUnbound |= (qi.maxQuantity !== nb); cpuAvailable += qi.price.type.cpu * nb; cpuReserved += qi.cpu * nb; ramAvailable += qi.price.type.ram * nb; ramReserved += (ramAdjustedRate > 1 ? qi.ram * ramAdjustedRate : qi.ram) * nb; instanceCost += cost; publicAccess += (qi.internet === 'public') ? 1 : 0; enabledInstances[qi.id] = true; for (t = (qi.usage || defaultUsage).start || 0; t < duration; t++) { timeline[t].instance += cost; } } for (t = 0; t < duration; t++) { timeline[t].cost += instanceCost; } // Database statistics var publicAccessD = 0; var databases = current.getFilteredData('database'); var ramAvailableD = 0; var ramReservedD = 0; var cpuAvailableD = 0; var cpuReservedD = 0; var instanceCostD = 0; var minInstancesD = 0; var engines = {}; var maxInstancesUnboundD = false; var enabledInstancesD = {}; for (i = 0; i < databases.length; i++) { qi = databases[i]; cost = qi.cost.min || qi.cost || 0; nb = qi.minQuantity || 1; minInstancesD += nb; maxInstancesUnboundD |= (qi.maxQuantity !== nb); cpuAvailableD += qi.price.type.cpu * nb; cpuReservedD += qi.cpu * nb; ramAvailableD += qi.price.type.ram * nb; ramReservedD += (ramAdjustedRate > 1 ? qi.ram * ramAdjustedRate : qi.ram) * nb; instanceCostD += cost; var engine = qi.engine.replace(/AURORA .*/, 'AURORA'); engines[engine] = (engines[engine] || 0) + 1; publicAccessD += (qi.internet === 'public') ? 1 : 0; enabledInstancesD[qi.id] = true; for (t = (qi.usage || defaultUsage).start || 0; t < duration; t++) { timeline[t].database += cost; } } for (t = 0; t < duration; t++) { timeline[t].cost += instanceCostD; } // Storage statistics var storageAvailable = 0; var storageReserved = 0; var storageCost = 0; var storages = current.getFilteredData('storage'); for (i = 0; i < storages.length; i++) { var qs = storages[i]; if (qs.quoteInstance && enabledInstances[qs.quoteInstance.id]) { nb = qs.quoteInstance.minQuantity || 1; } else if (qs.quoteDatabase && enabledInstancesD[qs.quoteDatabase.id]) { nb = qs.quoteDatabase.minQuantity || 1; } else { nb = 1; } storageAvailable += Math.max(qs.size, qs.price.type.minimal) * nb; storageReserved += qs.size * nb; storageCost += qs.cost; } for (t = 0; t < duration; t++) { timeline[t].storage = storageCost; timeline[t].cost += storageCost; } // Support statistics var supportCost = 0; var supports = current.getFilteredData('support'); for (i = 0; i < supports.length; i++) { supportCost += supports[i].cost; } for (t = 0; t < duration; t++) { timeline[t].support = supportCost; timeline[t].cost += supportCost; } return { cost: instanceCost + instanceCostD + storageCost + supportCost, costNoSupport: instanceCost + storageCost, unbound: maxInstancesUnbound || maxInstancesUnboundD, timeline: timeline, instance: { nb: instances.length, min: minInstances, unbound: maxInstancesUnbound, ram: { available: ramAvailable, reserved: ramReserved }, cpu: { available: cpuAvailable, reserved: cpuReserved }, publicAccess: publicAccess, filtered: instances, cost: instanceCost }, database: { nb: databases.length, min: minInstancesD, unbound: maxInstancesUnboundD, ram: { available: ramAvailableD, reserved: ramReservedD }, cpu: { available: cpuAvailableD, reserved: cpuReservedD }, engines: engines, publicAccess: publicAccessD, filtered: databases, cost: instanceCostD }, storage: { nb: storages.length, available: storageAvailable, reserved: storageReserved, filtered: storages, cost: storageCost }, support: { nb: supports.length, filtered: supports, first: supports.length ? supports[0].price.type.name : null, more: supports.length > 1, cost: supportCost } }; }, /** * Update the model to detach a storage from its instance * @param storage The storage model to detach. * @param property The storage property of attachment. */ detachStorage: function (storage, property) { if (storage[property]) { var qis = storage[property].storages || []; for (var i = qis.length; i-- > 0;) { if (qis[i] === storage) { qis.splice(i, 1); break; } } delete storage[property]; } }, /** * Update the model to attach a storage to its resource * @param storage The storage model to attach. * @param type The resource type to attach. * @param resource The resource model or identifier to attach. * @param force When <code>true</code>, the previous resource will not be dettached. */ attachStorage: function (storage, type, resource, force) { if (typeof resource === 'number') { resource = current.model.configuration[type + 'sById'][resource]; } var property = 'quote' + type.charAt(0).toUpperCase() + type.slice(1); if (force !== true && storage[property] === resource) { // Already attached or nothing to attach to the target resource return; } if (force !== true && storage[property]) { // Ddetach the old resource current.detachStorage(storage, property); } // Update the model if (resource) { if ($.isArray(resource.storages)) { resource.storages.push(storage); } else { resource.storages = [storage]; } storage[property] = resource; } }, toD3: function (usage) { var data = { name: current.$messages['service:prov:total'], value: usage.cost, children: [] }; current.storageToD3(data, usage); current.instanceToD3(data, usage); current.databaseToD3(data, usage); current.supportToD3(data, usage); return data; }, instanceToD3: function (data, usage) { var allOss = {}; var instances = usage.instance.filtered; var d3instances = { name: '<i class="fas fa-server fa-2x"></i> ' + current.$messages['service:prov:instances-block'], value: 0, children: [] }; data.children.push(d3instances); for (var i = 0; i < instances.length; i++) { var qi = instances[i]; var oss = allOss[qi.os]; if (typeof oss === 'undefined') { // First OS oss = { name: qi.os, type: 'os', value: 0, children: [] }; allOss[qi.os] = oss; d3instances.children.push(oss); } oss.value += qi.cost; d3instances.value += qi.cost; oss.children.push({ name: qi.id, type: 'instance', size: qi.cost }); } }, databaseToD3: function (data, usage) { var allEngines = {}; var databases = usage.database.filtered; var d3databases = { name: '<i class="fas fa-server fa-2x"></i> ' + current.$messages['service:prov:databases-block'], value: 0, children: [] }; data.children.push(d3databases); for (var i = 0; i < databases.length; i++) { var qi = databases[i]; var engines = allEngines[qi.engine]; if (typeof engines === 'undefined') { // First Engine engines = { name: qi.engine, type: 'engine', value: 0, children: [] }; allEngines[qi.engine] = engines; d3databases.children.push(engines); } engines.value += qi.cost; d3databases.value += qi.cost; engines.children.push({ name: qi.id, type: 'database', size: qi.cost }); } }, storageToD3: function (data, usage) { var storages = usage.storage.filtered; var d3storages = { name: '<i class="far fa-hdd fa-2x"></i> ' + current.$messages['service:prov:storages-block'], value: 0, children: [] }; data.children.push(d3storages); var allOptimizations = {}; for (var i = 0; i < storages.length; i++) { var qs = storages[i]; var optimizations = allOptimizations[qs.price.type.latency]; if (typeof optimizations === 'undefined') { // First optimization optimizations = { name: qs.price.type.latency, type: 'latency', value: 0, children: [] }; allOptimizations[qs.price.type.latency] = optimizations; d3storages.children.push(optimizations); } optimizations.value += qs.cost; d3storages.value += qs.cost; optimizations.children.push({ name: qs.id, type: 'storage', size: qs.cost }); } }, supportToD3: function (data, usage) { var supports = usage.support.filtered; var d3supports = { name: '<i class="fas fa-ambulance fa-2x"></i> ' + current.$messages['service:prov:support-block'], value: 0, children: [] }; data.children.push(d3supports); for (var i = 0; i < supports.length; i++) { var support = supports[i]; d3supports.value += support.cost; d3supports.children.push({ name: support.id, type: 'support', size: support.cost }); } }, /** * Initialize the instance datatables from the whole quote */ instanceNewTable: function () { return current.genericInstanceNewTable('instance', [{ data: 'minQuantity', className: 'hidden-xs', type: 'num', render: current.formatQuantity }, { data: 'os', className: 'truncate', width: '24px', render: current.formatOs }, { data: 'cpu', className: 'truncate', width: '48px', type: 'num', render: current.formatCpu }, { data: 'ram', className: 'truncate', width: '64px', type: 'num', render: current.formatRam }, { data: 'price.term', className: 'hidden-xs hidden-sm price-term', render: current.formatInstanceTerm }, { data: 'price.type', className: 'truncate hidden-xs hidden-sm hidden-md', render: current.formatInstanceType }, { data: 'usage', className: 'hidden-xs hidden-sm usage', render: current.formatUsageTemplate }, { data: 'location', className: 'hidden-xs hidden-sm location', width: '24px', render: current.formatLocation }, { data: null, className: 'truncate hidden-xs hidden-sm', render: current.formatQiStorages }]); }, /** * Initialize the support datatables from the whole quote */ supportNewTable: function () { return { columns: [{ data: 'level', width: '128px', render: current.formatSupportLevel }, { data: 'seats', className: 'hidden-xs', type: 'num', render: current.formatSupportSeats }, { data: 'accessApi', className: 'hidden-xs hidden-sm hidden-md', render: current.formatSupportAccess }, { data: 'accessPhone', className: 'hidden-xs hidden-sm hidden-md', render: current.formatSupportAccess }, { data: 'accessEmail', className: 'hidden-xs hidden-sm hidden-md', render: current.formatSupportAccess }, { data: 'accessChat', className: 'hidden-xs hidden-sm hidden-md', render: current.formatSupportAccess }, { data: 'price.type.name', className: 'truncate' }] }; }, /** * Find a free name within the given namespace. * @param {array} resources The namespace of current resources. * @param {string} prefix The preferred name (if available) and used as prefix when there is collision. * @param {string} increment The current increment number of collision. Will starts from 1 when not specified. * @param {string} resourcesByName The namespace where key is the unique name. */ findNewName: function (resources, prefix, increment, resourcesByName) { if (typeof resourcesByName === 'undefined') { // Build the name based index resourcesByName = {}; resources.forEach(resource => resourcesByName[resource.name] = resource); } if (resourcesByName[prefix]) { increment = increment || 1; if (resourcesByName[prefix + '-' + increment]) { return current.findNewName(resourcesByName, prefix, increment + 1, resourcesByName); } return prefix + '-' + increment; } return prefix; }, /** * Initialize the storage datatables from the whole quote */ storageNewTable: function () { return { columns: [{ data: null, type: 'num', className: 'hidden-xs', render: (_i, mode, data) => current.formatQuantity(null, mode, (data.quoteInstance || data.quoteDatabase)) }, { data: 'size', width: '36px', className: 'truncate', type: 'num', render: current.formatStorage }, { data: 'price.type.latency', className: 'truncate hidden-xs', render: current.formatStorageLatency }, { data: 'price.type.optimized', className: 'truncate hidden-xs', render: current.formatStorageOptimized }, { data: 'price.type', className: 'truncate hidden-xs hidden-sm hidden-md', render: current.formatStorageType }, { data: null, className: 'truncate hidden-xs hidden-sm', render: (_i, mode, data) => (data.quoteInstance || data.quoteDatabase || {}).name }] }; }, /** * Donut of usage * @param {integer} rate The rate percent tage 1-100% */ updateD3UsageRate: function (rate) { require(['d3', '../main/service/prov/lib/donut'], function (d3, donut) { if (current.contextDonut) { donut.update(current.contextDonut, rate); } else { current.contextDonut = donut.create("#usage-chart", rate, 250, 250); } }); }, formatDatabaseEngine(engine, mode, clazz) { var cfg = current.databaseEngines[(engine.id || engine || 'MYSQL').toUpperCase()] || current.databaseEngines.MYSQL; if (mode === 'sort' || mode === 'filter') { return cfg[0]; } clazz = cfg[1] + (typeof clazz === 'string' ? clazz : ''); return '<i class="' + clazz + '" data-toggle="tooltip" title="' + cfg[0] + '"></i> ' + cfg[0]; }, /** * Initialize the database datatables from the whole quote */ databaseNewTable: function () { return current.genericInstanceNewTable('database', [{ data: 'minQuantity', className: 'hidden-xs', type: 'num', render: current.formatQuantity }, { data: 'price.engine', className: 'truncate', render: current.formatDatabaseEngine }, { data: 'price.edition', className: 'truncate' }, { data: 'cpu', className: 'truncate', width: '48px', type: 'num', render: current.formatCpu }, { data: 'ram', className: 'truncate', width: '64px', type: 'num', render: current.formatRam }, { data: 'price.term', className: 'hidden-xs hidden-sm price-term', render: current.formatInstanceTerm }, { data: 'price.type', className: 'truncate hidden-xs hidden-sm hidden-md', render: current.formatInstanceType }, { data: 'usage', className: 'hidden-xs hidden-sm usage', render: current.formatUsageTemplate }, { data: 'location', className: 'hidden-xs hidden-sm location', width: '24px', render: current.formatLocation }, { data: null, className: 'truncate hidden-xs hidden-sm', render: current.formatQiStorages }]); }, /** * Initialize the database datatables from the whole quote */ genericInstanceNewTable: function (type, columns) { return { rowCallback: function (nRow, qi) { $(nRow).find('.storages-tags').select2('destroy').select2({ multiple: true, minimumInputLength: 1, createSearchChoice: () => null, formatInputTooShort: current.$messages['service:prov:storage-select'], formatResult: current.formatStoragePriceHtml, formatSelection: current.formatStorageHtml, ajax: { url: REST_PATH + 'service/prov/' + current.model.subscription + '/storage-lookup?' + type + '=' + qi.id, dataType: 'json', data: function (term) { return { size: $.isNumeric(term) ? parseInt(term, 10) : 1, // search term }; }, results: function (data) { // Completed the requested identifier data.forEach(quote => { quote.id = quote.price.id + '-' + new Date().getMilliseconds(); quote.text = quote.price.type.name; }); return { more: false, results: data }; } } }).select2('data', qi.storages || []).off('change').on('change', function (event) { if (event.added) { // New storage var suggest = event.added; var data = { name: current.findNewName(current.model.configuration.storages, qi.name), type: suggest.price.type.name, size: suggest.size, quoteInstance: type === 'instance' && qi.id, quoteDatabase: type === 'database' && qi.id, subscription: current.model.subscription }; current.$main.trimObject(data); $.ajax({ type: 'POST', url: REST_PATH + 'service/prov/storage', dataType: 'json', contentType: 'application/json', data: JSON.stringify(data), success: function (updatedCost) { current.saveAndUpdateCosts('storage', updatedCost, data, suggest, null, qi.location); // Keep the focus on this UI after the redraw of the row $(function () { _('prov-' + type + 's').find('tr[data-id="' + qi.id + '"]').find('.storages-tags .select2-input').trigger('focus'); }); } }); } else if (event.removed) { // Storage to delete var qs = event.removed.qs || event.removed; $.ajax({ type: 'DELETE', url: REST_PATH + 'service/prov/storage/' + qs.id, success: updatedCost => current.defaultCallback('storage', updatedCost) }); } }); }, columns: columns }; }, /** * Default Ajax callback after a deletion, update or create. This function looks the updated resources (identifiers), the deletd resources and the new updated costs. * @param {string} type The related resource type. * @param {object} updatedCost The new costs details. * @param {object} resource Optional resource to update or create. When null, its a deletion. */ defaultCallback: function (type, updatedCost, resource) { var related = updatedCost.related || {}; var deleted = updatedCost.deleted || {}; var conf = current.model.configuration; var nbCreated = 0; var nbUpdated = 0; var nbDeleted = 0; var createdSample = null; var updatedSample = null; var deletedSample = null; conf.cost = updatedCost.total; // Look the deleted resources Object.keys(deleted).forEach(type => { // For each deleted resource of this type, update the UI and the cost in the model for (var i = deleted[type].length; i-- > 0;) { var deletedR = current.delete(type.toLowerCase(), deleted[type][i], true); if (nbDeleted++ === 0) { deletedSample = deletedR.name; } } }); // Look the updated resources Object.keys(related).forEach(key => { // For each updated resource of this type, update the UI and the cost in the model Object.keys(related[key]).forEach(id => { var relatedType = key.toLowerCase(); var resource = conf[relatedType + 'sById'][id]; var cost = related[key][id]; conf[relatedType + 'Cost'] += cost.min - resource.cost; resource.cost = cost.min; resource.maxCost = cost.max; if (nbUpdated++ === 0) { updatedSample = resource.name; } current.redrawResource(relatedType, id); }); }); // Update the current object if (resource) { resource.cost = updatedCost.cost.min; resource.maxCost = updatedCost.cost.max; if (conf[type + 'sById'][updatedCost.id]) { // Update : Redraw the row nbUpdated++; updatedSample = resource.name; current.redrawResource(type, updatedCost.id); } else { conf[type + 's'].push(resource); conf[type + 'sById'][updatedCost.id] = resource; resource.id = updatedCost.id; nbCreated++; createdSample = resource.name; _('prov-' + type + 's').DataTable().row.add(resource).draw(false); } } else if (updatedCost.id) { // Delete this object nbDeleted++; deletedSample = current.delete(type, updatedCost.id, true).name; } // Notify callback var message = []; if (nbCreated) { message.push(Handlebars.compile(current.$messages['service:prov:created'])({ count: nbCreated, sample: createdSample, more: nbCreated - 1 })); } if (nbUpdated) { message.push(Handlebars.compile(current.$messages['service:prov:updated'])({ count: nbUpdated, sample: updatedSample, more: nbUpdated - 1 })); } if (nbDeleted) { message.push(Handlebars.compile(current.$messages['service:prov:deleted'])({ count: nbDeleted, sample: deletedSample, more: nbDeleted - 1 })); } if (message.length) { notifyManager.notify(message.join('<br>')); } $('.tooltip').remove(); // TODO Generalize current.updateUiCost(); }, /** * Delete a resource. * @param {string} type The resource type. * @param {integer} id The resource identifier. */ delete: function (type, id, draw) { var conf = current.model.configuration; var resources = conf[type + 's']; for (var i = resources.length; i-- > 0;) { var resource = resources[i]; if (resource.id === id) { resources.splice(i, 1); delete conf[type + 'sById'][resource.id]; conf[type + 'Cost'] -= resource.cost; if (type === 'storage') { var qr = resource.quoteInstance || resource.quoteDatabase; if (qr) { // Also redraw the instance var attachedType = resource.quoteInstance ? 'instance' : 'database'; current.detachStorage(resource, 'quote' + attachedType.charAt(0).toUpperCase() + attachedType.slice(1)); if (draw) { current.redrawResource(attachedType, qr.id); } } } var row = _('prov-' + type + 's').DataTable().rows((_, data) => data.id === id).remove(); if (draw) { row.draw(false); } return resource; } } }, }; return current; });
src/main/resources/META-INF/resources/webjars/service/prov/prov.js
/* * Licensed under MIT (https://github.com/ligoj/ligoj/blob/master/LICENSE) */ /*jshint esversion: 6*/ define(function () { var current = { /** * Current quote. */ model: null, /** * Usage rate templates */ usageTemplates: {}, contextDonut: null, /** * Enable resource type. */ types: ['instance', 'storage', 'support', 'database'], /** * Show the members of the given group */ configure: function (subscription) { current.model = subscription; current.cleanup(); $('.loader-wrapper').addClass('hidden'); require(['text!../main/service/prov/menu.html'], function (menu) { _('service-prov-menu').empty().remove(); _('extra-menu').append($(Handlebars.compile(menu)(current.$messages))); current.initOdometer(); current.optimizeModel(); current.initializeForm(); current.initializeUpload(); _('subscribe-configuration-prov').removeClass('hide'); $('.provider').text(current.model.node.name); _('name-prov').val(current.model.configuration.name); var now = moment(); $('.prov-export-instances-inline').attr('href', REST_PATH + 'service/prov/' + subscription.id + '/ligoj-prov-instances-inline-storage-' + subscription.id + '-' + now.format('YYYY-MM-DD') + '.csv'); $('.prov-export-instances-split').attr('href', REST_PATH + 'service/prov/' + subscription.id + '/ligoj-prov-split-' + subscription.id + '-' + now.format('YYYY-MM-DD') + '.csv'); }); }, /** * Cleanup the UI component cache. */ cleanup: function () { delete current.contextDonut; delete current.d3Arc; delete current.d3Gauge; $(current.types).each(function (_i, type) { delete current[type + 'Table']; }); }, unload: function () { // Clean the shared menu _('service-prov-menu').empty().remove(); current.cleanup(); }, /** * Reload the model */ reload: function () { // Clear the table var $instances = _('prov-instances').DataTable(); var $storages = _('prov-storages').DataTable(); $instances.clear().draw(); $storages.clear().draw(); $.ajax({ dataType: 'json', url: REST_PATH + 'subscription/' + current.model.subscription + '/configuration', type: 'GET', success: function (data) { current.model = data; current.optimizeModel(); var configuration = data.configuration; $instances.rows.add(configuration.instances).draw(); $storages.rows.add(configuration.storages).draw(); _('quote-location').select2('data', configuration.location); $('.location-wrapper').html(current.locationMap(configuration.location)); _('quote-usage').select2('data', configuration.usage); _('quote-support').select2('data', configuration.supports); _('quote-license').select2('data', configuration.license ? { id: configuration.license, text: current.formatLicense(configuration.license) } : null); } }); }, /** * Request to refresh the cost and trigger a global update as needed */ refreshCost: function () { $.ajax({ type: 'PUT', url: REST_PATH + 'service/prov/' + current.model.subscription + '/refresh', dataType: 'json', success: current.reloadAsNeed }); }, /** * Reload the whole quote if the new cost is different from the previous one. * @param {object} newCost The new cost. * @param {function} forceUpdateUi When true, the UI is always refreshed, even when the cost has not been updated. */ reloadAsNeed: function (newCost, forceUpdateUi) { var dirty = true; if (newCost.min !== current.model.configuration.cost.min || newCost.max !== current.model.configuration.cost.max) { // The cost has been updated current.model.configuration.cost = newCost; notifyManager.notify(current.$messages['service:prov:refresh-needed']); dirty = false; current.reload(); } else { // The cost still the same notifyManager.notify(current.$messages['service:prov:refresh-no-change']); } if (dirty && forceUpdateUi) { current.updateUiCost(); } }, /** * Render Provisioning management link. */ renderFeatures: function (subscription) { // Add quote configuration link var result = current.$super('renderServiceLink')('calculator', '#/home/project/' + subscription.project + '/subscription/' + subscription.id, 'service:prov:manage'); // Help result += current.$super('renderServiceHelpLink')(subscription.parameters, 'service:prov:help'); return result; }, /** * Display the cost of the quote. */ renderDetailsFeatures: function (subscription) { if (subscription.data.quote && (subscription.data.quote.cost.min || subscription.data.quote.cost.max)) { var price = current.formatCost(subscription.data.quote.cost, null, null, true); return '<span data-toggle="tooltip" title="' + current.$messages['service:prov:cost-title'] + ' : ' + price + '" class="price label label-default">' + price + '</span>'; } }, /** * Render provisioning details : cpu, ram, nbVm, storages. */ renderDetailsKey: function (subscription) { var quote = subscription.data.quote; var resources = []; if (quote.nbInstances) { resources.push('<span class="sub-item">' + current.$super('icon')('server', 'service:prov:nb-instances') + quote.nbInstances + ' VM</span>'); } if (quote.nbDatabases) { resources.push('<span class="sub-item">' + current.$super('icon')('database', 'service:prov:nb-databases') + quote.nbDatabases + ' DB</span>'); } if (quote.nbInstances || quote.nbDatabases) { resources.push('<span class="sub-item">' + current.$super('icon')('bolt', 'service:prov:total-cpu') + quote.totalCpu + ' ' + current.$messages['service:prov:cpu'] + '</span>'); resources.push('<span class="sub-item">' + current.$super('icon')('microchip', 'service:prov:total-ram') + current.formatRam(quote.totalRam) + '</span>'); } if (quote.nbPublicAccess) { resources.push('<span class="sub-item">' + current.$super('icon')('globe', 'service:prov:nb-public-access') + quote.nbPublicAccess + '</span>'); } if (quote.totalStorage) { resources.push('<span class="sub-item">' + current.$super('icon')('fas fa-hdd', 'service:prov:total-storage') + current.formatStorage(quote.totalStorage) + '</span>'); } return current.$super('generateCarousel')(subscription, [ ['name', quote.name], ['service:prov:resources', resources.join(', ')], ['service:prov:location', current.$super('icon')('map-marker-alt', 'service:prov:location') + current.locationToHtml(quote.location, true)] ], 1); }, /** * Format instance type details. */ formatInstanceType: function (name, mode, qi) { var type = qi ? qi.price.type : {}; name = type ? type.name : name; if (mode !== 'display' || (typeof type.id === 'undefined')) { // Use only the name return name; } // Instance type details are available var details = type.description ? type.description.replace(/"/g, '') + '<br>' : ''; details += '<i class=\'fas fa-bolt fa-fw\'></i> '; details += type.cpuRate ? '<i class=\'' + current.rates[type.cpuRate] + '\'></i> ' : ''; if (type.cpu) { details += '#' + type.cpu; details += ' ' + current.formatConstant(type.constant); } else { details += current.$messages['service:prov:instance-custom']; } if (type.ram) { details += '<br><i class=\'fas fa-microchip fa-fw\'></i> '; details += type.ramRate ? '<i class=\'' + current.rates[type.ramRate] + '\'></i> ' : ''; details += current.formatRam(type.ram); } if (type.storageRate) { details += '<br><i class=\'far fa-hdd fa-fw\'></i> '; details += type.ramRate ? '<i class=\'' + current.rates[type.storageRate] + '\'></i>' : ''; // TODO Add instance storage } if (type.networkRate) { details += '<br><i class=\'fas fa-globe fa-fw\'></i> '; details += type.ramRate ? '<i class=\'' + current.rates[type.networkRate] + '\'></i>' : ''; // TODO Add memory type } return '<u class="details-help" data-toggle="popover" title="' + name + '" data-content="' + details + '">' + name + '</u>'; }, formatStorageType: function (name, mode, qs) { var type = qs ? qs.price.type : {}; name = type ? type.name : name; if (mode !== 'display' || (typeof type.id === 'undefined')) { // Use only the name return name; } // Storage type details are available var details = type.description ? type.description.replace(/"/g, '') + '<br>' : ''; details += '<i class=\'far fa-hdd fa-fw\'></i> '; details += formatManager.formatSize((type.minimal || 1) * 1024 * 1024 * 1024, 3) + ' - '; details += type.maximal ? formatManager.formatSize(type.maximal * 1024 * 1024 * 1024, 3) : '∞'; if (type.latency) { details += '<br><i class=\'fas fa-fw fa-stopwatch\'></i> <i class=\'' + current.rates[type.latency] + '\'></i>'; } if (type.iops) { details += '<br><i class=\'' + current.storageOptimized.iops + '\'></i> ' + type.iops + ' IOPS'; } if (type.throughput) { details += '<br><i class=\'' + current.storageOptimized.throughput + '\'></i> ' + type.throughput + ' MB/s'; } if (type.durability9) { var nines = '9'.repeat(type.durability9); nines = type.durability9 < 3 ? '0'.repeat(3 - type.durability9) : nines; details += '<br><i class=\'far fa-fw fa-gem\'></i> ' + nines.substring(0, 2) + '.' + nines.substring(2) + '%'; } if (type.availability) { details += '<br><i class=\'fas fa-fw fa-thumbs-up\'></i> ' + type.availability + '%'; } return '<u class="details-help" data-toggle="popover" title="' + name + '" data-content="' + details + '">' + name + '</u>'; }, /** * Format instance term detail */ formatInstanceTerm: function (name, mode, qi) { var term = qi ? qi.price.term : null; name = term ? term.name : name; if (mode === 'sort' || (term && typeof term.id === 'undefined')) { // Use only the name return name; } // Instance details are available var details = '<i class=\'fas fa-clock\'></i> '; if (term && term.period) { details += term.period + ' months period'; } else { details = 'on demand, hourly (or less) billing period'; } if (qi.price.initialCost) { details += '<br/>Initial cost: $' + qi.price.initialCost; } return '<u class="details-help" data-toggle="popover" title="' + name + '" data-content="' + details + '">' + name + '</u>'; }, /** * Format instance quantity */ formatQuantity: function (quantity, mode, instance) { var min = typeof instance === 'undefined' ? quantity : (instance.minQuantity || 0); if (mode === 'sort' || mode === 'filter' || typeof instance === 'undefined') { return min; } var max = instance.maxQuantity; if (typeof max !== 'number') { return min + '+'; } if (max === min) { return min; } // A range return min + '-' + max; }, /** * Format the constant CPU. */ formatConstant: function (constant) { return current.$messages[constant === true ? 'service:prov:cpu-constant' : 'service:prov:cpu-variable']; }, /** * Format the cost. * @param {number} cost The cost value. May contains "min" and "max" attributes. * @param {String|jQuery} mode Either 'sort' for a raw value, either a JQuery container for advanced format with "odometer". Otherwise will be simple format. * @param {object} obj The optional cost object taking precedence over the cost parameter. May contains "min" and "max" attributes. * @param {boolean} noRichText When true, the cost will be in plain text, no HTML markup. * @return The formated cost. */ formatCost: function (cost, mode, obj, noRichText) { if (mode === 'sort' || mode === 'filter') { return cost; } var formatter = current.formatCostText; var $cost = $(); if (mode instanceof jQuery) { // Odomoter format formatter = current.formatCostOdometer; $cost = mode; } // Computation part obj = (typeof obj === 'undefined' || obj === null) ? cost : obj; if (typeof obj.cost === 'undefined' && typeof obj.min !== 'number') { // Standard cost $cost.find('.cost-min').addClass('hidden'); return formatter(cost, true, $cost, noRichText, cost && cost.unbound); } // A floating cost var min = obj.cost || obj.min || 0; var max = typeof obj.maxCost === 'number' ? obj.maxCost : obj.max; var unbound = (min !== max) || obj.unbound || (cost && cost.unbound) || (obj.minQuantity != obj.maxQuantity); if ((typeof max !== 'number') || max === min) { // Max cost is equal to min cost, no range $cost.find('.cost-min').addClass('hidden'); return formatter(min, true, $cost, noRichText, unbound); } // Max cost, is different, display a range return formatter(min, false, $cost, noRichText) + '-' + formatter(max, true, $cost, noRichText, unbound); }, /** * Configure Odometer components */ initOdometer: function () { var $cost = $('.cost'); var weightUnit = '<span class="cost-weight"></span><span class="cost-unit"></span>'; $cost.append('<span class="cost-min hidden"><span class="odo-wrapper cost-value"></span>' + weightUnit + '<span class="cost-separator">-</span></span>'); $cost.append('<span class="cost-max"><span class="odo-wrapper cost-value"></span>' + weightUnit + '</span>'); require(['../main/service/prov/lib/odometer'], function (Odometer) { // Odometer component current.registerOdometer(Odometer, $('#service-prov-menu').find('.odo-wrapper')); current.updateUiCost(); }); }, registerOdometer: function (Odometer, $container) { $container.each(function () { new Odometer({ el: $(this)[0], theme: 'minimal', duration: 0 }).render(); }); }, formatCostOdometer: function (cost, isMax, $cost, noRichTest, unbound) { if (isMax) { formatManager.formatCost(cost, 3, '$', 'cost-unit', function (value, weight, unit) { var $wrapper = $cost.find('.cost-max'); $wrapper.find('.cost-value').html(value); $wrapper.find('.cost-weight').html(weight + ((cost.unbound || unbound) ? '+' : '')); $wrapper.find('.cost-unit').html(unit); }); } else { formatManager.formatCost(cost, 3, '$', 'cost-unit', function (value, weight, unit) { var $wrapper = $cost.find('.cost-min').removeClass('hidden'); $wrapper.find('.cost-value').html(value); $wrapper.find('.cost-weight').html(weight); $wrapper.find('.cost-unit').html(unit); }); } }, formatCostText: function (cost, isMax, _i, noRichText, unbound) { return formatManager.formatCost(cost, 3, '$', noRichText === true ? '' : 'cost-unit') + (unbound ? '+' : ''); }, /** * Format the memory size. */ formatRam: function (sizeMB, mode, instance) { if (mode === 'sort' || mode === 'filter') { return sizeMB; } if (mode === 'display' && instance) { return current.formatEfficiency(sizeMB, instance.price.type.ram, function (value) { return formatManager.formatSize(value * 1024 * 1024, 3); }); } return formatManager.formatSize(sizeMB * 1024 * 1024, 3); }, /** * Format the memory size. */ formatCpu: function (value, mode, instance) { if (mode === 'display' && instance) { return current.formatEfficiency(value, instance.price.type.cpu); } return value; }, /** * Format the efficiency of a data depending on the rate against the maximum value. * @param value {number} Current value. * @param max {number} Maximal value. * @param formatter {function} Option formatter function of the value. * @returns {string} The value to display containing the rate. */ formatEfficiency: function (value, max, formatter) { var fullClass = null; max = max || value || 1; if (value === 0) { value = max; } else if (max / 2.0 > value) { fullClass = 'far fa-circle text-danger'; } else if (max / 1.65 > value) { fullClass = 'fas fa-adjust fa-rotate-270 text-danger'; } else if (max / 1.5 > value) { fullClass = 'fas fa-adjust fa-rotate-270 text-warning'; } else if (max / 1.3 > value) { fullClass = 'fas fa-circle text-primary'; } else if (max / 1.01 > value) { fullClass = 'fas fa-circle text-success'; } var rate = Math.round(value * 100 / max); return (formatter ? formatter(value) : value) + (fullClass ? '<span class="efficiency pull-right"><i class="' + fullClass + '" data-toggle="tooltip" title="' + Handlebars.compile(current.$messages['service:prov:usage-partial'])((formatter ? [formatter(value), formatter(max), rate] : [value, max, rate])) + '"></i></span>' : ''); }, /** * Format the storage size. */ formatStorage: function (sizeGB, mode, data) { if (mode === 'sort' || mode === 'filter') { return sizeGB; } if (data && data.price.type.minimal > sizeGB) { // Enable efficiency display return current.formatEfficiency(sizeGB, data.price.type.maximal, function (value) { return formatManager.formatSize(value * 1024 * 1024 * 1024, 3); }); } // No efficiency rendering can be done return formatManager.formatSize(sizeGB * 1024 * 1024 * 1024, 3); }, /** * Format the storage size to html markup. * @param {object} qs Quote storage with price, type and size. * @param {boolean} showName When true, the type name is displayed. Default is false. * @return {string} The HTML markup representing the quote storage : type and flags. */ formatStorageHtml: function (qs, showName) { var type = qs.price.type; return (showName === true ? type.name + ' ' : '') + current.formatStorageLatency(type.latency) + (type.optimized ? ' ' + current.formatStorageOptimized(type.optimized) : '') + ' ' + formatManager.formatSize(qs.size * 1024 * 1024 * 1024, 3) + ((qs.size < type.minimal) ? ' (' + formatManager.formatSize(type.minimal * 1024 * 1024 * 1024, 3) + ')' : ''); }, /** * Format the storage price to html markup. * @param {object} qs Quote storage with price, type and size. * @return {string} The HTML markup representing the quote storage : cost, type and flags. */ formatStoragePriceHtml: function (qs) { return current.formatStorageHtml(qs, false) + ' ' + qs.price.type.name + '<span class="pull-right text-small">' + current.formatCost(qs.cost) + '<span class="cost-unit">/m</span></span>'; }, /** * Format an attached storages */ formatQiStorages: function (instance, mode) { // Compute the sum var storages = instance.storages; var sum = 0; if (storages) { storages.forEach(storage => sum += storage.size); } if (mode === 'display') { // Need to build a Select2 tags markup return '<input type="text" class="storages-tags" data-instance="' + instance.id + '" autocomplete="off" name="storages-tags">'; } return sum; }, /** * OS key to markup/label mapping. */ os: { 'linux': ['Linux', 'fab fa-linux fa-fw'], 'windows': ['Windows', 'fab fa-windows fa-fw'], 'suse': ['SUSE', 'icon-suse fa-fw'], 'rhel': ['Red Hat Enterprise', 'icon-redhat fa-fw'], 'centos': ['CentOS', 'icon-centos fa-fw'], 'debian': ['Debian', 'icon-debian fa-fw'], 'fedora': ['Fedora', 'icon-fedora fa-fw'], 'ubuntu': ['Ubuntu', 'icon-ubuntu fa-fw'] }, /** * Engine key to markup/label mapping. */ databaseEngines: { 'MYSQL': ['MySQL', 'icon-mysql'], 'ORACLE': ['Oracle', 'icon-oracle'], 'MARIADB': ['MariaDB', 'icon-mariadb'], 'AURORA MYSQL': ['Aurora MySQL', 'icon-aws'], 'AURORA POSTGRESQL': ['Aurora PostgreSQL', 'icon-aws'], 'POSTGRESQL': ['PostgreSQL', 'icon-postgres'], 'SQL SERVER': ['SQL Server', 'icon-mssql'], }, /** * Internet Access key to markup/label mapping. */ internet: { 'public': ['Public', 'fas fa-globe fa-fw'], 'private': ['Private', 'fas fa-lock fa-fw'], 'private_nat': ['NAT', 'fas fa-low-vision fa-fw'] }, /** * Rate name (identifier) to class mapping. Classes are ditributed across 5 values. */ rates: { 'worst': 'far fa-star text-danger fa-fw', 'low': 'fas fa-star-half text-danger fa-fw', 'medium': 'fas fa-star-half fa-fw', 'good': 'fas fa-star text-primary fa-fw', 'best': 'fas fa-star text-success fa-fw', 'invalid': 'fas fa-ban fa-fw' }, /** * Rate name (identifier) to class mapping. Classes are ditributed across 3 values. */ rates3: { 'low': 'far fa-star-half fa-fw', 'medium': 'far fa-star text-success fa-fw', 'good': 'fas fa-star text-success fa-fw', 'invalid': 'fas fa-ban fa-fw' }, /** * Storage optimized key to markup/label mapping. */ storageOptimized: { 'throughput': 'fas fa-angle-double-right fa-fw', 'durability': 'fas fa-archive fa-fw', 'iops': 'fas fa-bolt fa-fw' }, /** * Support access type key to markup/label mapping. */ supportAccessType: { 'technical': 'fas fa-wrench fa-fw', 'billing': 'fas fa-dollar-sign fa-fw', 'all': 'fas fa-users fa-fw' }, /** * Return the HTML markup from the OS key name. */ formatOs: function (os, mode, clazz) { var cfg = current.os[(os.id || os || 'linux').toLowerCase()] || current.os.linux; if (mode === 'sort' || mode === 'filter') { return cfg[0]; } clazz = cfg[1] + (typeof clazz === 'string' ? clazz : ''); return '<i class="' + clazz + '" data-toggle="tooltip" title="' + cfg[0] + '"></i>' + (mode === 'display' ? '' : ' ' + cfg[0]); }, /** * Return the HTML markup from the Internet privacy key name. */ formatInternet: function (internet, mode, clazz) { var cfg = (internet && current.internet[(internet.id || internet).toLowerCase()]) || current.internet.public || 'public'; if (mode === 'sort') { return cfg[0]; } clazz = cfg[1] + (typeof clazz === 'string' ? clazz : ''); return '<i class="' + clazz + '" data-toggle="tooltip" title="' + cfg[0] + '"></i>' + (mode === 'display' ? '' : ' ' + cfg[0]); }, formatUsageTemplate: function (usage, mode) { if (usage) { // TODO } else { usage = current.model.configuration.usage || { rate: 100, duration: 1, name: '<i>default</i>' }; } if (mode === 'display') { var tooltip = current.$messages.name + ': ' + usage.name; tooltip += '<br>' + current.$messages['service:prov:usage-rate'] + ': ' + (usage.rate || 100) + '%'; tooltip += '<br>' + current.$messages['service:prov:usage-duration'] + ': ' + (usage.duration || 1) + ' month(s)'; tooltip += '<br>' + current.$messages['service:prov:usage-start'] + ': ' + (usage.start || 0) + ' month(s)'; return '<span data-toggle="tooltip" title="' + tooltip + '">' + usage.name + '</span>'; } return usage.text || usage.name; }, formatLocation: function (location, mode, data) { var conf = current.model.configuration; var obj; if (location) { if (location.id) { obj = location; } else { obj = conf.locationsById[location]; } } else if (data.price && data.price.location) { obj = conf.locationsById[data.price.location]; } else if (data.quoteInstance && data.quoteInstance.price.location) { obj = conf.locationsById[data.quoteInstance.price.location]; } else if (data.quoteDatabase && data.quoteDatabase.price.location) { obj = conf.locationsById[data.quoteDatabase.price.location]; } else { obj = current.model.configuration.location; } if (mode === 'display') { return current.locationToHtml(obj, false, true); } return obj ? obj.name : ''; }, /** * Return the HTML markup from the quote instance model. */ formatQuoteInstance: function (quoteInstance) { return quoteInstance.name; }, /** * Return the HTML markup from the support level. */ formatSupportLevel: function (level, mode, clazz) { var id = level ? (level.id || level).toLowerCase() : ''; if (id) { var text = current.$messages['service:prov:support-level-' + id]; clazz = current.rates3[id] + (typeof clazz === 'string' ? clazz : ''); if (mode === 'sort' || mode === 'filter') { return text; } return '<i class="' + clazz + '" data-toggle="tooltip" title="' + text + '"></i>' + (mode ? ' ' + text : ''); } return ''; }, /** * Return the HTML markup from the support seats. */ formatSupportSeats: function (seats, mode) { if (mode === 'sort' || mode === 'filter') { return seats || 0; } return seats ? seats : '∞'; }, /** * Return the HTML markup from the storage latency. */ formatStorageLatency: function (latency, mode, clazz) { var id = latency ? (latency.id || latency).toLowerCase() : 'invalid'; var text = id && current.$messages['service:prov:storage-latency-' + id]; if (mode === 'sort' || mode === 'filter') { return text; } clazz = current.rates[id] + (typeof clazz === 'string' ? clazz : ''); return '<i class="' + clazz + '" data-toggle="tooltip" title="' + text + '"></i>' + (mode ? ' ' + text : ''); }, /** * Return the HTML markup from the storage optimized. */ formatStorageOptimized: function (optimized, withText, clazz) { if (optimized) { var id = (optimized.id || optimized).toLowerCase(); var text = current.$messages['service:prov:storage-optimized-' + id]; clazz = current.storageOptimized[id] + (typeof clazz === 'string' ? clazz : ''); return '<i class="' + clazz + '" data-toggle="tooltip" title="' + text + '"></i>' + (withText ? ' ' + text : ''); } }, /** * Return the HTML markup from the support access type. */ formatSupportAccess: function (type, mode) { if (type) { var id = (type.id || type).toLowerCase(); var text = current.$messages['service:prov:support-access-' + id]; if (mode === 'sort' || mode === 'filter') { return text; } var clazz = current.supportAccessType[id]; return '<i class="' + clazz + '" data-toggle="tooltip" title="' + text + '"></i>' + (mode === 'display' ? '' : (' ' + text)); } }, /** * Associate the storages to the instances */ optimizeModel: function () { var conf = current.model.configuration; var i, qi; // Instances conf.instancesById = {}; conf.instanceCost = 0; var instances = conf.instances; for (i = 0; i < instances.length; i++) { qi = instances[i]; // Optimize id access conf.instancesById[qi.id] = qi; conf.instanceCost += qi.cost; } // Databases conf.databasesById = {}; conf.databaseCost = 0; var databases = conf.databases; for (i = 0; i < databases.length; i++) { qi = databases[i]; // Optimize id access conf.databasesById[qi.id] = qi; conf.databaseCost += qi.cost; } // Storage conf.storagesById = {}; conf.storageCost = 0; var storages = conf.storages; for (i = 0; i < storages.length; i++) { var qs = storages[i]; conf.storageCost += qs.cost; current.attachStorage(qs, 'instance', qs.quoteInstance, true); current.attachStorage(qs, 'database', qs.quoteDatabase, true); // Optimize id access conf.storagesById[qs.id] = qs; } // Locations conf.locationsById = {}; var locations = conf.locations; for (i = 0; i < locations.length; i++) { var loc = locations[i]; // Optimize id access conf.locationsById[loc.name] = loc; } // Support conf.supportsById = {}; conf.supportCost = 0; var supports = conf.supports; for (i = 0; i < supports.length; i++) { var qs2 = supports[i]; // Optimize id access conf.supportsById[qs2.id] = qs2; conf.supportCost += qs2.cost; } current.initializeTerraformStatus(); current.updateUiCost(); }, /** * Refresh the Terraform status embedded in the quote. */ initializeTerraformStatus: function () { if (current.model.configuration.terraformStatus) { current.updateTerraformStatus(current.model.configuration.terraformStatus, true); if (typeof current.model.configuration.terraformStatus.end === 'undefined') { // At least one snapshot is pending: track it setTimeout(function () { // Poll the unfinished snapshot current.pollStart('terraform-' + current.model.subscription, current.model.subscription, current.synchronizeTerraform); }, 10); } } else { _('prov-terraform-status').addClass('invisible'); current.enableTerraform(); } }, /** * Return the query parameter name to use to filter some other inputs. */ toQueryName: function (type, $item) { var id = $item.attr('id'); return id.indexOf(type + '-') === 0 && id.substring((type + '-').length); }, /** * Return the memory query parameter value to use to filter some other inputs. */ toQueryValueRam: function (value) { return (current.cleanInt(value) || 0) * parseInt(_('instance-ram-unit').find('li.active').data('value'), 10); }, /** * Return the constant CPU query parameter value to use to filter some other inputs. */ toQueryValueConstant: function (value) { return value === 'constant' ? true : (value === 'variable' ? false : null); }, /** * Disable the create/update button * @return the related button. */ disableCreate: function ($popup) { return $popup.find('input[type="submit"]').attr('disabled', 'disabled').addClass('disabled'); }, /** * Enable the create/update button * @return the related button. */ enableCreate: function ($popup) { return $popup.find('input[type="submit"]').removeAttr('disabled').removeClass('disabled'); }, /** * Checks there is at least one instance matching to the requirement. * Uses the current "this" jQuery context to get the UI context. */ checkResource: function () { var $form = $(this).closest('[data-prov-type]'); var queries = []; var type = $form.attr('data-prov-type'); var popupType = (type == 'instance' || type == 'database') ? 'generic' : type; var $popup = _('popup-prov-' + popupType); // Build the query $form.find('.resource-query').filter(function () { return $(this).closest('[data-exclusive]').length === 0 || $(this).closest('[data-exclusive]').attr('data-exclusive') === type; }).each(function () { current.addQuery(type, $(this), queries); if (type === 'database') { // Also include the instance inputs current.addQuery('instance', $(this), queries); } }); // Check the availability of this instance for these requirements current.disableCreate($popup); $.ajax({ dataType: 'json', url: REST_PATH + 'service/prov/' + current.model.subscription + '/' + type + '-lookup/?' + queries.join('&'), type: 'GET', success: function (suggest) { current[type + 'SetUiPrice'](suggest); if (suggest && (suggest.price || ($.isArray(suggest) && suggest.length))) { // The resource is valid, enable the create current.enableCreate($popup); } }, error: function () { current.enableCreate($popup); } }); }, addQuery(type, $item, queries) { var value = current.getResourceValue($item); var queryParam = value && current.toQueryName(type, $item); if (queryParam) { value = $item.is('[type="checkbox"]') ? $item.is(':checked') : value; var toValue = current['toQueryValue' + queryParam.capitalize()]; value = toValue ? toValue(value, $item) : value; if (value || value === false) { // Add as query queries.push(queryParam + '=' + encodeURIComponent(value)); } } }, getResourceValue: function ($item) { var value = ''; if ($item.is('.input-group-btn')) { value = $item.find('li.active').data('value'); } else if ($item.prev().is('.select2-container')) { var data = ($item.select2('data') || {}); value = $item.is('.named') ? data.name || (data.data && data.data.name) : (data.id || $item.val()); } else if ($item.is('[type="number"]')) { value = parseInt(current.cleanData($item.val()) || "0", 10); } else if (!$item.is('.select2-container')) { value = current.cleanData($item.val()); } return value; }, /** * Set the current storage price. * @param {object|Array} Quote or prices */ storageSetUiPrice: function (quote) { if (quote && (($.isArray(quote) && quote.length) || quote.price)) { var suggests = quote; if (!$.isArray(quote)) { // Single price suggests = [quote]; } for (var i = 0; i < suggests.length; i++) { suggests[i].id = suggests[i].id || suggests[i].price.id; } var suggest = suggests[0]; _('storage-price').select2('destroy').select2({ data: suggests, formatSelection: current.formatStoragePriceHtml, formatResult: current.formatStoragePriceHtml }).select2('data', suggest); } else { _('storage-price').select2('data', null); } current.updateInstanceCompatible(_('storage-price').select2('data')); }, /** * Depending on the current storage type, enable/disable the instance selection */ updateInstanceCompatible: function (suggest) { if (suggest && suggest.price && suggest.price.type.instanceCompatible === false) { // Disable _('storage-instance').select2('data', null).select2('disable'); _('storage-instance').prev('.select2-container').find('.select2-chosen').text(current.$messages['service:prov:cannot-attach-instance']); } else { // Enable _('storage-instance').select2('enable'); if (_('storage-instance').select2('data') === null) { _('storage-instance').prev('.select2-container').find('.select2-chosen').text(current.$messages['service:prov:no-attached-instance']); } } }, /** * Set the current instance/database price. */ genericSetUiPrice: function (quote) { if (quote && quote.price) { var suggests = [quote]; _('instance-price').select2('destroy').select2({ data: suggests, formatSelection: function (qi) { return qi.price.type.name + ' (' + current.formatCost(qi.cost, null, null, true) + '/m)'; }, formatResult: function (qi) { return qi.price.type.name + ' (' + current.formatCost(qi.cost, null, null, true) + '/m)'; } }).select2('data', quote); _('instance-term').select2('data', quote.price.term).val(quote.price.term.id); } else { _('instance-price').select2('data', null); } }, /** * Set the current instance price. */ instanceSetUiPrice: function (quote) { current.genericSetUiPrice(quote); }, /** * Set the current instance price. */ databaseSetUiPrice: function (quote) { current.genericSetUiPrice(quote); }, /** * Set the current support price. */ supportSetUiPrice: function (quote) { if (quote && (($.isArray(quote) && quote.length) || quote.price)) { var suggests = quote; if (!$.isArray(quote)) { // Single price suggests = [quote]; } for (var i = 0; i < suggests.length; i++) { suggests[i].id = suggests[i].id || suggests[i].price.id; } var suggest = suggests[0]; _('support-price').select2('destroy').select2({ data: suggests, formatSelection: function (qi) { return qi.price.type.name + ' (' + current.formatCost(qi.cost, null, null, true) + '/m)'; }, formatResult: function (qi) { return qi.price.type.name + ' (' + current.formatCost(qi.cost, null, null, true) + '/m)'; } }).select2('data', suggest); } else { _('support-price').select2('data', null); } }, /** * Initialize data tables and popup event : delete and details */ initializeDataTableEvents: function (type) { var oSettings = current[type + 'NewTable'](); var popupType = (type == 'instance' || type == 'database') ? 'generic' : type; var $table = _('prov-' + type + 's'); $.extend(oSettings, { data: current.model.configuration[type + 's'] || [], dom: 'Brt<"row"<"col-xs-6"i><"col-xs-6"p>>', destroy: true, stateSave: true, stateDuration: 0, stateLoadCallback: function (settings, callback) { try { return JSON.parse(localStorage.getItem('service:prov/' + type)); } catch (e) { // Ignore the state error log callback(null); } }, stateLoadParams: function (settings, data) { if (data && data.search && data.search.search) { // Restore the filter input $table.closest('[data-prov-type]').find('.subscribe-configuration-prov-search').val(data.search.search); } }, stateSaveCallback: function (settings, data) { try { localStorage.setItem('service:prov/' + type, JSON.stringify(data)); } catch (e) { // Ignore the state error log } }, searching: true, createdRow: (nRow, data) => $(nRow).attr('data-id', data.id), buttons: [{ extend: 'colvis', postfixButtons: ['colvisRestore'], columns: ':not(.noVis)', columnText: (dt, idx) => dt.settings()[0].aoColumns[idx].sTitle }], columnDefs: [{ targets: 'noVisDefault', visible: false }], language: { buttons: { colvis: '<i class="fas fa-cog"></i>', colvisRestore: current.$messages['restore-visibility'] } }, }); oSettings.columns.splice(0, 0, { data: 'name', className: 'truncate' }); oSettings.columns.push( { data: 'cost', className: 'truncate hidden-xs', render: current.formatCost }, { data: null, width: '32px', orderable: false, render: function () { var links = '<a class="update" data-toggle="modal" data-target="#popup-prov-' + popupType + '"><i class="fas fa-pencil-alt" data-toggle="tooltip" title="' + current.$messages.update + '"></i></a>'; return links + '<a class="delete"><i class="fas fa-trash-alt" data-toggle="tooltip" title="' + current.$messages.delete + '"></i></a>'; } }); var dataTable = $table.dataTable(oSettings); $table.on('click', '.delete', function () { // Delete a single row/item var resource = dataTable.fnGetData($(this).closest('tr')[0]); $.ajax({ type: 'DELETE', url: REST_PATH + 'service/prov/' + type + '/' + resource.id, success: function (updatedCost) { current.defaultCallback(type, updatedCost); } }); }).on('click', '.delete-all', function () { // Delete all items $.ajax({ type: 'DELETE', url: REST_PATH + 'service/prov/' + current.model.subscription + '/' + type, success: function (updatedCost) { current.defaultCallback(type, updatedCost); } }); }); current[type + 'Table'] = dataTable; }, /** * Initialize data tables and popup event : delete and details */ initializePopupEvents: function (type) { // Resource edition pop-up var popupType = (type == 'instance' || type == 'database') ? 'generic' : type; var $popup = _('popup-prov-' + popupType); $popup.on('shown.bs.modal', function () { var inputType = (type == 'instance' || type == 'database') ? 'instance' : type; _(inputType + '-name').trigger('focus'); }).on('submit', function (e) { e.preventDefault(); var dynaType = $(this).closest('[data-prov-type]').attr('data-prov-type'); current.save(dynaType); }).on('show.bs.modal', function (event) { var $source = $(event.relatedTarget); var $tr = $source.closest('tr'); var dynaType = $source.closest('[data-prov-type]').attr('data-prov-type'); var $table = _('prov-' + dynaType + 's'); var quote = ($tr.length && $table.dataTable().fnGetData($tr[0])) || {}; $(this).attr('data-prov-type', dynaType) .find('input[type="submit"]') .removeClass('btn-primary btn-success') .addClass(quote.id ? 'btn-primary' : 'btn-success'); $popup.find('.old-required').removeClass('old-required').attr('required', 'required'); $popup.find('[data-exclusive]').not('[data-exclusive="' + dynaType + '"]').find(':required').addClass('old-required').removeAttr('required'); if (quote.id) { current.enableCreate($popup); } else { current.disableCreate($popup); } current.model.quote = quote; current.toUi(dynaType, quote); }); }, initializeUpload: function () { var $popup = _('popup-prov-instance-import'); _('csv-headers-included').on('change', function () { if ($(this).is(':checked')) { // Useless input headers _('csv-headers').closest('.form-group').addClass('hidden'); } else { _('csv-headers').closest('.form-group').removeClass('hidden'); } }); $popup.on('shown.bs.modal', function () { _('csv-file').trigger('focus'); }).on('show.bs.modal', function () { $('.import-summary').addClass('hidden'); }).on('submit', function (e) { // Avoid useless empty optional inputs _('instance-usage-upload-name').val((_('instance-usage-upload').select2('data') || {}).name || null); _('csv-headers-included').val(_('csv-headers-included').is(':checked') ? 'true' : 'false'); $popup.find('input[type="text"]').not('[readonly]').not('.select2-focusser').not('[disabled]').filter(function () { return $(this).val() === ''; }).attr('disabled', 'disabled').attr('readonly', 'readonly').addClass('temp-disabled').closest('.select2-container').select2('enable', false); $(this).ajaxSubmit({ url: REST_PATH + 'service/prov/' + current.model.subscription + '/upload', type: 'POST', dataType: 'json', beforeSubmit: function () { // Reset the summary current.disableCreate($popup); validationManager.reset($popup); validationManager.mapping.DEFAULT = 'csv-file'; $('.import-summary').html('Processing...'); $('.loader-wrapper').removeClass('hidden'); }, success: function () { $popup.modal('hide'); // Refresh the data current.reload(); }, complete: function () { $('.loader-wrapper').addClass('hidden'); $('.import-summary').html('').addClass('hidden'); // Restore the optional inputs $popup.find('input.temp-disabled').removeAttr('disabled').removeAttr('readonly').removeClass('temp-disabled').closest('.select2-container').select2('enable', true); current.enableCreate($popup); } }); e.preventDefault(); return false; }); }, initializeForm: function () { // Global datatables filter $('.subscribe-configuration-prov-search').on('keyup', function (event) { if (event.which !== 16 && event.which !== 91) { var table = current[$(this).closest('[data-prov-type]').attr('data-prov-type') + 'Table']; if (table) { table.fnFilter($(this).val()); current.updateUiCost(); } } }); $('input.resource-query').not('[type="number"]').on('change', current.checkResource); $('input.resource-query[type="number"]').on('keyup', function (event) { if (event.which !== 16 && event.which !== 91) { $.proxy(current.checkResource, $(this))(); } }); $(current.types).each(function (_i, type) { current.initializeDataTableEvents(type); if (type !== 'database') { current.initializePopupEvents(type); } }); $('.quote-name').text(current.model.configuration.name); _('popup-prov-update').on('shown.bs.modal', function () { _('quote-name').trigger('focus'); }).on('submit', function (e) { e.preventDefault(); current.updateQuote({ name: _('quote-name').val(), description: _('quote-description').val() }); }).on('show.bs.modal', function () { _('quote-name').val(current.model.configuration.name); _('quote-description').val(current.model.configuration.description || ''); }); $('.cost-refresh').on('click', current.refreshCost); $('#instance-min-quantity, #instance-max-quantity').on('change', current.updateAutoScale); // Related instance of the storage _('storage-instance').select2({ formatSelection: current.formatQuoteInstance, formatResult: current.formatQuoteInstance, placeholder: current.$messages['service:prov:no-attached-instance'], allowClear: true, escapeMarkup: function (m) { return m; }, data: function () { return { results: current.model.configuration.instances }; } }); $('.support-access').select2({ formatSelection: current.formatSupportAccess, formatResult: current.formatSupportAccess, allowClear: true, placeholder: 'None', escapeMarkup: m => m, data: [{ id: 'technical', text: 'technical' }, { id: 'billing', text: 'billing' }, { id: 'all', text: 'all' }] }); _('support-level').select2({ formatSelection: current.formatSupportLevel, formatResult: current.formatSupportLevel, allowClear: true, placeholder: 'None', escapeMarkup: m => m, data: [{ id: 'LOW', text: 'LOW' }, { id: 'MEDIUM', text: 'MEDIUM' }, { id: 'GOOD', text: 'GOOD' }] }); _('instance-os').select2({ formatSelection: current.formatOs, formatResult: current.formatOs, escapeMarkup: m => m, data: [{ id: 'LINUX', text: 'LINUX' }, { id: 'WINDOWS', text: 'WINDOWS' }, { id: 'SUSE', text: 'SUSE' }, { id: 'RHEL', text: 'RHEL' }, { id: 'CENTOS', text: 'CENTOS' }, { id: 'DEBIAN', text: 'DEBIAN' }, { id: 'UBUNTU', text: 'UBUNTU' }, { id: 'FEDORA', text: 'FEDORA' }] }); _('instance-software').select2(current.genericSelect2(current.$messages['service:prov:software-none'], current.defaultToText, function () { return 'instance-software/' + _('instance-os').val(); })); _('database-engine').select2(current.genericSelect2(null, current.formatDatabaseEngine, 'database-engine')); _('database-edition').select2(current.genericSelect2(current.$messages['service:prov:database-edition'], current.defaultToText, function () { return 'database-edition/' + _('database-engine').val(); })); _('instance-internet').select2({ formatSelection: current.formatInternet, formatResult: current.formatInternet, escapeMarkup: m => m, data: [{ id: 'PUBLIC', text: 'PUBLIC' }, { id: 'PRIVATE', text: 'PRIVATE' }, { id: 'PRIVATE_NAT', text: 'PRIVATE_NAT' }] }); _('storage-optimized').select2({ placeholder: current.$messages['service:prov:no-requirement'], allowClear: true, formatSelection: current.formatStorageOptimized, formatResult: current.formatStorageOptimized, escapeMarkup: m => m, data: [{ id: 'THROUGHPUT', text: 'THROUGHPUT' }, { id: 'IOPS', text: 'IOPS' }, { id: 'DURABILITY', text: 'DURABILITY' }] }); _('storage-latency').select2({ placeholder: current.$messages['service:prov:no-requirement'], allowClear: true, formatSelection: current.formatStorageLatency, formatResult: current.formatStorageLatency, escapeMarkup: m => m, data: [{ id: 'BEST', text: 'BEST' }, { id: 'GOOD', text: 'GOOD' }, { id: 'MEDIUM', text: 'MEDIUM' }, { id: 'LOW', text: 'LOW' }, { id: 'WORST', text: 'WORST' }] }); // Memory unit, CPU constant/variable selection _('popup-prov-generic').on('click', '.input-group-btn li', function () { var $select = $(this).closest('.input-group-btn'); $select.find('li.active').removeClass('active'); var $active = $(this).addClass('active').find('a'); $select.find('.btn span:first-child').html($active.find('i').length ? $active.find('i').prop('outerHTML') : $active.html()); // Also trigger the change of the value _('instance-cpu').trigger('keyup'); }); _('instance-term').select2(current.instanceTermSelect2(false)); _('storage-price').on('change', e => current.updateInstanceCompatible(e.added)); current.initializeTerraform(); current.initializeLocation(); current.initializeUsage(); current.initializeLicense(); current.initializeRamAdjustedRate(); }, /** * Configure RAM adjust rate. */ initializeRamAdjustedRate: function () { require(['jquery-ui'], function () { var handle = $('#quote-ram-adjust-handle'); $('#quote-ram-adjust').slider({ min: 50, max: 150, animate: true, step: 5, value: current.model.configuration.ramAdjustedRate, create: function () { handle.text($(this).slider('value') + '%'); }, slide: (_, ui) => handle.text(ui.value + '%'), change: function (event, slider) { current.updateQuote({ ramAdjustedRate: slider.value }, 'ramAdjustedRate', true); } }); }); }, /** * Configure Terraform. */ initializeTerraform: function () { _('prov-terraform-download').attr('href', REST_PATH + 'service/prov/' + current.model.subscription + '/terraform-' + current.model.subscription + '.zip'); _('prov-terraform-status').find('.terraform-logs a').attr('href', REST_PATH + 'service/prov/' + current.model.subscription + '/terraform.log'); _('popup-prov-terraform') .on('shown.bs.modal', () => _('terraform-cidr').trigger('focus')) .on('show.bs.modal', function () { if (_('terraform-key-name').val() === "") { _('terraform-key-name').val(current.$parent.model.pkey); } // Target platform current.updateTerraformTarget(); }).on('submit', current.terraform); _('popup-prov-terraform-destroy') .on('shown.bs.modal', () => _('terraform-confirm-destroy').trigger('focus')) .on('show.bs.modal', function () { current.updateTerraformTarget(); _('terraform-destroy-confirm').val('').trigger('change'); $('.terraform-destroy-alert').html(Handlebars.compile(current.$messages['service:prov:terraform:destroy-alert'])(current.$parent.model.pkey)); }).on('submit', function () { // Delete only when exact match if (_('terraform-destroy-confirm').val() === current.$parent.model.pkey) { current.terraformDestroy(); } }); // Live state ot Terraform destroy buttons _('terraform-destroy-confirm').on('change keyup', function () { if (_('terraform-destroy-confirm').val() === current.$parent.model.pkey) { _('popup-prov-terraform-destroy').find('input[type="submit"]').removeClass('disabled'); } else { _('popup-prov-terraform-destroy').find('input[type="submit"]').addClass('disabled'); } }) // render the dashboard current.$super('requireTool')(current.$parent, current.model.node.id, function ($tool) { var $dashboard = _('prov-terraform-status').find('.terraform-dashboard'); if ($tool && $tool.dashboardLink) { $dashboard.removeClass('hidden').find('a').attr('href', $tool.dashboardLink(current.model)); } else { $dashboard.addClass('hidden'); } }); }, /** * Configure location. */ initializeLocation: function () { _('quote-location').select2(current.locationSelect2(false)).select2('data', current.model.configuration.location).on('change', function (event) { if (event.added) { current.updateQuote({ location: event.added }, 'location'); $('.location-wrapper').html(current.locationMap(event.added)); } }); $('.location-wrapper').html(current.locationMap(current.model.configuration.location)); _('instance-location').select2(current.locationSelect2(current.$messages['service:prov:default'])); _('storage-location').select2(current.locationSelect2(current.$messages['service:prov:default'])); }, /** * Configure usage. */ initializeUsage: function () { _('popup-prov-usage').on('shown.bs.modal', function () { _('usage-name').trigger('focus'); }).on('submit', function (e) { e.preventDefault(); current.saveOrUpdateUsage({ name: _('usage-name').val(), rate: parseInt(_('usage-rate').val() || '100', 10), duration: parseInt(_('usage-duration').val() || '1', 10), start: parseInt(_('usage-start').val() || '0', 10) }, _('usage-old-name').val()); }).on('show.bs.modal', function (event) { current.enableCreate(_('popup-prov-usage')); if ($(event.relatedTarget).is('.btn-success')) { // Create mode _('usage-old-name').val(''); _('usage-name').val(''); _('usage-rate').val(100); _('usage-duration').val(1); _('usage-start').val(0); } else { // Update mode var usage = event.relatedTarget; _('usage-old-name').val(usage.name); _('usage-name').val(usage.name); _('usage-rate').val(usage.rate); _('usage-duration').val(usage.duration); _('usage-start').val(usage.start || 0); } validationManager.reset($(this)); validationManager.mapping.name = 'usage-name'; validationManager.mapping.rate = 'usage-rate'; validationManager.mapping.duration = 'usage-duration'; validationManager.mapping.start = 'usage-start'; _('usage-rate').trigger('change'); }); $('.usage-inputs input').on('change', current.synchronizeUsage); $('.usage-inputs input').on('keyup', current.synchronizeUsage); _('prov-usage-delete').click(() => current.deleteUsage(_('usage-old-name').val())); // Usage rate template var usageTemplates = [ { id: 29, text: moment().day(1).format('dddd') + ' - ' + moment().day(5).format('dddd') + ', 8h30 - 18h30' }, { id: 35, text: moment().day(1).format('dddd') + ' - ' + moment().day(5).format('dddd') + ', 8h00 - 20h00' }, { id: 100, text: current.$messages['service:prov:usage-template-full'] } ]; for (var i = 0; i < usageTemplates.length; i++) { current.usageTemplates[usageTemplates[i].id] = usageTemplates[i]; } _('usage-template').select2({ placeholder: 'Template', allowClear: true, formatSelection: current.formatUsageTemplate, formatResult: current.formatUsageTemplate, escapeMarkup: m => m, data: usageTemplates }); _('instance-usage-upload').select2(current.usageSelect2(current.$messages['service:prov:default'])); _('quote-usage').select2(current.usageSelect2(current.$messages['service:prov:usage-100'])) .select2('data', current.model.configuration.usage) .on('change', function (event) { current.updateQuote({ usage: event.added || null }, 'usage', true); }); var $usageSelect2 = _('quote-usage').data('select2'); if (typeof $usageSelect2.originalSelect === 'undefined') { $usageSelect2.originalSelect = $usageSelect2.onSelect; } $usageSelect2.onSelect = (function (fn) { return function (data, options) { if (options) { var $target = $(options.target).closest('.prov-usage-select2-action'); if ($target.is('.update')) { // Update action _('quote-usage').select2('close'); _('popup-prov-usage').modal('show', data); return; } } return fn.apply(this, arguments); }; })($usageSelect2.originalSelect); _('instance-usage').select2(current.usageSelect2(current.$messages['service:prov:default'])); }, /** * Configure license. */ initializeLicense: function () { _('instance-license').select2(current.genericSelect2(current.$messages['service:prov:default'], current.formatLicense, function () { return _('instance-license').closest('[data-prov-type]').attr('data-prov-type') === 'instance' ? 'instance-license/' + _('instance-os').val() : ('database-license/' + _('database-engine').val()) })); _('quote-license').select2(current.genericSelect2(current.$messages['service:prov:license-included'], current.formatLicense, () => 'instance-license/WINDOWS')) .select2('data', current.model.configuration.license ? { id: current.model.configuration.license, text: current.formatLicense(current.model.configuration.license) } : null) .on('change', function (event) { current.updateQuote({ license: event.added || null }, 'license', true); }); }, formatLicense: function (license) { return license.text || current.$messages['service:prov:license-' + license.toLowerCase()] || license; }, synchronizeUsage: function () { var $input = $(this); var id = $input.attr('id'); var val = $input.val(); var percent; // [1-100] if (val) { val = parseInt(val, 10); if (id === 'usage-month') { percent = val / 7.32; } else if (id === 'usage-week') { percent = val / 1.68; } else if (id === 'usage-day') { percent = val / 0.24; } else if (id === 'usage-template') { percent = _('usage-template').select2('data').id; } else { percent = val; } if (id !== 'usage-day') { _('usage-day').val(Math.ceil(percent * 0.24)); } if (id !== 'usage-month') { _('usage-month').val(Math.ceil(percent * 7.32)); } if (id !== 'usage-week') { _('usage-week').val(Math.ceil(percent * 1.68)); } if (id !== 'usage-rate') { _('usage-rate').val(Math.ceil(percent)); } if (id !== 'usage-template') { _('usage-template').select2('data', current.usageTemplates[Math.ceil(percent)] || current.usageTemplates[Math.ceil(percent - 1)] || null); } current.updateD3UsageRate(percent); } }, /** * Location Select2 configuration. */ locationSelect2: function (placeholder) { return current.genericSelect2(placeholder, current.locationToHtml, 'location', null, current.orderByName, 100); }, /** * Order the array items by their 'text' */ orderByName: function (data) { return data.sort(function (a, b) { a = a.text.toLowerCase(); b = b.text.toLowerCase(); if (a > b) { return 1; } if (a < b) { return -1; } return 0; }); }, /** * Usage Select2 configuration. */ usageSelect2: function (placeholder) { return current.genericSelect2(placeholder, current.usageToText, 'usage', function (usage) { return usage.name + '<span class="select2-usage-summary pull-right"><span class="x-small">(' + usage.rate + '%) </span>' + '<a class="update prov-usage-select2-action"><i data-toggle="tooltip" title="' + current.$messages.update + '" class="fas fa-fw fa-pencil-alt"></i><a></span>'; }); }, /** * Price term Select2 configuration. */ instanceTermSelect2: function () { return current.genericSelect2(current.$messages['service:prov:default'], current.defaultToText, 'instance-price-term'); }, /** * Generic Ajax Select2 configuration. * @param path {string|function} Either a string, either a function returning a relative path suffix to 'service/prov/$subscription/$path' */ genericSelect2: function (placeholder, renderer, path, rendererResult, orderCallback, pageSize) { pageSize = pageSize || 15; return { formatSelection: renderer, formatResult: rendererResult || renderer, escapeMarkup: m => m, allowClear: placeholder !== false, placeholder: placeholder ? placeholder : null, formatSearching: () => current.$messages.loading, ajax: { url: () => REST_PATH + 'service/prov/' + current.model.subscription + '/' + (typeof path === 'function' ? path() : path), dataType: 'json', data: function (term, page) { return { 'search[value]': term, // search term 'q': term, // search term 'rows': pageSize, 'page': page, 'start': (page - 1) * pageSize, 'filters': '{}', 'sidx': 'name', 'length': pageSize, 'columns[0][name]': 'name', 'order[0][column]': 0, 'order[0][dir]': 'asc', 'sord': 'asc' }; }, results: function (data, page) { var result = []; $((typeof data.data === 'undefined') ? data : data.data).each(function (_, item) { if (typeof item === 'string') { item = { id: item, text: renderer(item) }; } else { item.text = renderer(item); } result.push(item); }); if (orderCallback) { orderCallback(result); } return { more: data.recordsFiltered > page * pageSize, results: result }; } } }; }, /** * Interval identifiers for polling */ polling: {}, /** * Stop the timer for polling */ pollStop: function (key) { if (current.polling[key]) { clearInterval(current.polling[key]); } delete current.polling[key]; }, /** * Timer for the polling. */ pollStart: function (key, id, synchronizeFunction) { current.polling[key] = setInterval(function () { synchronizeFunction(key, id); }, 1000); }, /** * Get the new Terraform status. */ synchronizeTerraform: function (key, subscription) { current.pollStop(key); current.polling[key] = '-'; $.ajax({ dataType: 'json', url: REST_PATH + 'service/prov/' + subscription + '/terraform', type: 'GET', success: function (status) { current.updateTerraformStatus(status); if (status.end) { return; } // Continue polling for this Terraform current.pollStart(key, subscription, current.synchronizeTerraform); } }); }, /** * Update the Terraform status. */ updateTerraformStatus: function (status, reset) { if (status.end) { // Stop the polling, update the buttons current.enableTerraform(); } else { current.disableTerraform(); } require(['../main/service/prov/terraform'], function (terraform) { terraform[reset ? 'reset' : 'update'](status, _('prov-terraform-status'), current.$messages); }); }, enableTerraform: function () { _('prov-terraform-execute').enable(); }, disableTerraform: function () { _('prov-terraform-execute').disable(); }, /** * Update the Terraform target data. */ updateTerraformTarget: function () { var target = ['<strong>' + current.$messages.node + '</strong>&nbsp;' + current.$super('toIcon')(current.model.node, null, null, true) + ' ' + current.$super('getNodeName')(current.model.node)]; target.push('<strong>' + current.$messages.project + '</strong>&nbsp;' + current.$parent.model.pkey); $.each(current.model.parameters, function (parameter, value) { target.push('<strong>' + current.$messages[parameter] + '</strong>&nbsp;' + value); }); $('.terraform-target').html(target.join('<br>')); }, /** * Execute the terraform destroy */ terraformDestroy: function () { current.terraformAction(_('popup-prov-terraform-destroy'), {}, 'DELETE'); }, /** * Execute the terraform action. * @param {jQuery} $popup The JQuery popup source to hide on success. * @param {Number} context The Terraform context. * @param {Number} method The REST method. */ terraformAction: function ($popup, context, method) { var subscription = current.model.subscription; current.disableTerraform(); // Complete the Terraform inputs var data = { context: context } $.ajax({ type: method, url: REST_PATH + 'service/prov/' + subscription + '/terraform', dataType: 'json', data: JSON.stringify(data), contentType: 'application/json', success: function () { notifyManager.notify(current.$messages['service:prov:terraform:started']); setTimeout(function () { // Poll the unfinished Terraform current.pollStart('terraform-' + subscription, subscription, current.synchronizeTerraform); }, 10); $popup.modal('hide'); current.updateTerraformStatus({}, true); }, error: () => current.enableTerraform() }); }, /** * Execute the terraform deployment */ terraform: function () { current.terraformAction(_('popup-prov-terraform'), { 'key_name': _('terraform-key-name').val(), 'private_subnets': '"' + $.map(_('terraform-private-subnets').val().split(','), s => s.trim()).join('","') + '"', 'public_subnets': '"' + $.map(_('terraform-public-subnets').val().split(','), s => s.trim()).join('","') + '"', 'public_key': _('terraform-public-key').val(), 'cidr': _('terraform-cidr').val() }, 'POST'); }, /** * Update the auto-scale flag from the provided quantities. */ updateAutoScale: function () { var min = _('instance-min-quantity').val(); min = min && parseInt(min, 10); var max = _('instance-max-quantity').val(); max = max && parseInt(max, 10); if (min && max !== '' && min > max) { max = min; _('instance-max-quantity').val(min); } _('instance-auto-scale').prop('checked', (min !== max)); }, /** * Update the quote's details. If the total cost is updated, the quote will be updated. * @param {object} data The optional data overriding the on from the model. * @param {String} property The optional highlighted updated property name. Used for the feedback UI. * @param {function } forceUpdateUi When true, the UI is always refreshed, even when the cost has not been updated. */ updateQuote: function (data, property, forceUpdateUi) { var conf = current.model.configuration; var $popup = _('popup-prov-update'); current.disableCreate($popup); // Build the new data var jsonData = $.extend({ name: conf.name, description: conf.description, location: conf.location, license: conf.license, ramAdjustedRate: conf.ramAdjustedRate || 100, usage: conf.usage }, data || {}); jsonData.location = jsonData.location.name || jsonData.location; if (jsonData.license) { jsonData.license = jsonData.license.id || jsonData.license; } if (jsonData.usage) { jsonData.usage = jsonData.usage.name; } else { delete jsonData.usage; } // Check the changes if (conf.name === jsonData.name && conf.description === jsonData.description && (conf.location && conf.location.name) === jsonData.location && (conf.usage && conf.usage.name) === jsonData.usage && conf.license === jsonData.license && conf.ramAdjustedRate === jsonData.ramAdjustedRate) { // No change return; } $.ajax({ type: 'PUT', url: REST_PATH + 'service/prov/' + current.model.subscription, dataType: 'json', contentType: 'application/json', data: JSON.stringify(jsonData), beforeSend: () => $('.loader-wrapper').removeClass('hidden'), complete: () => $('.loader-wrapper').addClass('hidden'), success: function (newCost) { // Update the UI $('.quote-name').text(jsonData.name); // Commit to the model conf.name = jsonData.name; conf.description = jsonData.description; conf.location = data.location || conf.location; conf.usage = data.usage || conf.usage; conf.license = jsonData.license; conf.ramAdjustedRate = jsonData.ramAdjustedRate; // UI feedback $popup.modal('hide'); // Handle updated cost if (property) { current.reloadAsNeed(newCost, forceUpdateUi); } else if (forceUpdateUi) { current.updateUiCost(); } }, error: function () { // Restore the old property value if (property) { notifyManager.notifyDanger(Handlebars.compile(current.$messages['service:prov:' + property + '-failed'])(data[property].name)); _('quote-' + property).select2('data', current.model.configuration[property]); } current.enableCreate($popup); } }); }, /** * Delete an usage by its name. * @param {string} name The usage name to delete. */ deleteUsage: function (name) { var conf = current.model.configuration; var $popup = _('popup-prov-usage'); current.disableCreate($popup); $.ajax({ type: 'DELETE', url: REST_PATH + 'service/prov/' + current.model.subscription + '/usage/' + encodeURIComponent(name), dataType: 'json', contentType: 'application/json', success: function (newCost) { // Commit to the model if (conf.usage && conf.usage.name === name) { // Update the usage of the quote delete conf.usage; _('prov-usage').select2('data', null); } // UI feedback notifyManager.notify(Handlebars.compile(current.$messages.deleted)(name)); $popup.modal('hide'); // Handle updated cost current.reloadAsNeed(newCost); }, error: () => current.enableCreate($popup) }); }, /** * Update a quote usage. * @param {string} name The usage data to persist. * @param {string} oldName The optional old name. Required for 'update' mode. * @param {function } forceUpdateUi When true, the UI is always refreshed, even when the cost has not been updated. */ saveOrUpdateUsage: function (data, oldName, forceUpdateUi) { var conf = current.model.configuration; var $popup = _('popup-prov-usage'); current.disableCreate($popup); $.ajax({ type: oldName ? 'PUT' : 'POST', url: REST_PATH + 'service/prov/' + current.model.subscription + '/usage' + (oldName ? '/' + encodeURIComponent(oldName) : ''), dataType: 'json', contentType: 'application/json', data: JSON.stringify(data), success: function (newCost) { // Commit to the model if (conf.usage && conf.usage.name === oldName) { // Update the usage of the quote conf.usage.name = data.name; conf.usage.rate = data.rate; data.id = 0; _('quote-usage').select2('data', data); forceUpdateUi = true; } // UI feedback notifyManager.notify(Handlebars.compile(current.$messages[data.id ? 'updated' : 'created'])(data.name)); $popup.modal('hide'); // Handle updated cost if (newCost.tota) { current.reloadAsNeed(newCost.total, forceUpdateUi); } }, error: () => current.enableCreate($popup) }); }, locationMap: function (location) { if (location.longitude) { // https://www.google.com/maps/place/33%C2%B048'00.0%22S+151%C2%B012'00.0%22E/@-33.8,151.1978113,3z // http://www.google.com/maps/place/49.46800006494457,17.11514008755796/@49.46800006494457,17.11514008755796,17z // html += '<a href="https://maps.google.com/?q=' + location.latitude + ',' + location.longitude + '" target="_blank"><i class="fas fa-location-arrow"></i></a> '; return '<a href="http://www.google.com/maps/place/' + location.latitude + ',' + location.longitude + '/@' + location.latitude + ',' + location.longitude + ',3z" target="_blank"><i class="fas fa-location-arrow"></i></a> '; } else { return ''; } }, /** * Location html renderer. */ locationToHtml: function (location, map, short) { var id = location.name; var subRegion = location.subRegion && (current.$messages[location.subRegion] || location.subRegion); var m49 = location.countryM49 && current.$messages.m49[parseInt(location.countryM49, 10)]; var placement = subRegion || (location.placement && current.$messages[location.placement]) || location.placement; var html = map === true ? current.locationMap(location) : ''; if (location.countryA2) { var a2 = (location.countryA2 === 'UK' ? 'GB' : location.countryA2).toLowerCase(); var tooltip = m49 || id; var img = '<img class="flag-icon prov-location-flag" src="' + current.$path + 'flag-icon-css/flags/4x3/' + a2 + '.svg" alt=""'; if (short === true) { // Only flag tooltip += (placement && placement !== html) ? '<br>Placement: ' + placement : ''; tooltip += '<br>Id: ' + id; return '<u class="details-help" data-toggle="popover" data-content="' + tooltip + '" title="' + location.name + '">' + img + '></u>'; } html += img + ' title="' + location.name + '">'; } html += m49 || id; html += (placement && placement !== html) ? ' <span class="small">(' + placement + ')</span>' : ''; html += (subRegion || m49) ? '<span class="prov-location-api">' + id + '</span>' : id; return html; }, /** * Location text renderer. */ usageToText: function (usage) { return usage.text || (usage.name + '<span class="pull-right">(' + usage.rate + '%)<span>'); }, /** * Price term text renderer. */ defaultToText: function (term) { return term.text || term.name || term; }, /** * Redraw an resource table row from its identifier * @param {String} type Resource type : 'instance', 'storage'. * @param {number|Object} resourceOrId Quote resource or its identifier. */ redrawResource: function (type, resourceOrId) { var id = resourceOrId && (resourceOrId.id || resourceOrId); if (id) { // The instance is valid _('prov-' + type + 's').DataTable().rows((_, data) => data.id === id).invalidate().draw(); } }, storageCommitToModel: function (data, model) { model.size = parseInt(data.size, 10); model.latency = data.latency; model.optimized = data.optimized; // Update the attachment current.attachStorage(model, 'instance', data.quoteInstance); current.attachStorage(model, 'database', data.quoteDatabase); }, supportCommitToModel: function (data, model) { model.seats = parseInt(data.seats, 10); model.level = data.level; model.accessApi = data.accessApi; model.accessPhone = data.accessPhone; model.accessChat = data.accessChat; model.accessEmail = data.accessEmail; }, genericCommitToModel: function (data, model) { model.cpu = parseFloat(data.cpu, 10); model.ram = parseInt(data.ram, 10); model.internet = data.internet; model.minQuantity = parseInt(data.minQuantity, 10); model.maxQuantity = data.maxQuantity ? parseInt(data.maxQuantity, 10) : null; model.constant = data.constant; }, instanceCommitToModel: function (data, model) { current.genericCommitToModel(data, model); model.maxVariableCost = parseFloat(data.maxVariableCost, 10); model.ephemeral = data.ephemeral; model.os = data.os; }, databaseCommitToModel: function (data, model) { current.genericCommitToModel(data, model); model.engine = data.engine; model.edition = data.edition; }, storageUiToData: function (data) { data.size = current.cleanInt(_('storage-size').val()); delete data.quoteInstance; delete data.quoteDatabase; if (_('storage-instance').select2('data')) { if (_('storage-instance').select2('data').type === 'database') { data.quoteDatabase = (_('storage-instance').select2('data') || {}).id; } else { data.quoteInstance = (_('storage-instance').select2('data') || {}).id; } } data.optimized = _('storage-optimized').val(); data.latency = _('storage-latency').val(); data.type = _('storage-price').select2('data').price.type.name; }, supportUiToData: function (data) { data.seats = current.cleanInt(_('support-seats').val()); data.accessApi = (_('support-access-api').select2('data') || {}).id || null; data.accessEmail = (_('support-access-email').select2('data') || {}).id || null; data.accessPhone = (_('support-access-phone').select2('data') || {}).id || null; data.accessChat = (_('support-access-chat').select2('data') || {}).id || null; data.level = (_('support-level').select2('data') || {}).id || null; data.type = _('support-price').select2('data').price.type.name; }, genericUiToData: function (data) { data.cpu = current.cleanFloat(_('instance-cpu').val()); data.ram = current.toQueryValueRam(_('instance-ram').val()); data.internet = _('instance-internet').val().toLowerCase(); data.minQuantity = current.cleanInt(_('instance-min-quantity').val()) || 0; data.maxQuantity = current.cleanInt(_('instance-max-quantity').val()) || null; data.license = _('instance-license').val().toLowerCase() || null; data.constant = current.toQueryValueConstant(_('instance-constant').find('li.active').data('value')); data.price = _('instance-price').select2('data').price.id; }, instanceUiToData: function (data) { current.genericUiToData(data) data.maxVariableCost = current.cleanFloat(_('instance-max-variable-cost').val()); data.ephemeral = _('instance-ephemeral').is(':checked'); data.os = _('instance-os').val().toLowerCase(); data.software = _('instance-software').val().toLowerCase() || null; }, databaseUiToData: function (data) { current.genericUiToData(data) data.engine = _('database-engine').val().toUpperCase(); data.edition = _('database-edition').val().toUpperCase() || null; }, cleanFloat: function (data) { data = current.cleanData(data); return data && parseFloat(data, 10); }, cleanInt: function (data) { data = current.cleanData(data); return data && parseInt(data, 10); }, cleanData: function (data) { return (typeof data === 'string') ? data.replace(',', '.').replace(' ', '') || null : data; }, /** * Fill the popup from the model * @param {string} type, The entity type (instance/storage) * @param {Object} model, the entity corresponding to the quote. */ toUi: function (type, model) { var popupType = (type == 'instance' || type == 'database') ? 'generic' : type; var inputType = (type == 'instance' || type == 'database') ? 'instance' : type; var $popup = _('popup-prov-' + popupType); validationManager.reset($popup); _(inputType + '-name').val(model.name || current.findNewName(current.model.configuration[type + 's'], type)); _(inputType + '-description').val(model.description || ''); _(inputType + '-location').select2('data', model.location || null); _(inputType + '-usage').select2('data', model.usage || null); $popup.attr('data-prov-type', type); current[type + 'ToUi'](model); $.proxy(current.checkResource, $popup)(); }, /** * Fill the instance popup with given entity or default values. * @param {Object} quote, the entity corresponding to the quote. */ genericToUi: function (quote) { current.adaptRamUnit(quote.ram || 2048); _('instance-cpu').val(quote.cpu || 1); _('instance-constant').find('li.active').removeClass('active'); _('instance-min-quantity').val((typeof quote.minQuantity === 'number') ? quote.minQuantity : (quote.id ? 0 : 1)); _('instance-max-quantity').val((typeof quote.maxQuantity === 'number') ? quote.maxQuantity : (quote.id ? '' : 1)); var license = (quote.id && (quote.license || quote.price.license)) || null; _('instance-license').select2('data', license ? { id: license, text: current.formatLicense(license) } : null); if (quote.constant === true) { _('instance-constant').find('li[data-value="constant"]').addClass('active'); } else if (quote.constant === false) { _('instance-constant').find('li[data-value="variable"]').addClass('active'); } else { _('instance-constant').find('li:first-child').addClass('active'); } }, /** * Fill the instance popup with given entity or default values. * @param {Object} quote, the entity corresponding to the quote. */ instanceToUi: function (quote) { current.genericToUi(quote); _('instance-max-variable-cost').val(quote.maxVariableCost || null); _('instance-ephemeral').prop('checked', quote.ephemeral); _('instance-os').select2('data', current.select2IdentityData((quote.id && (quote.os || quote.price.os)) || 'LINUX')); _('instance-internet').select2('data', current.select2IdentityData(quote.internet || 'PUBLIC')); current.updateAutoScale(); current.instanceSetUiPrice(quote); }, /** * Fill the database popup with given entity or default values. * @param {Object} quote, the entity corresponding to the quote. */ databaseToUi: function (quote) { current.genericToUi(quote); _('database-engine').select2('data', current.select2IdentityData(quote.engine || 'MYSQL')); _('database-edition').select2('data', current.select2IdentityData(quote.edition || null)); _('instance-internet').select2('data', current.select2IdentityData(quote.internet || 'PRIVATE')); current.instanceSetUiPrice(quote); }, /** * Fill the support popup with given entity or default values. * @param {Object} quote, the entity corresponding to the quote. */ supportToUi: function (quote) { _('support-seats').val(quote.id ? quote.seats || null : 1); _('support-level').select2('data', current.select2IdentityData(quote.level || null)); // Access types _('support-access-api').select2('data', quote.accessApi || null); _('support-access-email').select2('data', quote.accessEmail || null); _('support-access-phone').select2('data', quote.accessPhone || null); _('support-access-chat').select2('data', quote.accessChat || null); current.supportSetUiPrice(quote); }, /** * Fill the storage popup with given entity. * @param {Object} model, the entity corresponding to the quote. */ storageToUi: function (quote) { _('storage-size').val((quote && quote.size) || '10'); _('storage-latency').select2('data', current.select2IdentityData((quote.latency) || null)); _('storage-optimized').select2('data', current.select2IdentityData((quote.optimized) || null)); _('storage-instance').select2('data', quote.quoteInstance || quote.quoteDatabase || null); current.storageSetUiPrice(quote); }, /** * Auto select the right RAM unit depending on the RAM amount. * @param {int} ram, the RAM value in MB. */ adaptRamUnit: function (ram) { _('instance-ram-unit').find('li.active').removeClass('active'); if (ram && ram >= 1024 && (ram / 1024) % 1 === 0) { // Auto select GB _('instance-ram-unit').find('li:last-child').addClass('active'); _('instance-ram').val(ram / 1024); } else { // Keep MB _('instance-ram-unit').find('li:first-child').addClass('active'); _('instance-ram').val(ram); } _('instance-ram-unit').find('.btn span:first-child').text(_('instance-ram-unit').find('li.active a').text()); }, select2IdentityData: function (id) { return id && { id: id, text: id }; }, /** * Save a storage or an instance in the database from the corresponding popup. Handle the cost delta, update the model, then the UI. * @param {string} type Resource type to save. */ save: function (type) { var popupType = (type == 'instance' || type == 'database') ? 'generic' : type; var inputType = (type == 'instance' || type == 'database') ? 'instance' : type; var $popup = _('popup-prov-' + popupType); // Build the playload for API service var suggest = { price: _(inputType + '-price').select2('data'), usage: _(inputType + '-usage').select2('data'), location: _(inputType + '-location').select2('data') }; var data = { id: current.model.quote.id, name: _(inputType + '-name').val(), description: _(inputType + '-description').val(), location: (suggest.location || {}).name, usage: (suggest.usage || {}).name, subscription: current.model.subscription }; // Complete the data from the UI and backup the price context current[type + 'UiToData'](data); // Trim the data current.$main.trimObject(data); current.disableCreate($popup); $.ajax({ type: data.id ? 'PUT' : 'POST', url: REST_PATH + 'service/prov/' + type, dataType: 'json', contentType: 'application/json', data: JSON.stringify(data), success: function (updatedCost) { current.saveAndUpdateCosts(type, updatedCost, data, suggest.price, suggest.usage, suggest.location); $popup.modal('hide'); }, error: () => current.enableCreate($popup) }); }, /** * Commit to the model the saved data (server side) and update the computed cost. * @param {string} type Resource type to save. * @param {string} updatedCost The new updated cost with identifier, total cost, resource cost and related resources costs. * @param {object} data The original data sent to the back-end. * @param {object} price The last know price suggest replacing the current price. When undefined, the original price is used. * @param {object} usage The last provided usage. * @param {object} location The last provided usage. * @return {object} The updated or created model. */ saveAndUpdateCosts: function (type, updatedCost, data, price, usage, location) { var conf = current.model.configuration; // Update the model var qx = conf[type + 'sById'][updatedCost.id] || { id: updatedCost.id, cost: 0 }; // Common data qx.price = (price || current.model.quote || qx).price; qx.name = data.name; qx.description = data.description; qx.location = location; qx.usage = usage; // Specific data current[type + 'CommitToModel'](data, qx); // With related cost, other UI table need to be updated current.defaultCallback(type, updatedCost, qx); return qx; }, /** * Update the D3 instance types bar chart. * @param {object} usage */ updateInstancesBarChart: function (usage) { require(['d3', '../main/service/prov/lib/stacked'], function (d3, d3Bar) { var numDataItems = usage.timeline.length; var data = []; for (var i = 0; i < numDataItems; i++) { data.push({ date: usage.timeline[i].date, instance: usage.timeline[i].instance, storage: usage.timeline[i].storage, database: usage.timeline[i].database, support: usage.timeline[i].support }); } if (usage.cost) { $("#prov-barchart").removeClass('hidden'); if (typeof current.d3Bar === 'undefined') { current.d3Bar = d3Bar; d3Bar.create("#prov-barchart .prov-barchart-svg", false, parseInt(d3.select('#prov-barchart').style('width')), 150, data, (d, bars) => { // Tooltip of barchart var tooltip = current.$messages['service:prov:date'] + ': ' + d.x; tooltip += '<br/>' + current.$messages['service:prov:total'] + ': ' + current.formatCost(bars.reduce((cost, bar) => cost + bar.height0, 0)); current.types.forEach(type => { var cost = bars.filter(bar => bar.cluster === type); if (cost.length && cost[0].height0) { tooltip += '<br/><span' + (d.cluster === type ? ' class="strong">' : '>') + current.$messages['service:prov:' + type] + ': ' + current.formatCost(cost[0].height0) + '</span>'; } }); return '<span class="tooltip-text">' + tooltip + '</span>'; }, d => { // Hover of barchart -> update sunburst and global cost current.filterDate = d && d['x-index']; current.updateUiCost(); }, (d, bars, clicked) => { // Hover of barchart -> update sunburst and global cost current.fixedDate = clicked && d && d['x-index']; current.updateUiCost(); }, d => current.formatCost(d, null, null, true)); $(window).off('resize.barchart').resize('resize.barchart', () => current.d3Bar.resize(parseInt(d3.select('#prov-barchart').style('width')))); } else { d3Bar.update(data); } } else { $("#prov-barchart").addClass('hidden'); } }); }, /** * Update the total cost of the quote. */ updateUiCost: function () { var conf = current.model.configuration; // Compute the new capacity and costs var usage = current.computeUsage(); // Update the global counts var filtered = usage.cost !== conf.cost.min; if (filtered) { // Filtered cost current.formatCost({ min: usage.cost, max: usage.cost, unbound: usage.unbound > 0 }, $('.cost')); } else { // Full cost current.formatCost(conf.cost, $('.cost')); } if (typeof current.filterDate !== 'number' && typeof current.fixedDate !== 'number') { // Do not update itself current.updateInstancesBarChart(usage); } // Instance summary var $instance = $('.nav-pills [href="#tab-instance"] .prov-resource-counter'); $instance.find('.odo-wrapper').text(usage.instance.nb || 0); $instance.find('.odo-wrapper-unbound').text((usage.instance.min > usage.instance.nb || usage.instance.unbound) ? '+' : ''); var $summary = $('.nav-pills [href="#tab-instance"] .summary> .badge'); if (usage.instance.cpu.available) { $summary.removeClass('hidden'); $summary.filter('.cpu').find('span').text(usage.instance.cpu.available); $summary.filter('.ram').find('span').text(current.formatRam(usage.instance.ram.available).replace('</span>', '').replace('<span class="unit">', '')); if (usage.instance.publicAccess) { $summary.filter('.internet').removeClass('hidden').find('span').text(usage.instance.publicAccess); } else { $summary.filter('.internet').addClass('hidden') } } else { $summary.addClass('hidden'); } // Database summary var $database = $('.nav-pills [href="#tab-database"] .prov-resource-counter'); $database.find('.odo-wrapper').text(usage.database.nb || 0); $database.find('.odo-wrapper-unbound').text((usage.database.min > usage.database.nb || usage.database.unbound) ? '+' : ''); $summary = $('.nav-pills [href="#tab-database"] .summary> .badge'); if (usage.database.cpu.available) { $summary.removeClass('hidden'); $summary.filter('.cpu').find('span').text(usage.database.cpu.available); $summary.filter('.ram').find('span').text(current.formatRam(usage.database.ram.available).replace('</span>', '').replace('<span class="unit">', '')); if (usage.database.publicAccess) { $summary.filter('.internet').removeClass('hidden').find('span').text(usage.database.publicAccess); } else { $summary.filter('.internet').addClass('hidden'); } var $engines = $summary.filter('[data-engine]').addClass('hidden'); Object.keys(usage.database.engines).forEach(engine => $engines.filter('[data-engine="' + engine + '"]').removeClass('hidden').find('span').text(usage.database.engines[engine])); } else { $summary.addClass('hidden'); } // Storage summary var $storage = $('.nav-pills [href="#tab-storage"] .prov-resource-counter'); $storage.find('.odo-wrapper').text(usage.storage.nb || 0); $summary = $('.nav-pills [href="#tab-storage"] .summary> .badge.size'); if (usage.storage.available) { $summary.removeClass('hidden'); $summary.text(current.formatStorage(usage.storage.available)); } else { $summary.addClass('hidden'); } // Support summary $('.nav-pills [href="#tab-support"] .prov-resource-counter').text(usage.support.nb || ''); $summary = $('.nav-pills [href="#tab-support"] .summary'); if (usage.support.first) { $summary.removeClass('hidden').find('.support-first').text(usage.support.first).attr("title", usage.support.first); if (usage.support.more) { $summary.find('.support-more').removeClass('hidden').text(usage.support.more); } else { $summary.find('.support-more').addClass('hidden'); } } else { $summary.addClass('hidden'); } // Update the gauge : reserved / available require(['d3', '../main/service/prov/lib/gauge'], function (d3) { if (typeof current.d3Gauge === 'undefined' && usage.cost) { current.d3Gauge = d3; d3.select('#prov-gauge').call(d3.liquidfillgauge, 1, { textColor: '#FF4444', textVertPosition: 0.6, waveAnimateTime: 600, waveHeight: 0.9, textSize: 1.5, backgroundColor: '#e0e0e0' }); $(function () { current.updateGauge(d3, usage); }); } else { current.updateGauge(d3, usage); } }); // Update the sunburst total resource capacity require(['d3', '../main/service/prov/lib/sunburst'], function (d3, sunburst) { if (usage.cost) { sunburst.init('#prov-sunburst', current.toD3(usage), function (data) { var tooltip; if (data.type === 'latency') { tooltip = 'Latency: ' + current.formatStorageLatency(data.name, true); } else if (data.type === 'os') { tooltip = current.formatOs(data.name, true, ' fa-2x'); } else if (data.type === 'instance') { var instance = conf.instancesById[data.name]; tooltip = 'Name: ' + instance.name + '</br>Type: ' + instance.price.type.name + '</br>OS: ' + current.formatOs(instance.price.os, true) + '</br>Term: ' + instance.price.term.name + '</br>Usage: ' + (instance.usage ? instance.usage.name : ('(default) ' + (conf.usage ? conf.usage.name : '100%'))); } else if (data.type === 'storage') { var storage = conf.storagesById[data.name]; tooltip = 'Name: ' + storage.name + '</br>Type: ' + storage.price.type.name + '</br>Latency: ' + current.formatStorageLatency(storage.price.type.latency, true) + '</br>Optimized: ' + storage.price.type.optimized; } else if (data.type === 'support') { var support = conf.supportsById[data.name]; tooltip = 'Name: ' + support.name + '</br>Type: ' + support.price.type.name; } else if (data.type === 'database') { var database = conf.databasesById[data.name]; tooltip = 'Name: ' + database.name + '</br>Type: ' + database.price.type.name + '</br>Engine: ' + current.formatDatabaseEngine(database.price.engine, true) + (database.price.edition ? '/' + database.price.edition : '') + '</br>Term: ' + database.price.term.name + '</br>Usage: ' + (database.usage ? database.usage.name : ('(default) ' + (conf.usage ? conf.usage.name : '100%'))); } else { tooltip = data.name; } return '<span class="tooltip-text">' + tooltip + '<br/>Cost: ' + current.formatCost(data.size || data.value) + '</span>'; }); _('prov-sunburst').removeClass('hidden'); } else { _('prov-sunburst').addClass('hidden'); } }); }, /** * Update the gauge value depending on the computed usage. */ updateGauge: function (d3, usage) { if (d3.select('#prov-gauge').on('valueChanged') && usage.costNoSupport) { var weightCost = 0; if (usage.instance.cpu.available) { weightCost += usage.instance.cost * 0.8 * usage.instance.cpu.reserved / usage.instance.cpu.available; } if (usage.instance.ram.available) { weightCost += usage.instance.cost * 0.2 * usage.instance.ram.reserved / usage.instance.ram.available; } if (usage.database.cpu.available) { weightCost += usage.database.cost * 0.8 * usage.database.cpu.reserved / usage.database.cpu.available; } if (usage.database.ram.available) { weightCost += usage.database.cost * 0.2 * usage.database.ram.reserved / usage.database.ram.available; } if (usage.storage.available) { weightCost += usage.storage.cost * usage.storage.reserved / usage.storage.available; } _('prov-gauge').removeClass('hidden'); // Weight average of average... d3.select('#prov-gauge').on('valueChanged')(Math.floor(weightCost * 100 / usage.costNoSupport)); } else { $('#prov-gauge').addClass('hidden'); } }, getFilteredData: function (type) { var result = []; if (current[type + 'Table'] && current[type + 'Table'].fnSettings().oPreviousSearch.sSearch) { var data = _('prov-' + type + 's').DataTable().rows({ filter: 'applied' }).data(); for (var index = 0; index < data.length; index++) { result.push(data[index]); } } else { result = current.model.configuration[type + 's'] || {}; } if (type === 'instance' && (typeof current.filterDate === 'number' || typeof current.fixedDate === 'number')) { var usage = (current.model.configuration.usage || {}); var date = typeof current.filterDate === 'number' ? current.filterDate : current.fixedDate; return result.filter(qi => ((qi.usage || usage).start || 0) <= date); } return result; }, /** * Compute the global resource usage of this quote and the available capacity. Only minimal quantities are considered and with minimal to 1. * Maximal quantities is currently ignored. */ computeUsage: function () { var conf = current.model.configuration; var nb = 0; var i, t, qi, cost; // Timeline var timeline = []; var defaultUsage = conf.usage || { rate: 100, start: 0 }; var duration = 36; var date = moment().startOf('month'); for (i = 0; i < 36; i++) { timeline.push({ cost: 0, month: date.month(), year: date.year(), date: date.format('MM/YYYY'), instance: 0, storage: 0, support: 0, database: 0 }); date.add(1, 'months'); } // Instance statistics var publicAccess = 0; var instances = current.getFilteredData('instance'); var ramAvailable = 0; var ramReserved = 0; var cpuAvailable = 0; var cpuReserved = 0; var instanceCost = 0; var ramAdjustedRate = conf.ramAdjustedRate / 100; var minInstances = 0; var maxInstancesUnbound = false; var enabledInstances = {}; for (i = 0; i < instances.length; i++) { qi = instances[i]; cost = qi.cost.min || qi.cost || 0; nb = qi.minQuantity || 1; minInstances += nb; maxInstancesUnbound |= (qi.maxQuantity !== nb); cpuAvailable += qi.price.type.cpu * nb; cpuReserved += qi.cpu * nb; ramAvailable += qi.price.type.ram * nb; ramReserved += (ramAdjustedRate > 1 ? qi.ram * ramAdjustedRate : qi.ram) * nb; instanceCost += cost; publicAccess += (qi.internet === 'public') ? 1 : 0; enabledInstances[qi.id] = true; for (t = (qi.usage || defaultUsage).start || 0; t < duration; t++) { timeline[t].instance += cost; } } for (t = 0; t < duration; t++) { timeline[t].cost += instanceCost; } // Database statistics var publicAccessD = 0; var databases = current.getFilteredData('database'); var ramAvailableD = 0; var ramReservedD = 0; var cpuAvailableD = 0; var cpuReservedD = 0; var instanceCostD = 0; var minInstancesD = 0; var engines = {}; var maxInstancesUnboundD = false; var enabledInstancesD = {}; for (i = 0; i < databases.length; i++) { qi = databases[i]; cost = qi.cost.min || qi.cost || 0; nb = qi.minQuantity || 1; minInstancesD += nb; maxInstancesUnboundD |= (qi.maxQuantity !== nb); cpuAvailableD += qi.price.type.cpu * nb; cpuReservedD += qi.cpu * nb; ramAvailableD += qi.price.type.ram * nb; ramReservedD += (ramAdjustedRate > 1 ? qi.ram * ramAdjustedRate : qi.ram) * nb; instanceCostD += cost; var engine = qi.engine.replace(/AURORA .*/, 'AURORA'); engines[engine] = (engines[engine] || 0) + 1; publicAccessD += (qi.internet === 'public') ? 1 : 0; enabledInstancesD[qi.id] = true; for (t = (qi.usage || defaultUsage).start || 0; t < duration; t++) { timeline[t].database += cost; } } for (t = 0; t < duration; t++) { timeline[t].cost += instanceCostD; } // Storage statistics var storageAvailable = 0; var storageReserved = 0; var storageCost = 0; var storages = current.getFilteredData('storage'); for (i = 0; i < storages.length; i++) { var qs = storages[i]; if (qs.quoteInstance && enabledInstances[qs.quoteInstance.id]) { nb = qs.quoteInstance.minQuantity || 1; } else if (qs.quoteDatabase && enabledInstancesD[qs.quoteDatabase.id]) { nb = qs.quoteDatabase.minQuantity || 1; } else { nb = 1; } storageAvailable += Math.max(qs.size, qs.price.type.minimal) * nb; storageReserved += qs.size * nb; storageCost += qs.cost; } for (t = 0; t < duration; t++) { timeline[t].storage = storageCost; timeline[t].cost += storageCost; } // Support statistics var supportCost = 0; var supports = current.getFilteredData('support'); for (i = 0; i < supports.length; i++) { supportCost += supports[i].cost; } for (t = 0; t < duration; t++) { timeline[t].support = supportCost; timeline[t].cost += supportCost; } return { cost: instanceCost + instanceCostD + storageCost + supportCost, costNoSupport: instanceCost + storageCost, unbound: maxInstancesUnbound || maxInstancesUnboundD, timeline: timeline, instance: { nb: instances.length, min: minInstances, unbound: maxInstancesUnbound, ram: { available: ramAvailable, reserved: ramReserved }, cpu: { available: cpuAvailable, reserved: cpuReserved }, publicAccess: publicAccess, filtered: instances, cost: instanceCost }, database: { nb: databases.length, min: minInstancesD, unbound: maxInstancesUnboundD, ram: { available: ramAvailableD, reserved: ramReservedD }, cpu: { available: cpuAvailableD, reserved: cpuReservedD }, engines: engines, publicAccess: publicAccessD, filtered: databases, cost: instanceCostD }, storage: { nb: storages.length, available: storageAvailable, reserved: storageReserved, filtered: storages, cost: storageCost }, support: { nb: supports.length, filtered: supports, first: supports.length ? supports[0].price.type.name : null, more: supports.length > 1, cost: supportCost } }; }, /** * Update the model to detach a storage from its instance * @param storage The storage model to detach. * @param property The storage property of attachment. */ detachStorage: function (storage, property) { if (storage[property]) { var qis = storage[property].storages || []; for (var i = qis.length; i-- > 0;) { if (qis[i] === storage) { qis.splice(i, 1); break; } } delete storage[property]; } }, /** * Update the model to attach a storage to its resource * @param storage The storage model to attach. * @param type The resource type to attach. * @param resource The resource model or identifier to attach. * @param force When <code>true</code>, the previous resource will not be dettached. */ attachStorage: function (storage, type, resource, force) { if (typeof resource === 'number') { resource = current.model.configuration[type + 'sById'][resource]; } var property = 'quote' + type.charAt(0).toUpperCase() + type.slice(1); if (force !== true && storage[property] === resource) { // Already attached or nothing to attach to the target resource return; } if (force !== true && storage[property]) { // Ddetach the old resource current.detachStorage(storage, property); } // Update the model if (resource) { if ($.isArray(resource.storages)) { resource.storages.push(storage); } else { resource.storages = [storage]; } storage[property] = resource; } }, toD3: function (usage) { var data = { name: current.$messages['service:prov:total'], value: usage.cost, children: [] }; current.storageToD3(data, usage); current.instanceToD3(data, usage); current.databaseToD3(data, usage); current.supportToD3(data, usage); return data; }, instanceToD3: function (data, usage) { var allOss = {}; var instances = usage.instance.filtered; var d3instances = { name: '<i class="fas fa-server fa-2x"></i> ' + current.$messages['service:prov:instances-block'], value: 0, children: [] }; data.children.push(d3instances); for (var i = 0; i < instances.length; i++) { var qi = instances[i]; var oss = allOss[qi.os]; if (typeof oss === 'undefined') { // First OS oss = { name: qi.os, type: 'os', value: 0, children: [] }; allOss[qi.os] = oss; d3instances.children.push(oss); } oss.value += qi.cost; d3instances.value += qi.cost; oss.children.push({ name: qi.id, type: 'instance', size: qi.cost }); } }, databaseToD3: function (data, usage) { var allEngines = {}; var databases = usage.database.filtered; var d3databases = { name: '<i class="fas fa-server fa-2x"></i> ' + current.$messages['service:prov:databases-block'], value: 0, children: [] }; data.children.push(d3databases); for (var i = 0; i < databases.length; i++) { var qi = databases[i]; var engines = allEngines[qi.engine]; if (typeof engines === 'undefined') { // First Engine engines = { name: qi.engine, type: 'engine', value: 0, children: [] }; allEngines[qi.engine] = engines; d3databases.children.push(engines); } engines.value += qi.cost; d3databases.value += qi.cost; engines.children.push({ name: qi.id, type: 'database', size: qi.cost }); } }, storageToD3: function (data, usage) { var storages = usage.storage.filtered; var d3storages = { name: '<i class="far fa-hdd fa-2x"></i> ' + current.$messages['service:prov:storages-block'], value: 0, children: [] }; data.children.push(d3storages); var allOptimizations = {}; for (var i = 0; i < storages.length; i++) { var qs = storages[i]; var optimizations = allOptimizations[qs.price.type.latency]; if (typeof optimizations === 'undefined') { // First optimization optimizations = { name: qs.price.type.latency, type: 'latency', value: 0, children: [] }; allOptimizations[qs.price.type.latency] = optimizations; d3storages.children.push(optimizations); } optimizations.value += qs.cost; d3storages.value += qs.cost; optimizations.children.push({ name: qs.id, type: 'storage', size: qs.cost }); } }, supportToD3: function (data, usage) { var supports = usage.support.filtered; var d3supports = { name: '<i class="fas fa-ambulance fa-2x"></i> ' + current.$messages['service:prov:support-block'], value: 0, children: [] }; data.children.push(d3supports); for (var i = 0; i < supports.length; i++) { var support = supports[i]; d3supports.value += support.cost; d3supports.children.push({ name: support.id, type: 'support', size: support.cost }); } }, /** * Initialize the instance datatables from the whole quote */ instanceNewTable: function () { return current.genericInstanceNewTable('instance', [{ data: 'minQuantity', className: 'hidden-xs', type: 'num', render: current.formatQuantity }, { data: 'os', className: 'truncate', width: '24px', render: current.formatOs }, { data: 'cpu', className: 'truncate', width: '48px', type: 'num', render: current.formatCpu }, { data: 'ram', className: 'truncate', width: '64px', type: 'num', render: current.formatRam }, { data: 'price.term', className: 'hidden-xs hidden-sm price-term', render: current.formatInstanceTerm }, { data: 'price.type', className: 'truncate hidden-xs hidden-sm hidden-md', render: current.formatInstanceType }, { data: 'usage', className: 'hidden-xs hidden-sm usage', render: current.formatUsageTemplate }, { data: 'location', className: 'hidden-xs hidden-sm location', width: '24px', render: current.formatLocation }, { data: null, className: 'truncate hidden-xs hidden-sm', render: current.formatQiStorages }]); }, /** * Initialize the support datatables from the whole quote */ supportNewTable: function () { return { columns: [{ data: 'level', width: '128px', render: current.formatSupportLevel }, { data: 'seats', className: 'hidden-xs', type: 'num', render: current.formatSupportSeats }, { data: 'accessApi', className: 'hidden-xs hidden-sm hidden-md', render: current.formatSupportAccess }, { data: 'accessPhone', className: 'hidden-xs hidden-sm hidden-md', render: current.formatSupportAccess }, { data: 'accessEmail', className: 'hidden-xs hidden-sm hidden-md', render: current.formatSupportAccess }, { data: 'accessChat', className: 'hidden-xs hidden-sm hidden-md', render: current.formatSupportAccess }, { data: 'price.type.name', className: 'truncate' }] }; }, /** * Find a free name within the given namespace. * @param {array} resources The namespace of current resources. * @param {string} prefix The preferred name (if available) and used as prefix when there is collision. * @param {string} increment The current increment number of collision. Will starts from 1 when not specified. * @param {string} resourcesByName The namespace where key is the unique name. */ findNewName: function (resources, prefix, increment, resourcesByName) { if (typeof resourcesByName === 'undefined') { // Build the name based index resourcesByName = {}; resources.forEach(resource => resourcesByName[resource.name] = resource); } if (resourcesByName[prefix]) { increment = increment || 1; if (resourcesByName[prefix + '-' + increment]) { return current.findNewName(resourcesByName, prefix, increment + 1, resourcesByName); } return prefix + '-' + increment; } return prefix; }, /** * Initialize the storage datatables from the whole quote */ storageNewTable: function () { return { columns: [{ data: null, type: 'num', className: 'hidden-xs', render: (_i, mode, data) => current.formatQuantity(null, mode, (data.quoteInstance || data.quoteDatabase)) }, { data: 'size', width: '36px', className: 'truncate', type: 'num', render: current.formatStorage }, { data: 'price.type.latency', className: 'truncate hidden-xs', render: current.formatStorageLatency }, { data: 'price.type.optimized', className: 'truncate hidden-xs', render: current.formatStorageOptimized }, { data: 'price.type', className: 'truncate hidden-xs hidden-sm hidden-md', render: current.formatStorageType }, { data: null, className: 'truncate hidden-xs hidden-sm', render: (_i, mode, data) => (data.quoteInstance || data.quoteDatabase || {}).name }] }; }, /** * Donut of usage * @param {integer} rate The rate percent tage 1-100% */ updateD3UsageRate: function (rate) { require(['d3', '../main/service/prov/lib/donut'], function (d3, donut) { if (current.contextDonut) { donut.update(current.contextDonut, rate); } else { current.contextDonut = donut.create("#usage-chart", rate, 250, 250); } }); }, formatDatabaseEngine(engine, mode, clazz) { var cfg = current.databaseEngines[(engine.id || engine || 'MYSQL').toUpperCase()] || current.databaseEngines.MYSQL; if (mode === 'sort' || mode === 'filter') { return cfg[0]; } clazz = cfg[1] + (typeof clazz === 'string' ? clazz : ''); return '<i class="' + clazz + '" data-toggle="tooltip" title="' + cfg[0] + '"></i> ' + cfg[0]; }, /** * Initialize the database datatables from the whole quote */ databaseNewTable: function () { return current.genericInstanceNewTable('database', [{ data: 'minQuantity', className: 'hidden-xs', type: 'num', render: current.formatQuantity }, { data: 'price.engine', className: 'truncate', render: current.formatDatabaseEngine }, { data: 'price.edition', className: 'truncate' }, { data: 'cpu', className: 'truncate', width: '48px', type: 'num', render: current.formatCpu }, { data: 'ram', className: 'truncate', width: '64px', type: 'num', render: current.formatRam }, { data: 'price.term', className: 'hidden-xs hidden-sm price-term', render: current.formatInstanceTerm }, { data: 'price.type', className: 'truncate hidden-xs hidden-sm hidden-md', render: current.formatInstanceType }, { data: 'usage', className: 'hidden-xs hidden-sm usage', render: current.formatUsageTemplate }, { data: 'location', className: 'hidden-xs hidden-sm location', width: '24px', render: current.formatLocation }, { data: null, className: 'truncate hidden-xs hidden-sm', render: current.formatQiStorages }]); }, /** * Initialize the database datatables from the whole quote */ genericInstanceNewTable: function (type, columns) { return { rowCallback: function (nRow, qi) { $(nRow).find('.storages-tags').select2('destroy').select2({ multiple: true, minimumInputLength: 1, createSearchChoice: () => null, formatInputTooShort: current.$messages['service:prov:storage-select'], formatResult: current.formatStoragePriceHtml, formatSelection: current.formatStorageHtml, ajax: { url: REST_PATH + 'service/prov/' + current.model.subscription + '/storage-lookup?' + type + '=' + qi.id, dataType: 'json', data: function (term) { return { size: $.isNumeric(term) ? parseInt(term, 10) : 1, // search term }; }, results: function (data) { // Completed the requested identifier data.forEach(quote => { quote.id = quote.price.id + '-' + new Date().getMilliseconds(); quote.text = quote.price.type.name; }); return { more: false, results: data }; } } }).select2('data', qi.storages || []).off('change').on('change', function (event) { if (event.added) { // New storage var suggest = event.added; var data = { name: current.findNewName(current.model.configuration.storages, qi.name), type: suggest.price.type.name, size: suggest.size, quoteInstance: type === 'instance' && qi.id, quoteDatabase: type === 'database' && qi.id, subscription: current.model.subscription }; current.$main.trimObject(data); $.ajax({ type: 'POST', url: REST_PATH + 'service/prov/storage', dataType: 'json', contentType: 'application/json', data: JSON.stringify(data), success: function (updatedCost) { current.saveAndUpdateCosts('storage', updatedCost, data, suggest, null, qi.location); // Keep the focus on this UI after the redraw of the row $(function () { _('prov-' + type + 's').find('tr[data-id="' + qi.id + '"]').find('.storages-tags .select2-input').trigger('focus'); }); } }); } else if (event.removed) { // Storage to delete var qs = event.removed.qs || event.removed; $.ajax({ type: 'DELETE', url: REST_PATH + 'service/prov/storage/' + qs.id, success: updatedCost => current.defaultCallback('storage', updatedCost) }); } }); }, columns: columns }; }, /** * Default Ajax callback after a deletion, update or create. This function looks the updated resources (identifiers), the deletd resources and the new updated costs. * @param {string} type The related resource type. * @param {object} updatedCost The new costs details. * @param {object} resource Optional resource to update or create. When null, its a deletion. */ defaultCallback: function (type, updatedCost, resource) { var related = updatedCost.related || {}; var deleted = updatedCost.deleted || {}; var conf = current.model.configuration; var nbCreated = 0; var nbUpdated = 0; var nbDeleted = 0; var createdSample = null; var updatedSample = null; var deletedSample = null; conf.cost = updatedCost.total; // Look the deleted resources Object.keys(deleted).forEach(type => { // For each deleted resource of this type, update the UI and the cost in the model for (var i = deleted[type].length; i-- > 0;) { var deletedR = current.delete(type.toLowerCase(), deleted[type][i], true); if (nbDeleted++ === 0) { deletedSample = deletedR.name; } } }); // Look the updated resources Object.keys(related).forEach(key => { // For each updated resource of this type, update the UI and the cost in the model Object.keys(related[key]).forEach(id => { var relatedType = key.toLowerCase(); var resource = conf[relatedType + 'sById'][id]; var cost = related[key][id]; conf[relatedType + 'Cost'] += cost.min - resource.cost; resource.cost = cost.min; resource.maxCost = cost.max; if (nbUpdated++ === 0) { updatedSample = resource.name; } current.redrawResource(relatedType, id); }); }); // Update the current object if (resource) { resource.cost = updatedCost.cost.min; resource.maxCost = updatedCost.cost.max; if (conf[type + 'sById'][updatedCost.id]) { // Update : Redraw the row nbUpdated++; updatedSample = resource.name; current.redrawResource(type, updatedCost.id); } else { conf[type + 's'].push(resource); conf[type + 'sById'][updatedCost.id] = resource; resource.id = updatedCost.id; nbCreated++; createdSample = resource.name; _('prov-' + type + 's').DataTable().row.add(resource).draw(false); } } else if (updatedCost.id) { // Delete this object nbDeleted++; deletedSample = current.delete(type, updatedCost.id, true).name; } // Notify callback var message = []; if (nbCreated) { message.push(Handlebars.compile(current.$messages['service:prov:created'])({ count: nbCreated, sample: createdSample, more: nbCreated - 1 })); } if (nbUpdated) { message.push(Handlebars.compile(current.$messages['service:prov:updated'])({ count: nbUpdated, sample: updatedSample, more: nbUpdated - 1 })); } if (nbDeleted) { message.push(Handlebars.compile(current.$messages['service:prov:deleted'])({ count: nbDeleted, sample: deletedSample, more: nbDeleted - 1 })); } if (message.length) { notifyManager.notify(message.join('<br>')); } $('.tooltip').remove(); // TODO Generalize current.updateUiCost(); }, /** * Delete a resource. * @param {string} type The resource type. * @param {integer} id The resource identifier. */ delete: function (type, id, draw) { var conf = current.model.configuration; var resources = conf[type + 's']; for (var i = resources.length; i-- > 0;) { var resource = resources[i]; if (resource.id === id) { resources.splice(i, 1); delete conf[type + 'sById'][resource.id]; conf[type + 'Cost'] -= resource.cost; if (type === 'storage') { var qr = resource.quoteInstance || resource.quoteDatabase; if (qr) { // Also redraw the instance var attachedType = resource.quoteInstance ? 'instance' : 'database'; current.detachStorage(resource, 'quote' + attachedType.charAt(0).toUpperCase() + attachedType.slice(1)); if (draw) { current.redrawResource(attachedType, qr.id); } } } var row = _('prov-' + type + 's').DataTable().rows((_, data) => data.id === id).remove(); if (draw) { row.draw(false); } return resource; } } }, }; return current; });
Fix #41 Disallow NAT internet visibility for databases
src/main/resources/META-INF/resources/webjars/service/prov/prov.js
Fix #41 Disallow NAT internet visibility for databases
<ide><path>rc/main/resources/META-INF/resources/webjars/service/prov/prov.js <ide> _('instance-internet').select2({ <ide> formatSelection: current.formatInternet, <ide> formatResult: current.formatInternet, <add> formatResultCssClass: function (data) { <add> if (data.id === 'PRIVATE_NAT' && _('instance-internet').closest('[data-prov-type]').attr('data-prov-type') === 'database') { <add> return 'hidden'; <add> } <add> }, <ide> escapeMarkup: m => m, <ide> data: [{ <ide> id: 'PUBLIC',
Java
apache-2.0
d4117b12d1b270a11b7e41a91feb9147bb91b5d7
0
linkedin/pinot,apucher/pinot,apucher/pinot,fx19880617/pinot-1,linkedin/pinot,fx19880617/pinot-1,apucher/pinot,fx19880617/pinot-1,fx19880617/pinot-1,linkedin/pinot,linkedin/pinot,fx19880617/pinot-1,linkedin/pinot,apucher/pinot,apucher/pinot
/** * Copyright (C) 2014-2018 LinkedIn Corp. ([email protected]) * * 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.linkedin.thirdeye.auto.onboard; import com.linkedin.thirdeye.anomaly.ThirdEyeAnomalyConfiguration; import com.linkedin.thirdeye.api.TimeGranularity; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This is a service to onboard datasets automatically to thirdeye from the different data sources * This service runs periodically and runs auto load for each data source */ public class AutoOnboardService implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(AutoOnboardService.class); private ScheduledExecutorService scheduledExecutorService; private List<AutoOnboard> autoOnboardServices = new ArrayList<>(); private TimeGranularity runFrequency; /** * Reads data sources configs and instantiates the constructors for auto load of all data sources, if availble * @param config */ public AutoOnboardService(ThirdEyeAnomalyConfiguration config) { this.runFrequency = config.getAutoOnboardConfiguration().getRunFrequency(); scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); Map<String, List<AutoOnboard>> dataSourceToOnboardMap = AutoOnboardUtility.getDataSourceToAutoOnboardMap( config.getDataSourcesAsUrl()); for (List<AutoOnboard> autoOnboards : dataSourceToOnboardMap.values()) { autoOnboardServices.addAll(autoOnboards); } } public void start() { scheduledExecutorService.scheduleAtFixedRate(this, 0, runFrequency.getSize(), runFrequency.getUnit()); } public void shutdown() { LOG.info("Shutting down AutoOnboardService"); scheduledExecutorService.shutdown(); } @Override public void run() { for (AutoOnboard autoOnboard : autoOnboardServices) { LOG.info("Running auto load for {}", autoOnboard.getClass().getSimpleName()); try { autoOnboard.run(); } catch (Throwable t) { LOG.error("Uncaught exception is detected while running AutoOnboard for {}", autoOnboard.getClass().getSimpleName()); t.printStackTrace(); } } } }
thirdeye/thirdeye-pinot/src/main/java/com/linkedin/thirdeye/auto/onboard/AutoOnboardService.java
/** * Copyright (C) 2014-2018 LinkedIn Corp. ([email protected]) * * 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.linkedin.thirdeye.auto.onboard; import com.linkedin.thirdeye.anomaly.ThirdEyeAnomalyConfiguration; import com.linkedin.thirdeye.api.TimeGranularity; import com.linkedin.thirdeye.datasource.DataSourceConfig; import com.linkedin.thirdeye.datasource.DataSources; import com.linkedin.thirdeye.datasource.DataSourcesLoader; import com.linkedin.thirdeye.datasource.MetadataSourceConfig; import java.lang.reflect.Constructor; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This is a service to onboard datasets automatically to thirdeye from the different data sources * This service runs periodically and runs auto load for each data source */ public class AutoOnboardService implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(AutoOnboardService.class); private ScheduledExecutorService scheduledExecutorService; private List<AutoOnboard> autoOnboardServices = new ArrayList<>(); private TimeGranularity runFrequency; /** * Reads data sources configs and instantiates the constructors for auto load of all data sources, if availble * @param config */ public AutoOnboardService(ThirdEyeAnomalyConfiguration config) { this.runFrequency = config.getAutoOnboardConfiguration().getRunFrequency(); scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); Map<String, List<AutoOnboard>> dataSourceToOnboardMap = AutoOnboardUtility.getDataSourceToAutoOnboardMap( config.getDataSourcesAsUrl()); for (List<AutoOnboard> autoOnboards : dataSourceToOnboardMap.values()) { autoOnboardServices.addAll(autoOnboards); } } public void start() { scheduledExecutorService.scheduleAtFixedRate(this, 0, runFrequency.getSize(), runFrequency.getUnit()); } public void shutdown() { LOG.info("Shutting down AutoOnboardService"); scheduledExecutorService.shutdown(); } @Override public void run() { for (AutoOnboard autoOnboard : autoOnboardServices) { LOG.info("Running auto load for {}", autoOnboard.getClass().getSimpleName()); try { autoOnboard.run(); } catch (Exception e) { LOG.error("There was an exception running AutoOnboard for {}", autoOnboard.getClass().getSimpleName(), e); } } } }
[TE] Cleanup and fix exception handler (#3239)
thirdeye/thirdeye-pinot/src/main/java/com/linkedin/thirdeye/auto/onboard/AutoOnboardService.java
[TE] Cleanup and fix exception handler (#3239)
<ide><path>hirdeye/thirdeye-pinot/src/main/java/com/linkedin/thirdeye/auto/onboard/AutoOnboardService.java <ide> <ide> import com.linkedin.thirdeye.anomaly.ThirdEyeAnomalyConfiguration; <ide> import com.linkedin.thirdeye.api.TimeGranularity; <del>import com.linkedin.thirdeye.datasource.DataSourceConfig; <del>import com.linkedin.thirdeye.datasource.DataSources; <del>import com.linkedin.thirdeye.datasource.DataSourcesLoader; <del>import com.linkedin.thirdeye.datasource.MetadataSourceConfig; <del>import java.lang.reflect.Constructor; <del>import java.net.URL; <ide> import java.util.ArrayList; <ide> import java.util.List; <ide> import java.util.Map; <ide> import java.util.concurrent.Executors; <ide> import java.util.concurrent.ScheduledExecutorService; <del>import org.apache.commons.lang3.StringUtils; <ide> import org.slf4j.Logger; <ide> import org.slf4j.LoggerFactory; <ide> <ide> LOG.info("Running auto load for {}", autoOnboard.getClass().getSimpleName()); <ide> try { <ide> autoOnboard.run(); <del> } catch (Exception e) { <del> LOG.error("There was an exception running AutoOnboard for {}", autoOnboard.getClass().getSimpleName(), e); <add> } catch (Throwable t) { <add> LOG.error("Uncaught exception is detected while running AutoOnboard for {}", autoOnboard.getClass().getSimpleName()); <add> t.printStackTrace(); <ide> } <ide> } <ide> }
Java
apache-2.0
108ca26967a1f7dc0a6fb8c166ada144908697f2
0
dbrant/apps-android-commons,whym/apps-android-commons,dbrant/apps-android-commons,maskaravivek/apps-android-commons,commons-app/apps-android-commons,domdomegg/apps-android-commons,misaochan/apps-android-commons,neslihanturan/apps-android-commons,misaochan/apps-android-commons,misaochan/apps-android-commons,commons-app/apps-android-commons,psh/apps-android-commons,maskaravivek/apps-android-commons,domdomegg/apps-android-commons,domdomegg/apps-android-commons,neslihanturan/apps-android-commons,maskaravivek/apps-android-commons,misaochan/apps-android-commons,psh/apps-android-commons,commons-app/apps-android-commons,commons-app/apps-android-commons,psh/apps-android-commons,maskaravivek/apps-android-commons,nicolas-raoul/apps-android-commons,misaochan/apps-android-commons,nicolas-raoul/apps-android-commons,neslihanturan/apps-android-commons,maskaravivek/apps-android-commons,nicolas-raoul/apps-android-commons,commons-app/apps-android-commons,misaochan/apps-android-commons,whym/apps-android-commons,dbrant/apps-android-commons,whym/apps-android-commons,psh/apps-android-commons,neslihanturan/apps-android-commons,domdomegg/apps-android-commons,neslihanturan/apps-android-commons,domdomegg/apps-android-commons,dbrant/apps-android-commons,nicolas-raoul/apps-android-commons,whym/apps-android-commons,psh/apps-android-commons
package fr.free.nrw.commons.nearby; import android.animation.ObjectAnimator; import android.animation.TypeEvaluator; import android.animation.ValueAnimator; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.BottomSheetBehavior; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import com.mapbox.mapboxsdk.Mapbox; import com.mapbox.mapboxsdk.annotations.Icon; import com.mapbox.mapboxsdk.annotations.IconFactory; import com.mapbox.mapboxsdk.annotations.Marker; import com.mapbox.mapboxsdk.annotations.MarkerOptions; import com.mapbox.mapboxsdk.annotations.PolygonOptions; import com.mapbox.mapboxsdk.camera.CameraPosition; import com.mapbox.mapboxsdk.camera.CameraUpdateFactory; import com.mapbox.mapboxsdk.constants.Style; import com.mapbox.mapboxsdk.geometry.LatLng; import com.mapbox.mapboxsdk.maps.MapView; import com.mapbox.mapboxsdk.maps.MapboxMap; import com.mapbox.mapboxsdk.maps.MapboxMapOptions; import com.mapbox.mapboxsdk.maps.OnMapReadyCallback; import com.mapbox.services.android.telemetry.MapboxTelemetry; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import javax.inject.Named; import dagger.android.support.DaggerFragment; import fr.free.nrw.commons.R; import fr.free.nrw.commons.Utils; import fr.free.nrw.commons.contributions.ContributionController; import fr.free.nrw.commons.utils.UriDeserializer; import fr.free.nrw.commons.utils.ViewUtil; import timber.log.Timber; import static android.app.Activity.RESULT_OK; import static android.content.pm.PackageManager.PERMISSION_GRANTED; public class NearbyMapFragment extends DaggerFragment { private MapView mapView; private List<NearbyBaseMarker> baseMarkerOptions; private fr.free.nrw.commons.location.LatLng curLatLng; public fr.free.nrw.commons.location.LatLng[] boundaryCoordinates; private View bottomSheetList; private View bottomSheetDetails; private BottomSheetBehavior bottomSheetListBehavior; private BottomSheetBehavior bottomSheetDetailsBehavior; private LinearLayout wikipediaButton; private LinearLayout wikidataButton; private LinearLayout directionsButton; private LinearLayout commonsButton; private FloatingActionButton fabPlus; private FloatingActionButton fabCamera; private FloatingActionButton fabGallery; private FloatingActionButton fabRecenter; private View transparentView; private TextView description; private TextView title; private TextView distance; private ImageView icon; private TextView wikipediaButtonText; private TextView wikidataButtonText; private TextView commonsButtonText; private TextView directionsButtonText; private boolean isFabOpen = false; private Animation rotate_backward; private Animation fab_close; private Animation fab_open; private Animation rotate_forward; private ContributionController controller; private DirectUpload directUpload; private Place place; private Marker selected; private Marker currentLocationMarker; private MapboxMap mapboxMap; private PolygonOptions currentLocationPolygonOptions; private boolean isBottomListSheetExpanded; private final double CAMERA_TARGET_SHIFT_FACTOR_PORTRAIT = 0.06; private final double CAMERA_TARGET_SHIFT_FACTOR_LANDSCAPE = 0.04; private Bundle bundleForUpdtes;// Carry information from activity about changed nearby places and current location @Inject @Named("prefs") SharedPreferences prefs; @Inject @Named("direct_nearby_upload_prefs") SharedPreferences directPrefs; public NearbyMapFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Timber.d("Nearby map fragment created"); controller = new ContributionController(this); directUpload = new DirectUpload(this, controller); Bundle bundle = this.getArguments(); Gson gson = new GsonBuilder() .registerTypeAdapter(Uri.class, new UriDeserializer()) .create(); if (bundle != null) { String gsonPlaceList = bundle.getString("PlaceList"); String gsonLatLng = bundle.getString("CurLatLng"); Type listType = new TypeToken<List<Place>>() { }.getType(); String gsonBoundaryCoordinates = bundle.getString("BoundaryCoord"); List<Place> placeList = gson.fromJson(gsonPlaceList, listType); Type curLatLngType = new TypeToken<fr.free.nrw.commons.location.LatLng>() { }.getType(); Type gsonBoundaryCoordinatesType = new TypeToken<fr.free.nrw.commons.location.LatLng[]>() {}.getType(); curLatLng = gson.fromJson(gsonLatLng, curLatLngType); baseMarkerOptions = NearbyController .loadAttractionsFromLocationToBaseMarkerOptions(curLatLng, placeList, getActivity()); boundaryCoordinates = gson.fromJson(gsonBoundaryCoordinates, gsonBoundaryCoordinatesType); } if (curLatLng != null) { Mapbox.getInstance(getActivity(), getString(R.string.mapbox_commons_app_token)); MapboxTelemetry.getInstance().setTelemetryEnabled(false); } setRetainInstance(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Timber.d("onCreateView called"); if (curLatLng != null) { Timber.d("curLatLng found, setting up map view..."); setupMapView(savedInstanceState); } setHasOptionsMenu(false); return mapView; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); this.getView().setFocusableInTouchMode(true); this.getView().requestFocus(); this.getView().setOnKeyListener((v, keyCode, event) -> { if (keyCode == KeyEvent.KEYCODE_BACK) { if (bottomSheetDetailsBehavior.getState() == BottomSheetBehavior .STATE_EXPANDED) { bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); return true; } else if (bottomSheetDetailsBehavior.getState() == BottomSheetBehavior .STATE_COLLAPSED) { bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); mapView.getMapAsync(MapboxMap::deselectMarkers); selected = null; return true; } } return false; }); } public void updateMapSlightly() { if (mapboxMap != null) { Gson gson = new GsonBuilder() .registerTypeAdapter(Uri.class, new UriDeserializer()) .create(); if (bundleForUpdtes != null) { String gsonLatLng = bundleForUpdtes.getString("CurLatLng"); Type curLatLngType = new TypeToken<fr.free.nrw.commons.location.LatLng>() {}.getType(); curLatLng = gson.fromJson(gsonLatLng, curLatLngType); } updateMapToTrackPosition(); } } public void updateMapSignificantly() { if (mapboxMap != null) { if (bundleForUpdtes != null) { Gson gson = new GsonBuilder() .registerTypeAdapter(Uri.class, new UriDeserializer()) .create(); String gsonPlaceList = bundleForUpdtes.getString("PlaceList"); String gsonLatLng = bundleForUpdtes.getString("CurLatLng"); String gsonBoundaryCoordinates = bundleForUpdtes.getString("BoundaryCoord"); Type listType = new TypeToken<List<Place>>() {}.getType(); List<Place> placeList = gson.fromJson(gsonPlaceList, listType); Type curLatLngType = new TypeToken<fr.free.nrw.commons.location.LatLng>() {}.getType(); Type gsonBoundaryCoordinatesType = new TypeToken<fr.free.nrw.commons.location.LatLng[]>() {}.getType(); curLatLng = gson.fromJson(gsonLatLng, curLatLngType); baseMarkerOptions = NearbyController .loadAttractionsFromLocationToBaseMarkerOptions(curLatLng, placeList, getActivity()); boundaryCoordinates = gson.fromJson(gsonBoundaryCoordinates, gsonBoundaryCoordinatesType); } mapboxMap.clear(); addCurrentLocationMarker(mapboxMap); updateMapToTrackPosition(); addNearbyMarkerstoMapBoxMap(); } } // Only update current position marker and camera view private void updateMapToTrackPosition() { if (currentLocationMarker != null) { LatLng curMapBoxLatLng = new LatLng(curLatLng.getLatitude(),curLatLng.getLongitude()); ValueAnimator markerAnimator = ObjectAnimator.ofObject(currentLocationMarker, "position", new LatLngEvaluator(), currentLocationMarker.getPosition(), curMapBoxLatLng); markerAnimator.setDuration(1000); markerAnimator.start(); List<LatLng> circle = createCircleArray(curLatLng.getLatitude(), curLatLng.getLongitude(), curLatLng.getAccuracy() * 2, 100); if (currentLocationPolygonOptions != null){ mapboxMap.removePolygon(currentLocationPolygonOptions.getPolygon()); currentLocationPolygonOptions = new PolygonOptions() .addAll(circle) .strokeColor(Color.parseColor("#55000000")) .fillColor(Color.parseColor("#11000000")); mapboxMap.addPolygon(currentLocationPolygonOptions); } // Make camera to follow user on location change CameraPosition position ; if(ViewUtil.isPortrait(getActivity())){ position = new CameraPosition.Builder() .target(isBottomListSheetExpanded ? new LatLng(curMapBoxLatLng.getLatitude()- CAMERA_TARGET_SHIFT_FACTOR_PORTRAIT, curMapBoxLatLng.getLongitude()) : curMapBoxLatLng ) // Sets the new camera position .zoom(isBottomListSheetExpanded ? 11 // zoom level is fixed to 11 when bottom sheet is expanded :mapboxMap.getCameraPosition().zoom) // Same zoom level .build(); }else { position = new CameraPosition.Builder() .target(isBottomListSheetExpanded ? new LatLng(curMapBoxLatLng.getLatitude()- CAMERA_TARGET_SHIFT_FACTOR_LANDSCAPE, curMapBoxLatLng.getLongitude()) : curMapBoxLatLng ) // Sets the new camera position .zoom(isBottomListSheetExpanded ? 11 // zoom level is fixed to 11 when bottom sheet is expanded :mapboxMap.getCameraPosition().zoom) // Same zoom level .build(); } mapboxMap.animateCamera(CameraUpdateFactory .newCameraPosition(position), 1000); } } private void updateMapCameraAccordingToBottomSheet(boolean isBottomListSheetExpanded) { CameraPosition position; this.isBottomListSheetExpanded = isBottomListSheetExpanded; if (mapboxMap != null && curLatLng != null) { if (isBottomListSheetExpanded) { // Make camera to follow user on location change if(ViewUtil.isPortrait(getActivity())) { position = new CameraPosition.Builder() .target(new LatLng(curLatLng.getLatitude() - CAMERA_TARGET_SHIFT_FACTOR_PORTRAIT, curLatLng.getLongitude())) // Sets the new camera target above // current to make it visible when sheet is expanded .zoom(11) // Fixed zoom level .build(); } else { position = new CameraPosition.Builder() .target(new LatLng(curLatLng.getLatitude() - CAMERA_TARGET_SHIFT_FACTOR_LANDSCAPE, curLatLng.getLongitude())) // Sets the new camera target above // current to make it visible when sheet is expanded .zoom(11) // Fixed zoom level .build(); } } else { // Make camera to follow user on location change position = new CameraPosition.Builder() .target(new LatLng(curLatLng.getLatitude(), curLatLng.getLongitude())) // Sets the new camera target to curLatLng .zoom(mapboxMap.getCameraPosition().zoom) // Same zoom level .build(); } mapboxMap.animateCamera(CameraUpdateFactory .newCameraPosition(position), 1000); } } private void initViews() { bottomSheetList = getActivity().findViewById(R.id.bottom_sheet); bottomSheetListBehavior = BottomSheetBehavior.from(bottomSheetList); bottomSheetDetails = getActivity().findViewById(R.id.bottom_sheet_details); bottomSheetDetailsBehavior = BottomSheetBehavior.from(bottomSheetDetails); bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); bottomSheetDetails.setVisibility(View.VISIBLE); fabPlus = getActivity().findViewById(R.id.fab_plus); fabCamera = getActivity().findViewById(R.id.fab_camera); fabGallery = getActivity().findViewById(R.id.fab_galery); fabRecenter = getActivity().findViewById(R.id.fab_recenter); fab_open = AnimationUtils.loadAnimation(getActivity(), R.anim.fab_open); fab_close = AnimationUtils.loadAnimation(getActivity(), R.anim.fab_close); rotate_forward = AnimationUtils.loadAnimation(getActivity(), R.anim.rotate_forward); rotate_backward = AnimationUtils.loadAnimation(getActivity(), R.anim.rotate_backward); transparentView = getActivity().findViewById(R.id.transparentView); description = getActivity().findViewById(R.id.description); title = getActivity().findViewById(R.id.title); distance = getActivity().findViewById(R.id.category); icon = getActivity().findViewById(R.id.icon); wikidataButton = getActivity().findViewById(R.id.wikidataButton); wikipediaButton = getActivity().findViewById(R.id.wikipediaButton); directionsButton = getActivity().findViewById(R.id.directionsButton); commonsButton = getActivity().findViewById(R.id.commonsButton); wikidataButtonText = getActivity().findViewById(R.id.wikidataButtonText); wikipediaButtonText = getActivity().findViewById(R.id.wikipediaButtonText); directionsButtonText = getActivity().findViewById(R.id.directionsButtonText); commonsButtonText = getActivity().findViewById(R.id.commonsButtonText); } private void setListeners() { fabPlus.setOnClickListener(view -> animateFAB(isFabOpen)); bottomSheetDetails.setOnClickListener(view -> { if (bottomSheetDetailsBehavior.getState() == BottomSheetBehavior.STATE_COLLAPSED) { bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_EXPANDED); } else { bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); } }); fabRecenter.setOnClickListener(view -> { if (curLatLng != null) { mapView.getMapAsync(mapboxMap -> { CameraPosition position; if(ViewUtil.isPortrait(getActivity())){ position = new CameraPosition.Builder() .target(isBottomListSheetExpanded ? new LatLng(curLatLng.getLatitude()- CAMERA_TARGET_SHIFT_FACTOR_PORTRAIT, curLatLng.getLongitude()) : new LatLng(curLatLng.getLatitude(), curLatLng.getLongitude(), 0)) // Sets the new camera position .zoom(isBottomListSheetExpanded ? 11 // zoom level is fixed to 11 when bottom sheet is expanded :mapboxMap.getCameraPosition().zoom) // Same zoom level .build(); }else { position = new CameraPosition.Builder() .target(isBottomListSheetExpanded ? new LatLng(curLatLng.getLatitude()- CAMERA_TARGET_SHIFT_FACTOR_LANDSCAPE, curLatLng.getLongitude()) : new LatLng(curLatLng.getLatitude(), curLatLng.getLongitude(), 0)) // Sets the new camera position .zoom(isBottomListSheetExpanded ? 11 // zoom level is fixed to 11 when bottom sheet is expanded :mapboxMap.getCameraPosition().zoom) // Same zoom level .build(); } mapboxMap.animateCamera(CameraUpdateFactory .newCameraPosition(position), 1000); }); } }); bottomSheetDetailsBehavior.setBottomSheetCallback(new BottomSheetBehavior .BottomSheetCallback() { @Override public void onStateChanged(@NonNull View bottomSheet, int newState) { prepareViewsForSheetPosition(newState); } @Override public void onSlide(@NonNull View bottomSheet, float slideOffset) { if (slideOffset >= 0) { transparentView.setAlpha(slideOffset); if (slideOffset == 1) { transparentView.setClickable(true); } else if (slideOffset == 0) { transparentView.setClickable(false); } } } }); bottomSheetListBehavior.setBottomSheetCallback(new BottomSheetBehavior .BottomSheetCallback() { @Override public void onStateChanged(@NonNull View bottomSheet, int newState) { if (newState == BottomSheetBehavior.STATE_EXPANDED) { bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); updateMapCameraAccordingToBottomSheet(true); } else { updateMapCameraAccordingToBottomSheet(false); } } @Override public void onSlide(@NonNull View bottomSheet, float slideOffset) { } }); // Remove button text if they exceed 1 line or if internal layout has not been built // Only need to check for directions button because it is the longest if (directionsButtonText.getLineCount() > 1 || directionsButtonText.getLineCount() == 0) { wikipediaButtonText.setVisibility(View.GONE); wikidataButtonText.setVisibility(View.GONE); commonsButtonText.setVisibility(View.GONE); directionsButtonText.setVisibility(View.GONE); } } private void setupMapView(Bundle savedInstanceState) { MapboxMapOptions options = new MapboxMapOptions() .compassGravity(Gravity.BOTTOM | Gravity.LEFT) .compassMargins(new int[]{12, 0, 0, 24}) .styleUrl(Style.OUTDOORS) .logoEnabled(false) .attributionEnabled(false) .camera(new CameraPosition.Builder() .target(new LatLng(curLatLng.getLatitude(), curLatLng.getLongitude())) .zoom(11) .build()); // create map mapView = new MapView(getActivity(), options); mapView.onCreate(savedInstanceState); mapView.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(MapboxMap mapboxMap) { NearbyMapFragment.this.mapboxMap = mapboxMap; updateMapSignificantly(); } }); mapView.setStyleUrl("asset://mapstyle.json"); } /** * Adds a marker for the user's current position. Adds a * circle which uses the accuracy * 2, to draw a circle * which represents the user's position with an accuracy * of 95%. * * Should be called only on creation of mapboxMap, there * is other method to update markers location with users * move. */ private void addCurrentLocationMarker(MapboxMap mapboxMap) { if (currentLocationMarker != null) { currentLocationMarker.remove(); // Remove previous marker, we are not Hansel and Gretel } Icon icon = IconFactory.getInstance(getContext()).fromResource(R.drawable.current_location_marker); MarkerOptions currentLocationMarkerOptions = new MarkerOptions() .position(new LatLng(curLatLng.getLatitude(), curLatLng.getLongitude())); currentLocationMarkerOptions.setIcon(icon); // Set custom icon currentLocationMarker = mapboxMap.addMarker(currentLocationMarkerOptions); List<LatLng> circle = createCircleArray(curLatLng.getLatitude(), curLatLng.getLongitude(), curLatLng.getAccuracy() * 2, 100); currentLocationPolygonOptions = new PolygonOptions() .addAll(circle) .strokeColor(Color.parseColor("#55000000")) .fillColor(Color.parseColor("#11000000")); mapboxMap.addPolygon(currentLocationPolygonOptions); } private void addNearbyMarkerstoMapBoxMap() { mapboxMap.addMarkers(baseMarkerOptions); mapboxMap.setOnInfoWindowCloseListener(marker -> { if (marker == selected) { bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); } }); mapView.getMapAsync(mapboxMap -> { mapboxMap.addMarkers(baseMarkerOptions); fabRecenter.setVisibility(View.VISIBLE); mapboxMap.setOnInfoWindowCloseListener(marker -> { if (marker == selected) { bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); } }); mapboxMap.setOnMarkerClickListener(marker -> { if (marker instanceof NearbyMarker) { this.selected = marker; NearbyMarker nearbyMarker = (NearbyMarker) marker; Place place = nearbyMarker.getNearbyBaseMarker().getPlace(); passInfoToSheet(place); bottomSheetListBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); } return false; }); }); } /** * Creates a series of points that create a circle on the map. * Takes the center latitude, center longitude of the circle, * the radius in meter and the number of nodes of the circle. * * @return List List of LatLng points of the circle. */ private List<LatLng> createCircleArray( double centerLat, double centerLong, float radius, int nodes) { List<LatLng> circle = new ArrayList<>(); float radiusKilometer = radius / 1000; double radiusLong = radiusKilometer / (111.320 * Math.cos(centerLat * Math.PI / 180)); double radiusLat = radiusKilometer / 110.574; for (int i = 0; i < nodes; i++) { double theta = ((double) i / (double) nodes) * (2 * Math.PI); double nodeLongitude = centerLong + radiusLong * Math.cos(theta); double nodeLatitude = centerLat + radiusLat * Math.sin(theta); circle.add(new LatLng(nodeLatitude, nodeLongitude)); } return circle; } public void prepareViewsForSheetPosition(int bottomSheetState) { switch (bottomSheetState) { case (BottomSheetBehavior.STATE_COLLAPSED): closeFabs(isFabOpen); if (!fabPlus.isShown()) showFAB(); this.getView().requestFocus(); break; case (BottomSheetBehavior.STATE_EXPANDED): this.getView().requestFocus(); break; case (BottomSheetBehavior.STATE_HIDDEN): mapView.getMapAsync(MapboxMap::deselectMarkers); transparentView.setClickable(false); transparentView.setAlpha(0); closeFabs(isFabOpen); hideFAB(); if (this.getView() != null) { this.getView().requestFocus(); } break; } } private void hideFAB() { removeAnchorFromFABs(fabPlus); fabPlus.hide(); removeAnchorFromFABs(fabCamera); fabCamera.hide(); removeAnchorFromFABs(fabGallery); fabGallery.hide(); } /* * We are not able to hide FABs without removing anchors, this method removes anchors * */ private void removeAnchorFromFABs(FloatingActionButton floatingActionButton) { //get rid of anchors //Somehow this was the only way https://stackoverflow.com/questions/32732932 // /floatingactionbutton-visible-for-sometime-even-if-visibility-is-set-to-gone CoordinatorLayout.LayoutParams param = (CoordinatorLayout.LayoutParams) floatingActionButton .getLayoutParams(); param.setAnchorId(View.NO_ID); // If we don't set them to zero, then they become visible for a moment on upper left side param.width = 0; param.height = 0; floatingActionButton.setLayoutParams(param); } private void showFAB() { addAnchorToBigFABs(fabPlus, getActivity().findViewById(R.id.bottom_sheet_details).getId()); fabPlus.show(); addAnchorToSmallFABs(fabGallery, getActivity().findViewById(R.id.empty_view).getId()); addAnchorToSmallFABs(fabCamera, getActivity().findViewById(R.id.empty_view1).getId()); } /* * Add anchors back before making them visible again. * */ private void addAnchorToBigFABs(FloatingActionButton floatingActionButton, int anchorID) { CoordinatorLayout.LayoutParams params = new CoordinatorLayout.LayoutParams (ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT); params.setAnchorId(anchorID); params.anchorGravity = Gravity.TOP|Gravity.RIGHT|Gravity.END; floatingActionButton.setLayoutParams(params); } /* * Add anchors back before making them visible again. Big and small fabs have different anchor * gravities, therefore the are two methods. * */ private void addAnchorToSmallFABs(FloatingActionButton floatingActionButton, int anchorID) { CoordinatorLayout.LayoutParams params = new CoordinatorLayout.LayoutParams (ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT); params.setAnchorId(anchorID); params.anchorGravity = Gravity.CENTER_HORIZONTAL; floatingActionButton.setLayoutParams(params); } private void passInfoToSheet(Place place) { this.place = place; wikipediaButton.setEnabled(place.hasWikipediaLink()); wikipediaButton.setOnClickListener(view -> openWebView(place.siteLinks.getWikipediaLink())); wikidataButton.setEnabled(place.hasWikidataLink()); wikidataButton.setOnClickListener(view -> openWebView(place.siteLinks.getWikidataLink())); directionsButton.setOnClickListener(view -> { //Open map app at given position Intent mapIntent = new Intent(Intent.ACTION_VIEW, this.place.location.getGmmIntentUri()); if (mapIntent.resolveActivity(getActivity().getPackageManager()) != null) { startActivity(mapIntent); } }); commonsButton.setEnabled(place.hasCommonsLink()); commonsButton.setOnClickListener(view -> openWebView(place.siteLinks.getCommonsLink())); icon.setImageResource(place.getLabel().getIcon()); title.setText(place.name); distance.setText(place.distance); description.setText(place.getLongDescription()); title.setText(place.name.toString()); distance.setText(place.distance.toString()); fabCamera.setOnClickListener(view -> { if (fabCamera.isShown()) { Timber.d("Camera button tapped. Image title: " + place.getName() + "Image desc: " + place.getLongDescription()); storeSharedPrefs(); directUpload.initiateCameraUpload(); } }); fabGallery.setOnClickListener(view -> { if (fabGallery.isShown()) { Timber.d("Gallery button tapped. Image title: " + place.getName() + "Image desc: " + place.getLongDescription()); storeSharedPrefs(); directUpload.initiateGalleryUpload(); } }); } void storeSharedPrefs() { SharedPreferences.Editor editor = directPrefs.edit(); editor.putString("Title", place.getName()); editor.putString("Desc", place.getLongDescription()); editor.putString("Category", place.getCategory()); editor.apply(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { Timber.d("onRequestPermissionsResult: req code = " + " perm = " + permissions + " grant =" + grantResults); // Do not use requestCode 1 as it will conflict with NearbyActivity's requestCodes switch (requestCode) { // 4 = "Read external storage" allowed when gallery selected case 4: { if (grantResults.length > 0 && grantResults[0] == PERMISSION_GRANTED) { Timber.d("Call controller.startGalleryPick()"); controller.startGalleryPick(); } } break; // 5 = "Write external storage" allowed when camera selected case 5: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Timber.d("Call controller.startCameraCapture()"); controller.startCameraCapture(); } } } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { Timber.d("OnActivityResult() parameters: Req code: %d Result code: %d Data: %s", requestCode, resultCode, data); controller.handleImagePicked(requestCode, data, true); } else { Timber.e("OnActivityResult() parameters: Req code: %d Result code: %d Data: %s", requestCode, resultCode, data); } } private void openWebView(Uri link) { Utils.handleWebUrl(getContext(), link); } private void animateFAB(boolean isFabOpen) { this.isFabOpen = !isFabOpen; if (fabPlus.isShown()){ if (isFabOpen) { fabPlus.startAnimation(rotate_backward); fabCamera.startAnimation(fab_close); fabGallery.startAnimation(fab_close); fabCamera.hide(); fabGallery.hide(); } else { fabPlus.startAnimation(rotate_forward); fabCamera.startAnimation(fab_open); fabGallery.startAnimation(fab_open); fabCamera.show(); fabGallery.show(); } this.isFabOpen=!isFabOpen; } } private void closeFabs ( boolean isFabOpen){ if (isFabOpen) { fabPlus.startAnimation(rotate_backward); fabCamera.startAnimation(fab_close); fabGallery.startAnimation(fab_close); fabCamera.hide(); fabGallery.hide(); this.isFabOpen = !isFabOpen; } } public void setBundleForUpdtes(Bundle bundleForUpdtes) { this.bundleForUpdtes = bundleForUpdtes; } @Override public void onStart() { if (mapView != null) { mapView.onStart(); } super.onStart(); } @Override public void onPause() { if (mapView != null) { mapView.onPause(); } super.onPause(); } @Override public void onResume() { super.onResume(); if (mapView != null) { mapView.onResume(); } initViews(); setListeners(); transparentView.setClickable(false); transparentView.setAlpha(0); } @Override public void onStop() { if (mapView != null) { mapView.onStop(); } super.onStop(); } @Override public void onDestroyView() { if (mapView != null) { mapView.onDestroy(); } selected = null; currentLocationMarker = null; super.onDestroyView(); } private static class LatLngEvaluator implements TypeEvaluator<LatLng> { // Method is used to interpolate the marker animation. private LatLng latLng = new LatLng(); @Override public LatLng evaluate(float fraction, LatLng startValue, LatLng endValue) { latLng.setLatitude(startValue.getLatitude() + ((endValue.getLatitude() - startValue.getLatitude()) * fraction)); latLng.setLongitude(startValue.getLongitude() + ((endValue.getLongitude() - startValue.getLongitude()) * fraction)); return latLng; } } }
app/src/main/java/fr/free/nrw/commons/nearby/NearbyMapFragment.java
package fr.free.nrw.commons.nearby; import android.animation.ObjectAnimator; import android.animation.TypeEvaluator; import android.animation.ValueAnimator; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.BottomSheetBehavior; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import com.mapbox.mapboxsdk.Mapbox; import com.mapbox.mapboxsdk.annotations.Icon; import com.mapbox.mapboxsdk.annotations.IconFactory; import com.mapbox.mapboxsdk.annotations.Marker; import com.mapbox.mapboxsdk.annotations.MarkerOptions; import com.mapbox.mapboxsdk.annotations.PolygonOptions; import com.mapbox.mapboxsdk.camera.CameraPosition; import com.mapbox.mapboxsdk.camera.CameraUpdateFactory; import com.mapbox.mapboxsdk.constants.Style; import com.mapbox.mapboxsdk.geometry.LatLng; import com.mapbox.mapboxsdk.maps.MapView; import com.mapbox.mapboxsdk.maps.MapboxMap; import com.mapbox.mapboxsdk.maps.MapboxMapOptions; import com.mapbox.mapboxsdk.maps.OnMapReadyCallback; import com.mapbox.services.android.telemetry.MapboxTelemetry; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import javax.inject.Named; import dagger.android.support.DaggerFragment; import fr.free.nrw.commons.R; import fr.free.nrw.commons.Utils; import fr.free.nrw.commons.contributions.ContributionController; import fr.free.nrw.commons.utils.UriDeserializer; import fr.free.nrw.commons.utils.ViewUtil; import timber.log.Timber; import static android.app.Activity.RESULT_OK; import static android.content.pm.PackageManager.PERMISSION_GRANTED; public class NearbyMapFragment extends DaggerFragment { private MapView mapView; private List<NearbyBaseMarker> baseMarkerOptions; private fr.free.nrw.commons.location.LatLng curLatLng; public fr.free.nrw.commons.location.LatLng[] boundaryCoordinates; private View bottomSheetList; private View bottomSheetDetails; private BottomSheetBehavior bottomSheetListBehavior; private BottomSheetBehavior bottomSheetDetailsBehavior; private LinearLayout wikipediaButton; private LinearLayout wikidataButton; private LinearLayout directionsButton; private LinearLayout commonsButton; private FloatingActionButton fabPlus; private FloatingActionButton fabCamera; private FloatingActionButton fabGallery; private FloatingActionButton fabRecenter; private View transparentView; private TextView description; private TextView title; private TextView distance; private ImageView icon; private TextView wikipediaButtonText; private TextView wikidataButtonText; private TextView commonsButtonText; private TextView directionsButtonText; private boolean isFabOpen = false; private Animation rotate_backward; private Animation fab_close; private Animation fab_open; private Animation rotate_forward; private ContributionController controller; private DirectUpload directUpload; private Place place; private Marker selected; private Marker currentLocationMarker; private MapboxMap mapboxMap; private PolygonOptions currentLocationPolygonOptions; private boolean isBottomListSheetExpanded; private final double CAMERA_TARGET_SHIFT_FACTOR_PORTRAIT = 0.06; private final double CAMERA_TARGET_SHIFT_FACTOR_LANDSCAPE = 0.04; private Bundle bundleForUpdtes;// Carry information from activity about changed nearby places and current location @Inject @Named("prefs") SharedPreferences prefs; @Inject @Named("direct_nearby_upload_prefs") SharedPreferences directPrefs; public NearbyMapFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Timber.d("Nearby map fragment created"); controller = new ContributionController(this); directUpload = new DirectUpload(this, controller); Bundle bundle = this.getArguments(); Gson gson = new GsonBuilder() .registerTypeAdapter(Uri.class, new UriDeserializer()) .create(); if (bundle != null) { String gsonPlaceList = bundle.getString("PlaceList"); String gsonLatLng = bundle.getString("CurLatLng"); Type listType = new TypeToken<List<Place>>() { }.getType(); String gsonBoundaryCoordinates = bundle.getString("BoundaryCoord"); List<Place> placeList = gson.fromJson(gsonPlaceList, listType); Type curLatLngType = new TypeToken<fr.free.nrw.commons.location.LatLng>() { }.getType(); Type gsonBoundaryCoordinatesType = new TypeToken<fr.free.nrw.commons.location.LatLng[]>() {}.getType(); curLatLng = gson.fromJson(gsonLatLng, curLatLngType); baseMarkerOptions = NearbyController .loadAttractionsFromLocationToBaseMarkerOptions(curLatLng, placeList, getActivity()); boundaryCoordinates = gson.fromJson(gsonBoundaryCoordinates, gsonBoundaryCoordinatesType); } if (curLatLng != null) { Mapbox.getInstance(getActivity(), getString(R.string.mapbox_commons_app_token)); MapboxTelemetry.getInstance().setTelemetryEnabled(false); } setRetainInstance(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Timber.d("onCreateView called"); if (curLatLng != null) { Timber.d("curLatLng found, setting up map view..."); setupMapView(savedInstanceState); } setHasOptionsMenu(false); return mapView; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); this.getView().setFocusableInTouchMode(true); this.getView().requestFocus(); this.getView().setOnKeyListener((v, keyCode, event) -> { if (keyCode == KeyEvent.KEYCODE_BACK) { if (bottomSheetDetailsBehavior.getState() == BottomSheetBehavior .STATE_EXPANDED) { bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); return true; } else if (bottomSheetDetailsBehavior.getState() == BottomSheetBehavior .STATE_COLLAPSED) { bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); mapView.getMapAsync(MapboxMap::deselectMarkers); selected = null; return true; } } return false; }); } public void updateMapSlightly() { if (mapboxMap != null) { Gson gson = new GsonBuilder() .registerTypeAdapter(Uri.class, new UriDeserializer()) .create(); if (bundleForUpdtes != null) { String gsonLatLng = bundleForUpdtes.getString("CurLatLng"); Type curLatLngType = new TypeToken<fr.free.nrw.commons.location.LatLng>() {}.getType(); curLatLng = gson.fromJson(gsonLatLng, curLatLngType); } updateMapToTrackPosition(); } } public void updateMapSignificantly() { if (mapboxMap != null) { if (bundleForUpdtes != null) { Gson gson = new GsonBuilder() .registerTypeAdapter(Uri.class, new UriDeserializer()) .create(); String gsonPlaceList = bundleForUpdtes.getString("PlaceList"); String gsonLatLng = bundleForUpdtes.getString("CurLatLng"); String gsonBoundaryCoordinates = bundleForUpdtes.getString("BoundaryCoord"); Type listType = new TypeToken<List<Place>>() {}.getType(); List<Place> placeList = gson.fromJson(gsonPlaceList, listType); Type curLatLngType = new TypeToken<fr.free.nrw.commons.location.LatLng>() {}.getType(); Type gsonBoundaryCoordinatesType = new TypeToken<fr.free.nrw.commons.location.LatLng[]>() {}.getType(); curLatLng = gson.fromJson(gsonLatLng, curLatLngType); baseMarkerOptions = NearbyController .loadAttractionsFromLocationToBaseMarkerOptions(curLatLng, placeList, getActivity()); boundaryCoordinates = gson.fromJson(gsonBoundaryCoordinates, gsonBoundaryCoordinatesType); } mapboxMap.clear(); addCurrentLocationMarker(mapboxMap); updateMapToTrackPosition(); addNearbyMarkerstoMapBoxMap(); } } // Only update current position marker and camera view private void updateMapToTrackPosition() { if (currentLocationMarker != null) { LatLng curMapBoxLatLng = new LatLng(curLatLng.getLatitude(),curLatLng.getLongitude()); ValueAnimator markerAnimator = ObjectAnimator.ofObject(currentLocationMarker, "position", new LatLngEvaluator(), currentLocationMarker.getPosition(), curMapBoxLatLng); markerAnimator.setDuration(1000); markerAnimator.start(); List<LatLng> circle = createCircleArray(curLatLng.getLatitude(), curLatLng.getLongitude(), curLatLng.getAccuracy() * 2, 100); if (currentLocationPolygonOptions != null){ mapboxMap.removePolygon(currentLocationPolygonOptions.getPolygon()); currentLocationPolygonOptions = new PolygonOptions() .addAll(circle) .strokeColor(Color.parseColor("#55000000")) .fillColor(Color.parseColor("#11000000")); mapboxMap.addPolygon(currentLocationPolygonOptions); } // Make camera to follow user on location change CameraPosition position ; if(ViewUtil.isPortrait(getActivity())){ position = new CameraPosition.Builder() .target(isBottomListSheetExpanded ? new LatLng(curMapBoxLatLng.getLatitude()- CAMERA_TARGET_SHIFT_FACTOR_PORTRAIT, curMapBoxLatLng.getLongitude()) : curMapBoxLatLng ) // Sets the new camera position .zoom(isBottomListSheetExpanded ? 11 // zoom level is fixed to 11 when bottom sheet is expanded :mapboxMap.getCameraPosition().zoom) // Same zoom level .build(); }else { position = new CameraPosition.Builder() .target(isBottomListSheetExpanded ? new LatLng(curMapBoxLatLng.getLatitude()- CAMERA_TARGET_SHIFT_FACTOR_LANDSCAPE, curMapBoxLatLng.getLongitude()) : curMapBoxLatLng ) // Sets the new camera position .zoom(isBottomListSheetExpanded ? 11 // zoom level is fixed to 11 when bottom sheet is expanded :mapboxMap.getCameraPosition().zoom) // Same zoom level .build(); } mapboxMap.animateCamera(CameraUpdateFactory .newCameraPosition(position), 1000); } } private void updateMapCameraAccordingToBottomSheet(boolean isBottomListSheetExpanded) { CameraPosition position; this.isBottomListSheetExpanded = isBottomListSheetExpanded; if (mapboxMap != null && curLatLng != null) { if (isBottomListSheetExpanded) { // Make camera to follow user on location change if(ViewUtil.isPortrait(getActivity())) { position = new CameraPosition.Builder() .target(new LatLng(curLatLng.getLatitude() - CAMERA_TARGET_SHIFT_FACTOR_PORTRAIT, curLatLng.getLongitude())) // Sets the new camera target above // current to make it visible when sheet is expanded .zoom(11) // Fixed zoom level .build(); } else { position = new CameraPosition.Builder() .target(new LatLng(curLatLng.getLatitude() - CAMERA_TARGET_SHIFT_FACTOR_LANDSCAPE, curLatLng.getLongitude())) // Sets the new camera target above // current to make it visible when sheet is expanded .zoom(11) // Fixed zoom level .build(); } } else { // Make camera to follow user on location change position = new CameraPosition.Builder() .target(new LatLng(curLatLng.getLatitude(), curLatLng.getLongitude())) // Sets the new camera target to curLatLng .zoom(mapboxMap.getCameraPosition().zoom) // Same zoom level .build(); } mapboxMap.animateCamera(CameraUpdateFactory .newCameraPosition(position), 1000); } } private void initViews() { bottomSheetList = getActivity().findViewById(R.id.bottom_sheet); bottomSheetListBehavior = BottomSheetBehavior.from(bottomSheetList); bottomSheetDetails = getActivity().findViewById(R.id.bottom_sheet_details); bottomSheetDetailsBehavior = BottomSheetBehavior.from(bottomSheetDetails); bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); bottomSheetDetails.setVisibility(View.VISIBLE); fabPlus = getActivity().findViewById(R.id.fab_plus); fabCamera = getActivity().findViewById(R.id.fab_camera); fabGallery = getActivity().findViewById(R.id.fab_galery); fabRecenter = getActivity().findViewById(R.id.fab_recenter); fab_open = AnimationUtils.loadAnimation(getActivity(), R.anim.fab_open); fab_close = AnimationUtils.loadAnimation(getActivity(), R.anim.fab_close); rotate_forward = AnimationUtils.loadAnimation(getActivity(), R.anim.rotate_forward); rotate_backward = AnimationUtils.loadAnimation(getActivity(), R.anim.rotate_backward); transparentView = getActivity().findViewById(R.id.transparentView); description = getActivity().findViewById(R.id.description); title = getActivity().findViewById(R.id.title); distance = getActivity().findViewById(R.id.category); icon = getActivity().findViewById(R.id.icon); wikidataButton = getActivity().findViewById(R.id.wikidataButton); wikipediaButton = getActivity().findViewById(R.id.wikipediaButton); directionsButton = getActivity().findViewById(R.id.directionsButton); commonsButton = getActivity().findViewById(R.id.commonsButton); wikidataButtonText = getActivity().findViewById(R.id.wikidataButtonText); wikipediaButtonText = getActivity().findViewById(R.id.wikipediaButtonText); directionsButtonText = getActivity().findViewById(R.id.directionsButtonText); commonsButtonText = getActivity().findViewById(R.id.commonsButtonText); } private void setListeners() { fabPlus.setOnClickListener(view -> animateFAB(isFabOpen)); bottomSheetDetails.setOnClickListener(view -> { if (bottomSheetDetailsBehavior.getState() == BottomSheetBehavior.STATE_COLLAPSED) { bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_EXPANDED); } else { bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); } }); fabRecenter.setOnClickListener(view -> { if (curLatLng != null) { mapView.getMapAsync(mapboxMap -> { CameraPosition position; if(ViewUtil.isPortrait(getActivity())){ position = new CameraPosition.Builder() .target(isBottomListSheetExpanded ? new LatLng(curLatLng.getLatitude()- CAMERA_TARGET_SHIFT_FACTOR_PORTRAIT, curLatLng.getLongitude()) : new LatLng(curLatLng.getLatitude(), curLatLng.getLongitude(), 0)) // Sets the new camera position .zoom(isBottomListSheetExpanded ? 11 // zoom level is fixed to 11 when bottom sheet is expanded :mapboxMap.getCameraPosition().zoom) // Same zoom level .build(); }else { position = new CameraPosition.Builder() .target(isBottomListSheetExpanded ? new LatLng(curLatLng.getLatitude()- CAMERA_TARGET_SHIFT_FACTOR_LANDSCAPE, curLatLng.getLongitude()) : new LatLng(curLatLng.getLatitude(), curLatLng.getLongitude(), 0)) // Sets the new camera position .zoom(isBottomListSheetExpanded ? 11 // zoom level is fixed to 11 when bottom sheet is expanded :mapboxMap.getCameraPosition().zoom) // Same zoom level .build(); } mapboxMap.animateCamera(CameraUpdateFactory .newCameraPosition(position), 1000); }); } }); bottomSheetDetailsBehavior.setBottomSheetCallback(new BottomSheetBehavior .BottomSheetCallback() { @Override public void onStateChanged(@NonNull View bottomSheet, int newState) { prepareViewsForSheetPosition(newState); } @Override public void onSlide(@NonNull View bottomSheet, float slideOffset) { if (slideOffset >= 0) { transparentView.setAlpha(slideOffset); if (slideOffset == 1) { transparentView.setClickable(true); } else if (slideOffset == 0) { transparentView.setClickable(false); } } } }); bottomSheetListBehavior.setBottomSheetCallback(new BottomSheetBehavior .BottomSheetCallback() { @Override public void onStateChanged(@NonNull View bottomSheet, int newState) { if (newState == BottomSheetBehavior.STATE_EXPANDED) { bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); updateMapCameraAccordingToBottomSheet(true); } else { updateMapCameraAccordingToBottomSheet(false); } } @Override public void onSlide(@NonNull View bottomSheet, float slideOffset) { } }); // Remove button text if they exceed 1 line or if internal layout has not been built // Only need to check for directions button because it is the longest if (directionsButtonText.getLineCount() > 1 || directionsButtonText.getLineCount() == 0) { wikipediaButtonText.setVisibility(View.GONE); wikidataButtonText.setVisibility(View.GONE); commonsButtonText.setVisibility(View.GONE); directionsButtonText.setVisibility(View.GONE); } } private void setupMapView(Bundle savedInstanceState) { MapboxMapOptions options = new MapboxMapOptions() .compassGravity(Gravity.BOTTOM | Gravity.LEFT) .compassMargins(new int[]{12, 0, 0, 24}) .styleUrl(Style.OUTDOORS) .logoEnabled(false) .attributionEnabled(false) .camera(new CameraPosition.Builder() .target(new LatLng(curLatLng.getLatitude(), curLatLng.getLongitude())) .zoom(11) .build()); // create map mapView = new MapView(getActivity(), options); mapView.onCreate(savedInstanceState); mapView.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(MapboxMap mapboxMap) { NearbyMapFragment.this.mapboxMap = mapboxMap; updateMapSignificantly(); } }); mapView.setStyleUrl("asset://mapstyle.json"); } /** * Adds a marker for the user's current position. Adds a * circle which uses the accuracy * 2, to draw a circle * which represents the user's position with an accuracy * of 95%. * * Should be called only on creation of mapboxMap, there * is other method to update markers location with users * move. */ private void addCurrentLocationMarker(MapboxMap mapboxMap) { if (currentLocationMarker != null) { currentLocationMarker.remove(); // Remove previous marker, we are not Hansel and Gretel } Icon icon = IconFactory.getInstance(getContext()).fromResource(R.drawable.current_location_marker); MarkerOptions currentLocationMarkerOptions = new MarkerOptions() .position(new LatLng(curLatLng.getLatitude(), curLatLng.getLongitude())); currentLocationMarkerOptions.setIcon(icon); // Set custom icon currentLocationMarker = mapboxMap.addMarker(currentLocationMarkerOptions); List<LatLng> circle = createCircleArray(curLatLng.getLatitude(), curLatLng.getLongitude(), curLatLng.getAccuracy() * 2, 100); currentLocationPolygonOptions = new PolygonOptions() .addAll(circle) .strokeColor(Color.parseColor("#55000000")) .fillColor(Color.parseColor("#11000000")); mapboxMap.addPolygon(currentLocationPolygonOptions); } private void addNearbyMarkerstoMapBoxMap() { mapboxMap.addMarkers(baseMarkerOptions); mapboxMap.setOnInfoWindowCloseListener(marker -> { if (marker == selected) { bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); } }); mapView.getMapAsync(mapboxMap -> { mapboxMap.addMarkers(baseMarkerOptions); fabRecenter.setVisibility(View.VISIBLE); mapboxMap.setOnInfoWindowCloseListener(marker -> { if (marker == selected) { bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); } }); mapboxMap.setOnMarkerClickListener(marker -> { if (marker instanceof NearbyMarker) { this.selected = marker; NearbyMarker nearbyMarker = (NearbyMarker) marker; Place place = nearbyMarker.getNearbyBaseMarker().getPlace(); passInfoToSheet(place); bottomSheetListBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); } return false; }); }); } /** * Creates a series of points that create a circle on the map. * Takes the center latitude, center longitude of the circle, * the radius in meter and the number of nodes of the circle. * * @return List List of LatLng points of the circle. */ private List<LatLng> createCircleArray( double centerLat, double centerLong, float radius, int nodes) { List<LatLng> circle = new ArrayList<>(); float radiusKilometer = radius / 1000; double radiusLong = radiusKilometer / (111.320 * Math.cos(centerLat * Math.PI / 180)); double radiusLat = radiusKilometer / 110.574; for (int i = 0; i < nodes; i++) { double theta = ((double) i / (double) nodes) * (2 * Math.PI); double nodeLongitude = centerLong + radiusLong * Math.cos(theta); double nodeLatitude = centerLat + radiusLat * Math.sin(theta); circle.add(new LatLng(nodeLatitude, nodeLongitude)); } return circle; } public void prepareViewsForSheetPosition(int bottomSheetState) { switch (bottomSheetState) { case (BottomSheetBehavior.STATE_COLLAPSED): closeFabs(isFabOpen); if (!fabPlus.isShown()) showFAB(); this.getView().requestFocus(); break; case (BottomSheetBehavior.STATE_EXPANDED): this.getView().requestFocus(); break; case (BottomSheetBehavior.STATE_HIDDEN): mapView.getMapAsync(MapboxMap::deselectMarkers); transparentView.setClickable(false); transparentView.setAlpha(0); closeFabs(isFabOpen); hideFAB(); if (this.getView() != null) { this.getView().requestFocus(); } break; } } private void hideFAB() { removeAnchorFromFABs(fabPlus); fabPlus.hide(); removeAnchorFromFABs(fabCamera); fabCamera.hide(); removeAnchorFromFABs(fabGallery); fabGallery.hide(); } /* * We are not able to hide FABs without removing anchors, this method removes anchors * */ private void removeAnchorFromFABs(FloatingActionButton floatingActionButton) { //get rid of anchors //Somehow this was the only way https://stackoverflow.com/questions/32732932 // /floatingactionbutton-visible-for-sometime-even-if-visibility-is-set-to-gone CoordinatorLayout.LayoutParams param = (CoordinatorLayout.LayoutParams) floatingActionButton .getLayoutParams(); param.setAnchorId(View.NO_ID); // If we don't set them to zero, then they become visible for a moment on upper left side param.width = 0; param.height = 0; floatingActionButton.setLayoutParams(param); } private void showFAB() { addAnchorToBigFABs(fabPlus, getActivity().findViewById(R.id.bottom_sheet_details).getId()); fabPlus.show(); addAnchorToSmallFABs(fabGallery, getActivity().findViewById(R.id.empty_view).getId()); addAnchorToSmallFABs(fabCamera, getActivity().findViewById(R.id.empty_view1).getId()); } /* * Add anchors back before making them visible again. * */ private void addAnchorToBigFABs(FloatingActionButton floatingActionButton, int anchorID) { CoordinatorLayout.LayoutParams params = new CoordinatorLayout.LayoutParams (ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT); params.setAnchorId(anchorID); params.anchorGravity = Gravity.TOP|Gravity.RIGHT|Gravity.END; floatingActionButton.setLayoutParams(params); } /* * Add anchors back before making them visible again. Big and small fabs have different anchor * gravities, therefore the are two methods. * */ private void addAnchorToSmallFABs(FloatingActionButton floatingActionButton, int anchorID) { CoordinatorLayout.LayoutParams params = new CoordinatorLayout.LayoutParams (ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT); params.setAnchorId(anchorID); params.anchorGravity = Gravity.CENTER_HORIZONTAL; floatingActionButton.setLayoutParams(params); } private void passInfoToSheet(Place place) { this.place = place; wikipediaButton.setEnabled(place.hasWikipediaLink()); wikipediaButton.setOnClickListener(view -> openWebView(place.siteLinks.getWikipediaLink())); wikidataButton.setEnabled(place.hasWikidataLink()); wikidataButton.setOnClickListener(view -> openWebView(place.siteLinks.getWikidataLink())); directionsButton.setOnClickListener(view -> { //Open map app at given position Intent mapIntent = new Intent(Intent.ACTION_VIEW, place.location.getGmmIntentUri()); if (mapIntent.resolveActivity(getActivity().getPackageManager()) != null) { startActivity(mapIntent); } }); commonsButton.setEnabled(place.hasCommonsLink()); commonsButton.setOnClickListener(view -> openWebView(place.siteLinks.getCommonsLink())); icon.setImageResource(place.getLabel().getIcon()); title.setText(place.name); distance.setText(place.distance); description.setText(place.getLongDescription()); title.setText(place.name.toString()); distance.setText(place.distance.toString()); fabCamera.setOnClickListener(view -> { if (fabCamera.isShown()) { Timber.d("Camera button tapped. Image title: " + place.getName() + "Image desc: " + place.getLongDescription()); storeSharedPrefs(); directUpload.initiateCameraUpload(); } }); fabGallery.setOnClickListener(view -> { if (fabGallery.isShown()) { Timber.d("Gallery button tapped. Image title: " + place.getName() + "Image desc: " + place.getLongDescription()); storeSharedPrefs(); directUpload.initiateGalleryUpload(); } }); } void storeSharedPrefs() { SharedPreferences.Editor editor = directPrefs.edit(); editor.putString("Title", place.getName()); editor.putString("Desc", place.getLongDescription()); editor.putString("Category", place.getCategory()); editor.apply(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { Timber.d("onRequestPermissionsResult: req code = " + " perm = " + permissions + " grant =" + grantResults); // Do not use requestCode 1 as it will conflict with NearbyActivity's requestCodes switch (requestCode) { // 4 = "Read external storage" allowed when gallery selected case 4: { if (grantResults.length > 0 && grantResults[0] == PERMISSION_GRANTED) { Timber.d("Call controller.startGalleryPick()"); controller.startGalleryPick(); } } break; // 5 = "Write external storage" allowed when camera selected case 5: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Timber.d("Call controller.startCameraCapture()"); controller.startCameraCapture(); } } } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { Timber.d("OnActivityResult() parameters: Req code: %d Result code: %d Data: %s", requestCode, resultCode, data); controller.handleImagePicked(requestCode, data, true); } else { Timber.e("OnActivityResult() parameters: Req code: %d Result code: %d Data: %s", requestCode, resultCode, data); } } private void openWebView(Uri link) { Utils.handleWebUrl(getContext(), link); } private void animateFAB(boolean isFabOpen) { this.isFabOpen = !isFabOpen; if (fabPlus.isShown()){ if (isFabOpen) { fabPlus.startAnimation(rotate_backward); fabCamera.startAnimation(fab_close); fabGallery.startAnimation(fab_close); fabCamera.hide(); fabGallery.hide(); } else { fabPlus.startAnimation(rotate_forward); fabCamera.startAnimation(fab_open); fabGallery.startAnimation(fab_open); fabCamera.show(); fabGallery.show(); } this.isFabOpen=!isFabOpen; } } private void closeFabs ( boolean isFabOpen){ if (isFabOpen) { fabPlus.startAnimation(rotate_backward); fabCamera.startAnimation(fab_close); fabGallery.startAnimation(fab_close); fabCamera.hide(); fabGallery.hide(); this.isFabOpen = !isFabOpen; } } public void setBundleForUpdtes(Bundle bundleForUpdtes) { this.bundleForUpdtes = bundleForUpdtes; } @Override public void onStart() { if (mapView != null) { mapView.onStart(); } super.onStart(); } @Override public void onPause() { if (mapView != null) { mapView.onPause(); } super.onPause(); } @Override public void onResume() { super.onResume(); if (mapView != null) { mapView.onResume(); } initViews(); setListeners(); transparentView.setClickable(false); transparentView.setAlpha(0); } @Override public void onStop() { if (mapView != null) { mapView.onStop(); } super.onStop(); } @Override public void onDestroyView() { if (mapView != null) { mapView.onDestroy(); } selected = null; currentLocationMarker = null; super.onDestroyView(); } private static class LatLngEvaluator implements TypeEvaluator<LatLng> { // Method is used to interpolate the marker animation. private LatLng latLng = new LatLng(); @Override public LatLng evaluate(float fraction, LatLng startValue, LatLng endValue) { latLng.setLatitude(startValue.getLatitude() + ((endValue.getLatitude() - startValue.getLatitude()) * fraction)); latLng.setLongitude(startValue.getLongitude() + ((endValue.getLongitude() - startValue.getLongitude()) * fraction)); return latLng; } } }
Fix for #1437 :Button that opens Google Maps shows always only the coordinates of the first chosen mark (#1446)
app/src/main/java/fr/free/nrw/commons/nearby/NearbyMapFragment.java
Fix for #1437 :Button that opens Google Maps shows always only the coordinates of the first chosen mark (#1446)
<ide><path>pp/src/main/java/fr/free/nrw/commons/nearby/NearbyMapFragment.java <ide> <ide> directionsButton.setOnClickListener(view -> { <ide> //Open map app at given position <del> Intent mapIntent = new Intent(Intent.ACTION_VIEW, place.location.getGmmIntentUri()); <add> Intent mapIntent = new Intent(Intent.ACTION_VIEW, this.place.location.getGmmIntentUri()); <ide> if (mapIntent.resolveActivity(getActivity().getPackageManager()) != null) { <ide> startActivity(mapIntent); <ide> }
Java
mit
6852c49eca907326b013b1d95d8420726a338c58
0
kevinsprong23/gamesolver
package com.kevinsprong.gamesolver; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; /** * Extension of TwoPlayerGame to play the game Threes! */ public class Threes extends TwoPlayerGame { // expose weights for tuning private double[] heuristicWeights = {5000, 1, 10, 5}; // getter and setter public double[] getHeuristicWeights() { return this.heuristicWeights; } public void setHeuristicWeights(double[] heuristicWeightsIn) { this.heuristicWeights = heuristicWeightsIn; } // constructors public Threes() { this.setP1MoveStrat("AlphaBeta"); this.setP2MoveStrat("DefaultComputer"); // solver parameters this.setSearchPly(6); this.setSearchTime(10000); // milliseconds this.setWinCondition(6144); // initialize game state GameState newGameState = new GameState(); int[][] blankBoard = {{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}}; newGameState.setBoardState(blankBoard); this.setGameState(newGameState); } public Threes(String p1Strat, String p2Strat) { this.setP1MoveStrat(p1Strat); this.setP2MoveStrat(p2Strat); // solver parameters this.setSearchPly(6); this.setSearchTime(10000); // milliseconds this.setWinCondition(6144); // initialize game state GameState newGameState = new GameState(); int[][] blankBoard = {{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}}; newGameState.setBoardState(blankBoard); this.setGameState(newGameState); } public Threes(String p1Strat, String p2Strat, int searchPly, int searchTime) { this.setP1MoveStrat(p1Strat); this.setP2MoveStrat(p2Strat); // solver parameters this.setSearchPly(searchPly); this.setSearchTime(searchTime); // milliseconds this.setWinCondition(6144); // initialize game state GameState newGameState = new GameState(); int[][] blankBoard = {{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}}; newGameState.setBoardState(blankBoard); this.setGameState(newGameState); } public Threes(String p1Strat, String p2Strat, int searchPly, int searchTime, int winCondition) { this.setP1MoveStrat(p1Strat); this.setP2MoveStrat(p2Strat); // solver parameters this.setSearchPly(searchPly); this.setSearchTime(searchTime); // milliseconds this.setWinCondition(winCondition); // get to this number to win! // initialize game state GameState newGameState = new GameState(); int[][] blankBoard = {{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}}; newGameState.setBoardState(blankBoard); this.setGameState(newGameState); } // implementation of abstract methods public void initializeBoard() { GameState currentState = this.getGameState(); // three ones, three twos, three threes in random locs int[] rows = new int[9]; int[] cols = new int[9]; int[] vals = {1,1,1,2,2,2,3,3,3}; // generate random nums from 0 to 15 in loop, check against hash set, and make x/y Set<Integer> randsChosen = new HashSet<Integer>(); int numsChosen = 0; while (numsChosen < 9) { // could do fewer checks for blank spaces and have fewer, but then indexing gets hard int randInt = this.randIntInRange(0, 15); while (randsChosen.contains(randInt)) { randInt = this.randIntInRange(0, 15); } rows[numsChosen] = randInt % 4; cols[numsChosen] = randInt / 4; } // assign to game state int[][] currentBoard = currentState.getBoardState(); for(int i = 0; i < 9; i++) { currentBoard[rows[i]][cols[i]] = vals[i]; } currentState.setBoardState(currentBoard); // set remaining move stack to one of each currentState.setMoveStack(this.generateFirstMoveStack()); // assign to game state this.setGameState(currentState); } // given a game state and strategies, return next player move public void playerMove() { // get needed variables GameState currentState = this.getGameState(); String p1Strat = this.getP1MoveStrat(); String p2Strat = this.getP2MoveStrat(); if (currentState.getPlayerToMove() == 1) { // dont toggle flag until we actually update the board in other func if (p1Strat.equals("AlphaBeta")) { // use AlphaBetaSolver currentState.setP1PreviousMove(AlphaBetaSolver.solveBoard(this)); } else if (p1Strat.equals("Random")) { // copy game state so we dont overwrite any of it GameState currentStateCopy = GameState.copyGameState(currentState); // pick a random legal move String[] legalMoves = this.findLegalMoves(currentStateCopy); int idx = this.randIntInRange(0, legalMoves.length - 1); // instead of return statement currentState.setP1PreviousMove(legalMoves[idx]); } } else { if (p2Strat.equals("DefaultComputer")) { // choose a tile at random // update all of this with threes logic // choose which number(s) we will get int pt1 = this.generateNewCell(); // find zero tiles on current board and their indices ArrayList<int[]> zeroList = this.getValidComputerMoveTiles(currentState); // choose random location for tile from among zero indices int randomNum1 = this.randIntInRange(0, zeroList.size()-1); int pt1y = zeroList.get(randomNum1)[0]; int pt1x = zeroList.get(randomNum1)[1]; // instead of return statement currentState.setP2PreviousMove(Integer.toString(pt1) + "_" + Integer.toString(pt1y) + "_" + Integer.toString(pt1x)); } } } // separate method to update game board of GameState manually public GameState calcUpdatedGameState(GameState gameStateIn, String move) { // give ourselves clean object to work with GameState currentState = GameState.copyGameState(gameStateIn); int[][] currentBoard = currentState.getBoardState(); int playerMoved = currentState.getPlayerToMove(); if (playerMoved == 1) { // update depending on move if (move.equals("U")) { // move everything up one tile, collide at top. one collision per move for (int j = 0; j < 4; j++) { // find and perform collision for (int i = 1; i < 4; i++) { if (currentBoard[i][j] > 0) { if (currentBoard[i][j] == currentBoard[i-1][j]) { currentBoard[i-1][j] = 2*currentBoard[i-1][j]; currentBoard[i][j] = 0; break; } // because board(i,j) > 0 this detects a 1 and 2 if (currentBoard[i][j] + currentBoard[i-1][j] == 3) { currentBoard[i-1][j] = 3; currentBoard[i][j] = 0; break; } } } // move everything up if there is a zero above for (int i = 1; i < 4; i++) { if (currentBoard[i-1][j] == 0) { currentBoard[i-1][j] = currentBoard[i][j]; currentBoard[i][j] = 0; } } } } else if (move.equals("D")) { // move everything down one tile, collide at bottom. one collision per move for (int j = 0; j < 4; j++) { // find and perform collision for (int i = 2; i >= 0; i--) { if (currentBoard[i][j] > 0) { if (currentBoard[i][j] == currentBoard[i+1][j]) { currentBoard[i+1][j] = 2*currentBoard[i+1][j]; currentBoard[i][j] = 0; break; } // because board(i,j) > 0 this detects a 1 and 2 if (currentBoard[i][j] + currentBoard[i+1][j] == 3) { currentBoard[i+1][j] = 3; currentBoard[i][j] = 0; break; } } } // move everything down if there is a zero below for (int i = 2; i >= 0; i--) { if (currentBoard[i+1][j] == 0) { currentBoard[i+1][j] = currentBoard[i][j]; currentBoard[i][j] = 0; } } } } else if (move.equals("L")) { // move everything left one tile, collide at left. one collision per move for (int i = 0; i < 4; i++) { // find and perform collision for (int j = 1; j < 4; j++) { if (currentBoard[i][j] > 0) { if (currentBoard[i][j] == currentBoard[i][j-1]) { currentBoard[i][j-1] = 2*currentBoard[i][j-1]; currentBoard[i][j] = 0; break; } // because board(i,j) > 0 this detects a 1 and 2 if (currentBoard[i][j] + currentBoard[i][j-1] == 3) { currentBoard[i][j-1] = 3; currentBoard[i][j] = 0; break; } } } // move everything left if there is a zero adjacent for (int j = 1; j < 4; j++) { if (currentBoard[i][j-1] == 0) { currentBoard[i][j-1] = currentBoard[i][j]; currentBoard[i][j] = 0; } } } } else if (move.equals("R")) { // move everything right one tile, collide at right. one collision per move for (int i = 0; i < 4; i++) { // find and perform collision for (int j = 2; j >= 0; j--) { if (currentBoard[i][j] > 0) { if (currentBoard[i][j] == currentBoard[i][j+1]) { currentBoard[i][j+1] = 2*currentBoard[i][j+1]; currentBoard[i][j] = 0; break; } // because board(i,j) > 0 this detects a 1 and 2 if (currentBoard[i][j] + currentBoard[i][j+1] == 3) { currentBoard[i][j+1] = 3; currentBoard[i][j] = 0; break; } } } // move everything right if there is a zero adjacent for (int j = 2; j >= 0; j--) { if (currentBoard[i][j+1] == 0) { currentBoard[i][j+1] = currentBoard[i][j]; currentBoard[i][j] = 0; } } } } // assign new board back to game state currentState.setBoardState(currentBoard); // unnec. due to obj pointer pass? } else { // parse move String[] parsedMove = move.split("_"); int pt1 = Integer.parseInt(parsedMove[0]); int pt1y = Integer.parseInt(parsedMove[1]); int pt1x = Integer.parseInt(parsedMove[2]); currentBoard[pt1y][pt1x] = pt1; // assign it to the board currentState.setBoardState(currentBoard); // update move stack to zero out the move element int[] moveList = currentState.getMoveStack(); for (int j = 0; j < 12; j++) { if (moveList[j] > 0) { moveList[j] = 0; break; } if (moveList[j] == 11) { // array is all zeros; reset move stack currentState.setMoveStack(this.generateNewMoveStack()); break; } } } return currentState; } // wrapper function for calculating updated game state public void updateGameState() { // get game variables we need GameState currentState = this.getGameState(); int playerMoved = currentState.getPlayerToMove(); String currentMove = null; if (playerMoved == 1) { currentMove = currentState.getP1PreviousMove(); } else { currentMove = currentState.getP2PreviousMove(); } // this call calculates the updated board and moveStack GameState newGameState = calcUpdatedGameState(currentState, currentMove); // switch playerToMove - flip 1 to 2 and vice versa newGameState.setPlayerToMove((playerMoved % 2) + 1); // add a move to the overall list if (playerMoved == 1) { newGameState.setMoveNum(newGameState.getMoveNum() + 1); } // calculate the move and update the official game state this.setGameState(newGameState); } // given a move history, calculate the score public void updateGameScore(GameState currentState, int tileMade) { // making a tile >= 3 gives 3 ^ the multiple of 3 it is // ignore second argument, score here is solely derived from board int totalScore = 0; int[][] currentBoard = currentState.getBoardState(); for (int[] row : currentBoard) { for (int val : row) { if (val >= 3) { totalScore += Math.pow(3, (this.logb(val/3, 2) + 1)); } } } // modify currentState that we are pointing to currentState.setGameScore(totalScore); } // given a gameState and whose turn it is, find list of legal moves public String[] findLegalMoves(GameState gameStateIn) { GameState currentState = GameState.copyGameState(gameStateIn); int[][] boardOrig = currentState.getBoardState(); ArrayList<String> legalMoveList = new ArrayList<String>(); if (currentState.getPlayerToMove() == 1) { // test each move individually // test Up GameState gameStateU = this.calcUpdatedGameState(currentState, "U"); if (!checkBoardEquality(gameStateU, currentState)) { // then up was a legal move legalMoveList.add("U"); } // test Down currentState.setBoardState(boardOrig); GameState gameStateD = this.calcUpdatedGameState(currentState, "D"); if (!checkBoardEquality(gameStateD, currentState)) { legalMoveList.add("D"); } // test Left currentState.setBoardState(boardOrig); GameState gameStateL = this.calcUpdatedGameState(currentState, "L"); if (!checkBoardEquality(gameStateL, currentState)) { legalMoveList.add("L"); } // test Right currentState.setBoardState(boardOrig); GameState gameStateR = this.calcUpdatedGameState(currentState, "R"); if (!checkBoardEquality(gameStateR, currentState)) { legalMoveList.add("R"); } } else { // computer player // get the valid move tiles ArrayList<int[]> zeroList = this.getValidComputerMoveTiles(currentState); // legal moves are the top of the moveStack or the bonusMoveList, to open tiles // opposite P1's move // parse moveStack List<Integer> uniqueMoves = new ArrayList<Integer>(); int topMove = this.getGameState().getMoveStack()[1]; uniqueMoves.add(topMove); for (int bonus : this.findBonusMoves()) { uniqueMoves.add(bonus); } Integer[] legalMoveTiles = uniqueMoves.toArray( new Integer[uniqueMoves.size()]); // build list of moves for (int tile : legalMoveTiles) { // yay auto-unboxing for (int[] pos : zeroList) { legalMoveList.add(Integer.toString(tile) + "_" + Integer.toString(pos[0]) + "_" + Integer.toString(pos[1])); } } } // convert array list into array of strings return legalMoveList.toArray(new String[legalMoveList.size()]); } private ArrayList<int[]> getValidComputerMoveTiles(GameState gsIn) { ArrayList<int[]> zeroList = new ArrayList<int[]>(); // get indices of open spaces along row/col opposite move int[][] boardOrig = gsIn.getBoardState(); String p1Move = gsIn.getP1PreviousMove(); if (p1Move.equals("U")) { for (int i = 0; i < 4; i++) { if (boardOrig[3][i] > 0) { zeroList.add(new int[]{3,i}); } } } else if (p1Move.equals("D")) { for (int i = 0; i < 4; i++) { if (boardOrig[0][i] > 0) { zeroList.add(new int[]{0,i}); } } } else if (p1Move.equals("L")) { for (int i = 0; i < 4; i++) { if (boardOrig[i][3] > 0) { zeroList.add(new int[]{i,3}); } } } else if (p1Move.equals("R")) { for (int i = 0; i < 4; i++) { if (boardOrig[i][0] > 0) { zeroList.add(new int[]{i,0}); } } } return zeroList; } // determine if win condition met - returns 0, 1, 2 for no winner yet/p1/p2 public int determineWinner() { GameState currentState = GameState.copyGameState(this.getGameState()); return this.determineWinner(currentState); } // with gs argument for alpha beta calls public int determineWinner(GameState currentState) { // check loser first if (currentState.getPlayerToMove() == 1 && this.findLegalMoves(currentState).length == 0) { // can do this first since getting to p1's win condition // requires a successful move which leaves at least one empty space // (conditions don't overlap) return 2; } // find max tile on board int maxTile = getMaxTile(currentState); if (maxTile >= this.getWinCondition()) { return 1; } // if neither then p1 is still alive return 0; } // compute board evaluation public double evaluateGameState(GameState gameStateIn) { // update all of this with threes stuff int[][] board = gameStateIn.getBoardState(); // heuristics to assess board. SCORE IS RELATIVE TO HUMAN PLAYER double[] heuristicVals = {0, 0, 0, 0}; double[] heuristicWeights = this.getHeuristicWeights(); double finalScore = 0; //--------------------------------------------------------------------- // Heuristic 1: there is a win condition int winStatus = this.determineWinner(gameStateIn); if (winStatus == 1) { heuristicVals[0] = 1; } else if (winStatus == 2) { heuristicVals[0] = -1; } else { heuristicVals[0] = 0; } //--------------------------------------------------------------------- // Heuristic 2: monotonicity int[] monoScores; int totalScore = 0; // loop over rows for (int[] row : board) { monoScores = checkMonotonicity(row); totalScore += Math.max(monoScores[0], monoScores[1]); } // loop over cols int[] col = {0,0,0,0}; for (int j = 0; j < 4; j++) { for (int i = 0; i < 4; i++) { col[i] = board[i][j]; } monoScores = checkMonotonicity(col); totalScore += Math.max(monoScores[0], monoScores[1]); } heuristicVals[1] = (double) totalScore; //--------------------------------------------------------------------- // Heuristic 3: the "smoothness" of the board // in log space to account for merges needed double totalDeviation = 0; // will be negative to penalize deviation // probe rightwards for (int i = 0; i < 4; i++) { for (int j = 0; j < 3; j++) { if (board[i][j] != 0) { // probe rightwards for (int k = j+1; k < 4; k++) { // check smoothness versus first non-zero tile if (board[i][k] != 0) { totalDeviation += Math.abs(logb(board[i][j], 2) - logb(board[i][k], 2)); break; } } } } } // probe downwards for (int j = 0; j < 4; j++) { for (int i = 0; i < 3; i++) { if (board[i][j] != 0) { // probe rightwards for (int k = i+1; k < 4; k++) { // check smoothness versus first non-zero tile if (board[k][j] != 0) { totalDeviation += Math.abs(logb(board[i][j], 2) - logb(board[k][j], 2)); break; } } } } } heuristicVals[2] = -1 * totalDeviation; //--------------------------------------------------------------------- // Heuristic 4: the number of open tiles double openTiles = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (board[i][j] == 0) { openTiles += 1; } } } heuristicVals[3] = Math.pow(openTiles, 2); //--------------------------------------------------------------------- // aggregate and return for (int i = 0; i < 4; i++) { finalScore += heuristicVals[i] * heuristicWeights[i]; } return finalScore; } // check monotonicity of a vector in log space ignoring zeros private int[] checkMonotonicity(int[] vec) { int[] scores = {0,0}; // forward and reverse dir respectively for (int i = 0; i < vec.length-1; i++) { if (vec[i] > 0) { // find next non-zero element for (int j = i+1; j < vec.length; j++) { if (vec[j] > 0) { if (vec[i] >= vec[j]) { // reverse dir scores[1] += logb(vec[i], 2) - logb(vec[j], 2); } if (vec[j] >= vec[i]) { // forward dir scores[1] += logb(vec[j], 2) - logb(vec[i], 2); } break; } } } } return scores; } // generate new tile for the game public int generateNewCell() { int rand = this.randIntInRange(1,21); int output = 0; // 1/21 to return a bonus tile if (rand == 1) { int[] bonusMoves = this.findBonusMoves(); int bidx = randIntInRange(0, bonusMoves.length-1); output = bonusMoves[bidx]; } else { // 20/21 to return first non-zero tile in moveStack // find first non-zero tile of moveStack int [] moveStack = this.getGameState().getMoveStack(); for (int i = 0; i < moveStack.length; i++) { if (moveStack[i] > 0) { output = moveStack[i]; break; } } } return output; } public int[] findBonusMoves() { int bonusTiles[] = {}; // find max tile int maxTile = this.getMaxTile(this.getGameState()); if (maxTile >= 48) { // return all multiples of 6 that are between 6 and maxTile/8 int maxTileMult = maxTile / 8 / 6; bonusTiles = new int[maxTileMult]; for (int i = 1; i < maxTileMult; i++) { bonusTiles[i-1] = 3 * (int) Math.pow(2, i); } } return bonusTiles; } public int[] generateNewMoveStack() { // generate 12 vector of four 1's, four 2's, four 3's. int[] newMoveStack = new int[12]; double[] doubleStack = new double[12]; double[] doubleStackCopy = new double[12]; int[] doubleStackIndex = new int[12]; double thisDouble; // create array of Random numbers and a sorted copy for (int i = 0; i < 12; i++) { thisDouble = Math.random(); doubleStack[i] = thisDouble; doubleStackCopy[i] = thisDouble; } Arrays.sort(doubleStackCopy); // find each number in sorted array for (int i = 0; i < 12; i++) { for (int j = 0; j < 12; j++) { if (doubleStack[i] == doubleStackCopy[j]) { doubleStackIndex[i] = j; break; } } } for (int i = 0; i < 12; i++) { newMoveStack[i] = doubleStackIndex[i] / 3 + 1; // integer division exploit to round the num down } return newMoveStack; } public int[] generateFirstMoveStack() { // generate 12 vector of nine zeros, a one, a two, and a three int[] newMoveStack = new int[12]; double[] doubleStack = new double[3]; double[] doubleStackCopy = new double[3]; int[] doubleStackIndex = new int[3]; double thisDouble; // create array of Random numbers and a sorted copy for (int i = 0; i < 3; i++) { thisDouble = Math.random(); doubleStack[i] = thisDouble; doubleStackCopy[i] = thisDouble; } Arrays.sort(doubleStackCopy); // find each number in sorted array for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (doubleStack[i] == doubleStackCopy[j]) { doubleStackIndex[i] = j; break; } } } for (int i = 0; i < 9; i++) { newMoveStack[i] = 0; } for (int i = 0; i < 3; i++) { newMoveStack[i+9] = doubleStackIndex[i] / 3 + 1; // integer division exploit to round the num down } return newMoveStack; } // get max tile of a game state public int getMaxTile(GameState gameStateIn) { int [][] currentBoard = gameStateIn.getBoardState(); int maxTile = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (currentBoard[i][j] > maxTile) { maxTile = currentBoard[i][j]; } } } return maxTile; } // check whether two boards are identical public boolean checkBoardEquality(GameState gs1, GameState gs2) { boolean boardEq = true; // default int[][] board1 = gs1.getBoardState(); int[][] board2 = gs2.getBoardState(); // loop and break on a differing value anywhere int[] idx = {0, 1, 2, 3}; for (int i : idx) { for (int j : idx) { if (board1[i][j] != board2[i][j]) { boardEq = false; break; } } } return boardEq; } // vector multiply public int vectormult(int[] a, int[] b) { int total = 0; for (int i = 0; i < a.length; i++) { total += a[i] * b[i]; } return total; } // return a log at a given base public double logb(double a, double b) { return Math.log(a) / Math.log(b); } // generate a random int in a range public int randIntInRange(int min, int max) { Random rand = new Random(); // nextInt is normally exclusive of the top value, // so add 1 to make it inclusive int randomNum = rand.nextInt((max - min) + 1) + min; return randomNum; } }
Threes/src/main/java/com/kevinsprong/gamesolver/Threes.java
package com.kevinsprong.gamesolver; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; /** * Extension of TwoPlayerGame to play the game Threes! */ public class Threes extends TwoPlayerGame { // expose weights for tuning private double[] heuristicWeights = {5000, 1, 10, 5}; // getter and setter public double[] getHeuristicWeights() { return this.heuristicWeights; } public void setHeuristicWeights(double[] heuristicWeightsIn) { this.heuristicWeights = heuristicWeightsIn; } // constructors public Threes() { this.setP1MoveStrat("AlphaBeta"); this.setP2MoveStrat("DefaultComputer"); // solver parameters this.setSearchPly(6); this.setSearchTime(10000); // milliseconds this.setWinCondition(6144); // initialize game state GameState newGameState = new GameState(); int[][] blankBoard = {{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}}; newGameState.setBoardState(blankBoard); this.setGameState(newGameState); } public Threes(String p1Strat, String p2Strat) { this.setP1MoveStrat(p1Strat); this.setP2MoveStrat(p2Strat); // solver parameters this.setSearchPly(6); this.setSearchTime(10000); // milliseconds this.setWinCondition(6144); // initialize game state GameState newGameState = new GameState(); int[][] blankBoard = {{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}}; newGameState.setBoardState(blankBoard); this.setGameState(newGameState); } public Threes(String p1Strat, String p2Strat, int searchPly, int searchTime) { this.setP1MoveStrat(p1Strat); this.setP2MoveStrat(p2Strat); // solver parameters this.setSearchPly(searchPly); this.setSearchTime(searchTime); // milliseconds this.setWinCondition(6144); // initialize game state GameState newGameState = new GameState(); int[][] blankBoard = {{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}}; newGameState.setBoardState(blankBoard); this.setGameState(newGameState); } public Threes(String p1Strat, String p2Strat, int searchPly, int searchTime, int winCondition) { this.setP1MoveStrat(p1Strat); this.setP2MoveStrat(p2Strat); // solver parameters this.setSearchPly(searchPly); this.setSearchTime(searchTime); // milliseconds this.setWinCondition(winCondition); // get to this number to win! // initialize game state GameState newGameState = new GameState(); int[][] blankBoard = {{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}}; newGameState.setBoardState(blankBoard); this.setGameState(newGameState); } // implementation of abstract methods public void initializeBoard() { GameState currentState = this.getGameState(); // three ones, three twos, three threes in random locs // set move stack to one of each // assign // choose which numbers we will get int pt1 = this.generateNewCell(); int pt2 = this.generateNewCell(); // choose nine random locations for tiles int randomNum1 = this.randIntInRange(0, 15); int randomNum2 = this.randIntInRange(0, 15); while (randomNum2 == randomNum1) { randomNum2 = this.randIntInRange(0, 15); } int pt1x = (randomNum1 % 4); int pt1y = randomNum1 / 4; int pt2x = (randomNum2 % 4); int pt2y = randomNum2 / 4; // assign to game state int[][] currentBoard = currentState.getBoardState(); currentBoard[pt1y][pt1x] = pt1; currentBoard[pt2y][pt2x] = pt2; currentState.setBoardState(currentBoard); this.setGameState(currentState); } // given a game state and strategies, return next player move public void playerMove() { // get needed variables GameState currentState = this.getGameState(); String p1Strat = this.getP1MoveStrat(); String p2Strat = this.getP2MoveStrat(); if (currentState.getPlayerToMove() == 1) { // dont toggle flag until we actually update the board in other func if (p1Strat.equals("AlphaBeta")) { // use AlphaBetaSolver currentState.setP1PreviousMove(AlphaBetaSolver.solveBoard(this)); } else if (p1Strat.equals("Random")) { // copy game state so we dont overwrite any of it GameState currentStateCopy = GameState.copyGameState(currentState); // pick a random legal move String[] legalMoves = this.findLegalMoves(currentStateCopy); int idx = this.randIntInRange(0, legalMoves.length - 1); // instead of return statement currentState.setP1PreviousMove(legalMoves[idx]); } } else { if (p2Strat.equals("DefaultComputer")) { // choose a tile at random // update all of this with threes logic // choose which number(s) we will get int pt1 = this.generateNewCell(); // find zero tiles on current board and their indices ArrayList<int[]> zeroList = this.getValidComputerMoveTiles(currentState); // choose random location for tile from among zero indices int randomNum1 = this.randIntInRange(0, zeroList.size()-1); int pt1y = zeroList.get(randomNum1)[0]; int pt1x = zeroList.get(randomNum1)[1]; // instead of return statement currentState.setP2PreviousMove(Integer.toString(pt1) + "_" + Integer.toString(pt1y) + "_" + Integer.toString(pt1x)); } } } // separate method to update game board of GameState manually public GameState calcUpdatedGameState(GameState gameStateIn, String move) { // give ourselves clean object to work with GameState currentState = GameState.copyGameState(gameStateIn); int[][] currentBoard = currentState.getBoardState(); int playerMoved = currentState.getPlayerToMove(); if (playerMoved == 1) { // update depending on move if (move.equals("U")) { // move everything up one tile, collide at top. one collision per move for (int j = 0; j < 4; j++) { // find and perform collision for (int i = 1; i < 4; i++) { if (currentBoard[i][j] > 0) { if (currentBoard[i][j] == currentBoard[i-1][j]) { currentBoard[i-1][j] = 2*currentBoard[i-1][j]; currentBoard[i][j] = 0; break; } // because board(i,j) > 0 this detects a 1 and 2 if (currentBoard[i][j] + currentBoard[i-1][j] == 3) { currentBoard[i-1][j] = 3; currentBoard[i][j] = 0; break; } } } // move everything up if there is a zero above for (int i = 1; i < 4; i++) { if (currentBoard[i-1][j] == 0) { currentBoard[i-1][j] = currentBoard[i][j]; currentBoard[i][j] = 0; } } } } else if (move.equals("D")) { // move everything down one tile, collide at bottom. one collision per move for (int j = 0; j < 4; j++) { // find and perform collision for (int i = 2; i >= 0; i--) { if (currentBoard[i][j] > 0) { if (currentBoard[i][j] == currentBoard[i+1][j]) { currentBoard[i+1][j] = 2*currentBoard[i+1][j]; currentBoard[i][j] = 0; break; } // because board(i,j) > 0 this detects a 1 and 2 if (currentBoard[i][j] + currentBoard[i+1][j] == 3) { currentBoard[i+1][j] = 3; currentBoard[i][j] = 0; break; } } } // move everything down if there is a zero below for (int i = 2; i >= 0; i--) { if (currentBoard[i+1][j] == 0) { currentBoard[i+1][j] = currentBoard[i][j]; currentBoard[i][j] = 0; } } } } else if (move.equals("L")) { // move everything left one tile, collide at left. one collision per move for (int i = 0; i < 4; i++) { // find and perform collision for (int j = 1; j < 4; j++) { if (currentBoard[i][j] > 0) { if (currentBoard[i][j] == currentBoard[i][j-1]) { currentBoard[i][j-1] = 2*currentBoard[i][j-1]; currentBoard[i][j] = 0; break; } // because board(i,j) > 0 this detects a 1 and 2 if (currentBoard[i][j] + currentBoard[i][j-1] == 3) { currentBoard[i][j-1] = 3; currentBoard[i][j] = 0; break; } } } // move everything left if there is a zero adjacent for (int j = 1; j < 4; j++) { if (currentBoard[i][j-1] == 0) { currentBoard[i][j-1] = currentBoard[i][j]; currentBoard[i][j] = 0; } } } } else if (move.equals("R")) { // move everything right one tile, collide at right. one collision per move for (int i = 0; i < 4; i++) { // find and perform collision for (int j = 2; j >= 0; j--) { if (currentBoard[i][j] > 0) { if (currentBoard[i][j] == currentBoard[i][j+1]) { currentBoard[i][j+1] = 2*currentBoard[i][j+1]; currentBoard[i][j] = 0; break; } // because board(i,j) > 0 this detects a 1 and 2 if (currentBoard[i][j] + currentBoard[i][j+1] == 3) { currentBoard[i][j+1] = 3; currentBoard[i][j] = 0; break; } } } // move everything right if there is a zero adjacent for (int j = 2; j >= 0; j--) { if (currentBoard[i][j+1] == 0) { currentBoard[i][j+1] = currentBoard[i][j]; currentBoard[i][j] = 0; } } } } // assign new board back to game state currentState.setBoardState(currentBoard); // unnec. due to obj pointer pass? } else { // parse move String[] parsedMove = move.split("_"); int pt1 = Integer.parseInt(parsedMove[0]); int pt1y = Integer.parseInt(parsedMove[1]); int pt1x = Integer.parseInt(parsedMove[2]); currentBoard[pt1y][pt1x] = pt1; // assign it to the board currentState.setBoardState(currentBoard); // update move stack to zero out the move element int[] moveList = currentState.getMoveStack(); for (int j = 0; j < 12; j++) { if (moveList[j] > 0) { moveList[j] = 0; break; } if (moveList[j] == 11) { // array is all zeros; reset move stack currentState.setMoveStack(this.generateNewMoveStack()); break; } } } return currentState; } // wrapper function for calculating updated game state public void updateGameState() { // get game variables we need GameState currentState = this.getGameState(); int playerMoved = currentState.getPlayerToMove(); String currentMove = null; if (playerMoved == 1) { currentMove = currentState.getP1PreviousMove(); } else { currentMove = currentState.getP2PreviousMove(); } // this call calculates the updated board and moveStack GameState newGameState = calcUpdatedGameState(currentState, currentMove); // switch playerToMove - flip 1 to 2 and vice versa newGameState.setPlayerToMove((playerMoved % 2) + 1); // add a move to the overall list if (playerMoved == 1) { newGameState.setMoveNum(newGameState.getMoveNum() + 1); } // calculate the move and update the official game state this.setGameState(newGameState); } // given a move history, calculate the score public void updateGameScore(GameState currentState, int tileMade) { // making a tile >= 3 gives 3 ^ the multiple of 3 it is // ignore second argument, score here is solely derived from board int totalScore = 0; int[][] currentBoard = currentState.getBoardState(); for (int[] row : currentBoard) { for (int val : row) { if (val >= 3) { totalScore += Math.pow(3, (this.logb(val/3, 2) + 1)); } } } // modify currentState that we are pointing to currentState.setGameScore(totalScore); } // given a gameState and whose turn it is, find list of legal moves public String[] findLegalMoves(GameState gameStateIn) { GameState currentState = GameState.copyGameState(gameStateIn); int[][] boardOrig = currentState.getBoardState(); ArrayList<String> legalMoveList = new ArrayList<String>(); if (currentState.getPlayerToMove() == 1) { // test each move individually // test Up GameState gameStateU = this.calcUpdatedGameState(currentState, "U"); if (!checkBoardEquality(gameStateU, currentState)) { // then up was a legal move legalMoveList.add("U"); } // test Down currentState.setBoardState(boardOrig); GameState gameStateD = this.calcUpdatedGameState(currentState, "D"); if (!checkBoardEquality(gameStateD, currentState)) { legalMoveList.add("D"); } // test Left currentState.setBoardState(boardOrig); GameState gameStateL = this.calcUpdatedGameState(currentState, "L"); if (!checkBoardEquality(gameStateL, currentState)) { legalMoveList.add("L"); } // test Right currentState.setBoardState(boardOrig); GameState gameStateR = this.calcUpdatedGameState(currentState, "R"); if (!checkBoardEquality(gameStateR, currentState)) { legalMoveList.add("R"); } } else { // computer player // get the valid move tiles ArrayList<int[]> zeroList = this.getValidComputerMoveTiles(currentState); // legal moves are the top of the moveStack or the bonusMoveList, to open tiles // opposite P1's move // parse moveStack List<Integer> uniqueMoves = new ArrayList<Integer>(); int topMove = this.getGameState().getMoveStack()[1]; uniqueMoves.add(topMove); for (int bonus : this.findBonusMoves()) { uniqueMoves.add(bonus); } Integer[] legalMoveTiles = uniqueMoves.toArray( new Integer[uniqueMoves.size()]); // build list of moves for (int tile : legalMoveTiles) { // yay auto-unboxing for (int[] pos : zeroList) { legalMoveList.add(Integer.toString(tile) + "_" + Integer.toString(pos[0]) + "_" + Integer.toString(pos[1])); } } } // convert array list into array of strings return legalMoveList.toArray(new String[legalMoveList.size()]); } private ArrayList<int[]> getValidComputerMoveTiles(GameState gsIn) { ArrayList<int[]> zeroList = new ArrayList<int[]>(); // get indices of open spaces along row/col opposite move int[][] boardOrig = gsIn.getBoardState(); String p1Move = gsIn.getP1PreviousMove(); if (p1Move.equals("U")) { for (int i = 0; i < 4; i++) { if (boardOrig[3][i] > 0) { zeroList.add(new int[]{3,i}); } } } else if (p1Move.equals("D")) { for (int i = 0; i < 4; i++) { if (boardOrig[0][i] > 0) { zeroList.add(new int[]{0,i}); } } } else if (p1Move.equals("L")) { for (int i = 0; i < 4; i++) { if (boardOrig[i][3] > 0) { zeroList.add(new int[]{i,3}); } } } else if (p1Move.equals("R")) { for (int i = 0; i < 4; i++) { if (boardOrig[i][0] > 0) { zeroList.add(new int[]{i,0}); } } } return zeroList; } // determine if win condition met - returns 0, 1, 2 for no winner yet/p1/p2 public int determineWinner() { GameState currentState = GameState.copyGameState(this.getGameState()); return this.determineWinner(currentState); } // with gs argument for alpha beta calls public int determineWinner(GameState currentState) { // check loser first if (currentState.getPlayerToMove() == 1 && this.findLegalMoves(currentState).length == 0) { // can do this first since getting to p1's win condition // requires a successful move which leaves at least one empty space // (conditions don't overlap) return 2; } // find max tile on board int maxTile = getMaxTile(currentState); if (maxTile >= this.getWinCondition()) { return 1; } // if neither then p1 is still alive return 0; } // compute board evaluation public double evaluateGameState(GameState gameStateIn) { // update all of this with threes stuff int[][] board = gameStateIn.getBoardState(); // heuristics to assess board. SCORE IS RELATIVE TO HUMAN PLAYER double[] heuristicVals = {0, 0, 0, 0}; double[] heuristicWeights = this.getHeuristicWeights(); double finalScore = 0; //--------------------------------------------------------------------- // Heuristic 1: there is a win condition int winStatus = this.determineWinner(gameStateIn); if (winStatus == 1) { heuristicVals[0] = 1; } else if (winStatus == 2) { heuristicVals[0] = -1; } else { heuristicVals[0] = 0; } //--------------------------------------------------------------------- // Heuristic 2: monotonicity int[] monoScores; int totalScore = 0; // loop over rows for (int[] row : board) { monoScores = checkMonotonicity(row); totalScore += Math.max(monoScores[0], monoScores[1]); } // loop over cols int[] col = {0,0,0,0}; for (int j = 0; j < 4; j++) { for (int i = 0; i < 4; i++) { col[i] = board[i][j]; } monoScores = checkMonotonicity(col); totalScore += Math.max(monoScores[0], monoScores[1]); } heuristicVals[1] = (double) totalScore; //--------------------------------------------------------------------- // Heuristic 3: the "smoothness" of the board // in log space to account for merges needed double totalDeviation = 0; // will be negative to penalize deviation // probe rightwards for (int i = 0; i < 4; i++) { for (int j = 0; j < 3; j++) { if (board[i][j] != 0) { // probe rightwards for (int k = j+1; k < 4; k++) { // check smoothness versus first non-zero tile if (board[i][k] != 0) { totalDeviation += Math.abs(logb(board[i][j], 2) - logb(board[i][k], 2)); break; } } } } } // probe downwards for (int j = 0; j < 4; j++) { for (int i = 0; i < 3; i++) { if (board[i][j] != 0) { // probe rightwards for (int k = i+1; k < 4; k++) { // check smoothness versus first non-zero tile if (board[k][j] != 0) { totalDeviation += Math.abs(logb(board[i][j], 2) - logb(board[k][j], 2)); break; } } } } } heuristicVals[2] = -1 * totalDeviation; //--------------------------------------------------------------------- // Heuristic 4: the number of open tiles double openTiles = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (board[i][j] == 0) { openTiles += 1; } } } heuristicVals[3] = Math.pow(openTiles, 2); //--------------------------------------------------------------------- // aggregate and return for (int i = 0; i < 4; i++) { finalScore += heuristicVals[i] * heuristicWeights[i]; } return finalScore; } // check monotonicity of a vector in log space ignoring zeros private int[] checkMonotonicity(int[] vec) { int[] scores = {0,0}; // forward and reverse dir respectively for (int i = 0; i < vec.length-1; i++) { if (vec[i] > 0) { // find next non-zero element for (int j = i+1; j < vec.length; j++) { if (vec[j] > 0) { if (vec[i] >= vec[j]) { // reverse dir scores[1] += logb(vec[i], 2) - logb(vec[j], 2); } if (vec[j] >= vec[i]) { // forward dir scores[1] += logb(vec[j], 2) - logb(vec[i], 2); } break; } } } } return scores; } // generate new tile for the game public int generateNewCell() { int rand = this.randIntInRange(1,21); int output = 0; // 1/21 to return a bonus tile if (rand == 1) { int[] bonusMoves = this.findBonusMoves(); int bidx = randIntInRange(0, bonusMoves.length-1); output = bonusMoves[bidx]; } else { // 20/21 to return first non-zero tile in moveStack // find first non-zero tile of moveStack int [] moveStack = this.getGameState().getMoveStack(); for (int i = 0; i < moveStack.length; i++) { if (moveStack[i] > 0) { output = moveStack[i]; break; } } } return output; } public int[] findBonusMoves() { int bonusTiles[] = {}; // find max tile int maxTile = this.getMaxTile(this.getGameState()); if (maxTile >= 48) { // return all multiples of 6 that are between 6 and maxTile/8 int maxTileMult = maxTile / 8 / 6; bonusTiles = new int[maxTileMult]; for (int i = 1; i < maxTileMult; i++) { bonusTiles[i-1] = 3 * (int) Math.pow(2, i); } } return bonusTiles; } public int[] generateNewMoveStack() { // generate 12 vector of four 1's, four 2's, four 3's. int[] newMoveStack = new int[12]; double[] doubleStack = new double[12]; double[] doubleStackCopy = new double[12]; int[] doubleStackIndex = new int[12]; double thisDouble; // create array of Random numbers and a sorted copy for (int i = 0; i < 12; i++) { thisDouble = Math.random(); doubleStack[i] = thisDouble; doubleStackCopy[i] = thisDouble; } Arrays.sort(doubleStackCopy); // find each number in sorted array for (int i = 0; i < 12; i++) { for (int j = 0; j < 12; j++) { if (doubleStack[i] == doubleStackCopy[j]) { doubleStackIndex[i] = j; break; } } } for (int i = 0; i < 12; i++) { newMoveStack[i] = doubleStackIndex[i] / 3 + 1; // integer division exploit to round the num down } return newMoveStack; } // get max tile of a game state public int getMaxTile(GameState gameStateIn) { int [][] currentBoard = gameStateIn.getBoardState(); int maxTile = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (currentBoard[i][j] > maxTile) { maxTile = currentBoard[i][j]; } } } return maxTile; } // check whether two boards are identical public boolean checkBoardEquality(GameState gs1, GameState gs2) { boolean boardEq = true; // default int[][] board1 = gs1.getBoardState(); int[][] board2 = gs2.getBoardState(); // loop and break on a differing value anywhere int[] idx = {0, 1, 2, 3}; for (int i : idx) { for (int j : idx) { if (board1[i][j] != board2[i][j]) { boardEq = false; break; } } } return boardEq; } // vector multiply public int vectormult(int[] a, int[] b) { int total = 0; for (int i = 0; i < a.length; i++) { total += a[i] * b[i]; } return total; } // return a log at a given base public double logb(double a, double b) { return Math.log(a) / Math.log(b); } // generate a random int in a range public int randIntInRange(int min, int max) { Random rand = new Random(); // nextInt is normally exclusive of the top value, // so add 1 to make it inclusive int randomNum = rand.nextInt((max - min) + 1) + min; return randomNum; } }
Threes ready for tests
Threes/src/main/java/com/kevinsprong/gamesolver/Threes.java
Threes ready for tests
<ide><path>hrees/src/main/java/com/kevinsprong/gamesolver/Threes.java <ide> GameState currentState = this.getGameState(); <ide> <ide> // three ones, three twos, three threes in random locs <del> // set move stack to one of each <del> <del> // assign <del> <del> <del> // choose which numbers we will get <del> int pt1 = this.generateNewCell(); <del> int pt2 = this.generateNewCell(); <del> // choose nine random locations for tiles <del> int randomNum1 = this.randIntInRange(0, 15); <del> int randomNum2 = this.randIntInRange(0, 15); <del> while (randomNum2 == randomNum1) { <del> randomNum2 = this.randIntInRange(0, 15); <add> int[] rows = new int[9]; <add> int[] cols = new int[9]; <add> int[] vals = {1,1,1,2,2,2,3,3,3}; <add> <add> // generate random nums from 0 to 15 in loop, check against hash set, and make x/y <add> Set<Integer> randsChosen = new HashSet<Integer>(); <add> int numsChosen = 0; <add> while (numsChosen < 9) { // could do fewer checks for blank spaces and have fewer, but then indexing gets hard <add> int randInt = this.randIntInRange(0, 15); <add> while (randsChosen.contains(randInt)) { <add> randInt = this.randIntInRange(0, 15); <add> } <add> rows[numsChosen] = randInt % 4; <add> cols[numsChosen] = randInt / 4; <add> } <add> <add> <add> // assign to game state <add> int[][] currentBoard = currentState.getBoardState(); <add> for(int i = 0; i < 9; i++) { <add> currentBoard[rows[i]][cols[i]] = vals[i]; <ide> } <del> int pt1x = (randomNum1 % 4); <del> int pt1y = randomNum1 / 4; <del> int pt2x = (randomNum2 % 4); <del> int pt2y = randomNum2 / 4; <del> <del> // assign to game state <del> int[][] currentBoard = currentState.getBoardState(); <del> currentBoard[pt1y][pt1x] = pt1; <del> currentBoard[pt2y][pt2x] = pt2; <ide> currentState.setBoardState(currentBoard); <ide> <add> // set remaining move stack to one of each <add> currentState.setMoveStack(this.generateFirstMoveStack()); <add> <add> // assign to game state <ide> this.setGameState(currentState); <add> <ide> } <ide> <ide> // given a game state and strategies, return next player move <ide> return newMoveStack; <ide> } <ide> <add> public int[] generateFirstMoveStack() { <add> // generate 12 vector of nine zeros, a one, a two, and a three <add> int[] newMoveStack = new int[12]; <add> double[] doubleStack = new double[3]; <add> double[] doubleStackCopy = new double[3]; <add> int[] doubleStackIndex = new int[3]; <add> double thisDouble; <add> <add> // create array of Random numbers and a sorted copy <add> for (int i = 0; i < 3; i++) { <add> thisDouble = Math.random(); <add> doubleStack[i] = thisDouble; <add> doubleStackCopy[i] = thisDouble; <add> } <add> Arrays.sort(doubleStackCopy); <add> // find each number in sorted array <add> for (int i = 0; i < 3; i++) { <add> for (int j = 0; j < 3; j++) { <add> if (doubleStack[i] == doubleStackCopy[j]) { <add> doubleStackIndex[i] = j; <add> break; <add> } <add> } <add> } <add> <add> for (int i = 0; i < 9; i++) { <add> newMoveStack[i] = 0; <add> } <add> for (int i = 0; i < 3; i++) { <add> newMoveStack[i+9] = doubleStackIndex[i] / 3 + 1; // integer division exploit to round the num down <add> } <add> <add> return newMoveStack; <add> } <add> <ide> // get max tile of a game state <ide> public int getMaxTile(GameState gameStateIn) { <ide> int [][] currentBoard = gameStateIn.getBoardState();
Java
mit
fa6f20747ba4d19a624658fca475903388bdcfe1
0
gsdlab/chocosolver,gsdlab/chocosolver
package org.clafer.choco.constraint.propagator; import java.util.Arrays; import org.chocosolver.solver.constraints.Propagator; import org.chocosolver.solver.constraints.PropagatorPriority; import org.chocosolver.solver.exception.ContradictionException; import org.chocosolver.solver.variables.IntVar; import org.chocosolver.solver.variables.SetVar; import org.chocosolver.solver.variables.Variable; import org.chocosolver.solver.variables.delta.ISetDeltaMonitor; import org.chocosolver.solver.variables.events.SetEventType; import org.chocosolver.util.ESat; import org.chocosolver.util.procedure.IntProcedure; /** * * @author jimmy */ public class PropContinuousUnion extends Propagator<Variable> { private final SetVar[] sets; private final ISetDeltaMonitor[] setsD; private final IntVar totalCard; private final int[] supports; public PropContinuousUnion(SetVar[] sets, IntVar totalCard) { super(buildArray(sets, totalCard), PropagatorPriority.BINARY, true); this.sets = sets; this.setsD = PropUtil.monitorDeltas(sets, this); this.totalCard = totalCard; this.supports = new int[totalCard.getUB()]; } private static Variable[] buildArray(SetVar[] sets, IntVar totalCard) { Variable[] variables = new Variable[sets.length + 1]; System.arraycopy(sets, 0, variables, 0, sets.length); variables[sets.length] = totalCard; return variables; } boolean isSetVar(int idx) { return idx < sets.length; } int getSetVarIndex(int idx) { return idx; } boolean isTotalCardVar(int idx) { return idx == sets.length; } //TODO: Sept16 // @Override // public int getPropagationConditions(int vIdx) { // if (isSetVar(vIdx)) { // return SetEventType.all(); // } // assert isTotalCardVar(vIdx); // return IntEventType.all(); // } private boolean support(int value) { if (value >= supports.length) { return false; } int support = supports[value]; if (sets[support].envelopeContains(value)) { return true; } for (int i = 0; i < sets.length; i++) { if (sets[i].envelopeContains(value)) { supports[value] = i; return true; } } return false; } private void findMate(int unionKer) throws ContradictionException { int mate = -1; for (int j = 0; j < sets.length; j++) { if (sets[j].envelopeContains(unionKer)) { // Found a second mate or in kernel. if (mate != -1 || sets[j].kernelContains(unionKer)) { return; } mate = j; } } if (mate == -1) { // No mates. contradiction(totalCard, "too high"); } else if (mate != -2) { // One mate. sets[mate].addToKernel(unionKer, this); } } @Override public void propagate(int evtmask) throws ContradictionException { for (SetVar set : sets) { for (int i = set.getEnvelopeFirst(); i != SetVar.END; i = set.getEnvelopeNext()) { if (i < 0 || i >= totalCard.getUB()) { set.removeFromEnvelope(i, this); } } } int maxEnv = PropUtil.maxEnv(sets[sets.length - 1]); int maxKer = PropUtil.maxKer(sets[sets.length - 1]); for (int i = sets.length - 2; i >= 0; i--) { maxEnv = Math.max(maxEnv, PropUtil.maxEnv(sets[i])); maxKer = Math.max(maxKer, PropUtil.maxKer(sets[i])); } totalCard.updateUpperBound(maxEnv == SetVar.END ? 0 : maxEnv + 1, this); if (totalCard.getLB() > 0) { totalCard.updateLowerBound(maxKer == SetVar.END ? 0 : maxKer + 1, this); } int ub = totalCard.getUB(); for (int i = 0; i < ub; i++) { if (!support(i)) { totalCard.updateUpperBound(i, this); break; } } int lb = totalCard.getLB(); for (int i = 0; i < lb; i++) { findMate(i); } } @Override public void propagate(int idxVarInProp, int mask) throws ContradictionException { if (isSetVar(idxVarInProp)) { int id = getSetVarIndex(idxVarInProp); setsD[id].freeze(); setsD[id].forEach(pruneUnionOnSetEnv, SetEventType.REMOVE_FROM_ENVELOPE); setsD[id].forEach(pickUnionOnSetKer, SetEventType.ADD_TO_KER); setsD[id].unfreeze(); } else { assert isTotalCardVar(idxVarInProp); int lb = totalCard.getLB(); for (int i = 0; i < lb; i++) { findMate(i); } for (SetVar set : sets) { for (int i = set.getEnvelopeFirst(); i != SetVar.END; i = set.getEnvelopeNext()) { if (i < 0 || i >= totalCard.getUB()) { set.removeFromEnvelope(i, this); } } } int ub = totalCard.getUB(); for (int i = 0; i < ub; i++) { if (!support(i)) { totalCard.updateUpperBound(i, this); break; } } } } private final IntProcedure pruneUnionOnSetEnv = new IntProcedure() { @Override public void execute(int env) throws ContradictionException { int maxEnv = PropUtil.maxEnv(sets[sets.length - 1]); for (int i = sets.length - 2; i >= 0; i--) { maxEnv = Math.max(maxEnv, PropUtil.maxEnv(sets[i])); } totalCard.updateUpperBound(maxEnv == SetVar.END ? 0 : maxEnv + 1, PropContinuousUnion.this); int lb = totalCard.getLB(); if (env < lb) { findMate(env); } if (!support(env)) { totalCard.updateUpperBound(env, PropContinuousUnion.this); } } }; private final IntProcedure pickUnionOnSetKer = new IntProcedure() { @Override public void execute(int ker) throws ContradictionException { int f = totalCard.getLB(); if (totalCard.updateLowerBound(ker + 1, PropContinuousUnion.this)) { int t = totalCard.getLB(); for (int i = f; i < t; i++) { findMate(i); } } } }; @Override public ESat isEntailed() { for (SetVar set : sets) { if (set.getKernelSize() > 0) { if (set.getKernelFirst() < 0 || PropUtil.maxKer(set) >= totalCard.getUB()) { return ESat.FALSE; } } } if (!totalCard.isInstantiated()) { return ESat.UNDEFINED; } for (SetVar set : sets) { if (set.getEnvelopeSize() > 0) { if (set.getEnvelopeFirst() < 0 || PropUtil.maxEnv(set) >= totalCard.getUB()) { return ESat.UNDEFINED; } } } int tc = totalCard.getValue(); boolean allRealized = true; for (int i = 0; i < tc; i++) { boolean realized = false; boolean support = false; for (SetVar set : sets) { if (set.kernelContains(i)) { realized = true; support = true; break; } else if (set.envelopeContains(i)) { support = true; } } allRealized &= realized; if (!support) { return ESat.FALSE; } } return allRealized ? ESat.TRUE : ESat.UNDEFINED; } @Override public String toString() { return "union(" + Arrays.toString(sets) + ") = {0, 1, ..., " + totalCard + " - 1}"; } }
src/main/java/org/clafer/choco/constraint/propagator/PropContinuousUnion.java
package org.clafer.choco.constraint.propagator; import java.util.Arrays; import org.chocosolver.solver.constraints.Propagator; import org.chocosolver.solver.constraints.PropagatorPriority; import org.chocosolver.solver.exception.ContradictionException; import org.chocosolver.solver.variables.IntVar; import org.chocosolver.solver.variables.SetVar; import org.chocosolver.solver.variables.Variable; import org.chocosolver.solver.variables.delta.ISetDeltaMonitor; import org.chocosolver.solver.variables.events.SetEventType; import org.chocosolver.util.ESat; import org.chocosolver.util.procedure.IntProcedure; /** * * @author jimmy */ public class PropContinuousUnion extends Propagator<Variable> { private final SetVar[] sets; private final ISetDeltaMonitor[] setsD; private final IntVar totalCard; private final int[] supports; public PropContinuousUnion(SetVar[] sets, IntVar totalCard) { super(buildArray(sets, totalCard), PropagatorPriority.BINARY, true); this.sets = sets; this.setsD = PropUtil.monitorDeltas(sets, this); this.totalCard = totalCard; this.supports = new int[totalCard.getUB()]; } private static Variable[] buildArray(SetVar[] sets, IntVar totalCard) { Variable[] variables = new Variable[sets.length + 1]; System.arraycopy(sets, 0, variables, 0, sets.length); variables[sets.length] = totalCard; return variables; } boolean isSetVar(int idx) { return idx < sets.length; } int getSetVarIndex(int idx) { return idx; } boolean isTotalCardVar(int idx) { return idx == sets.length; } //TODO: Sept16 // @Override // public int getPropagationConditions(int vIdx) { // if (isSetVar(vIdx)) { // return SetEventType.all(); // } // assert isTotalCardVar(vIdx); // return IntEventType.all(); // } private boolean support(int value) { int support = supports[value]; if (sets[support].envelopeContains(value)) { return true; } for (int i = 0; i < sets.length; i++) { if (sets[i].envelopeContains(value)) { supports[value] = i; return true; } } return false; } private void findMate(int unionKer) throws ContradictionException { int mate = -1; for (int j = 0; j < sets.length; j++) { if (sets[j].envelopeContains(unionKer)) { // Found a second mate or in kernel. if (mate != -1 || sets[j].kernelContains(unionKer)) { return; } mate = j; } } if (mate == -1) { // No mates. contradiction(totalCard, "too high"); } else if (mate != -2) { // One mate. sets[mate].addToKernel(unionKer, this); } } @Override public void propagate(int evtmask) throws ContradictionException { for (SetVar set : sets) { for (int i = set.getEnvelopeFirst(); i != SetVar.END; i = set.getEnvelopeNext()) { if (i < 0 || i >= totalCard.getUB()) { set.removeFromEnvelope(i, this); } } } int maxEnv = PropUtil.maxEnv(sets[sets.length - 1]); int maxKer = PropUtil.maxKer(sets[sets.length - 1]); for (int i = sets.length - 2; i >= 0; i--) { maxEnv = Math.max(maxEnv, PropUtil.maxEnv(sets[i])); maxKer = Math.max(maxKer, PropUtil.maxKer(sets[i])); } totalCard.updateUpperBound(maxEnv == SetVar.END ? 0 : maxEnv + 1, this); if (totalCard.getLB() > 0) { totalCard.updateLowerBound(maxKer == SetVar.END ? 0 : maxKer + 1, this); } int ub = totalCard.getUB(); for (int i = 0; i < ub; i++) { if (!support(i)) { totalCard.updateUpperBound(i, this); break; } } int lb = totalCard.getLB(); for (int i = 0; i < lb; i++) { findMate(i); } } @Override public void propagate(int idxVarInProp, int mask) throws ContradictionException { if (isSetVar(idxVarInProp)) { int id = getSetVarIndex(idxVarInProp); setsD[id].freeze(); setsD[id].forEach(pruneUnionOnSetEnv, SetEventType.REMOVE_FROM_ENVELOPE); setsD[id].forEach(pickUnionOnSetKer, SetEventType.ADD_TO_KER); setsD[id].unfreeze(); } else { assert isTotalCardVar(idxVarInProp); int lb = totalCard.getLB(); for (int i = 0; i < lb; i++) { findMate(i); } for (SetVar set : sets) { for (int i = set.getEnvelopeFirst(); i != SetVar.END; i = set.getEnvelopeNext()) { if (i < 0 || i >= totalCard.getUB()) { set.removeFromEnvelope(i, this); } } } int ub = totalCard.getUB(); for (int i = 0; i < ub; i++) { if (!support(i)) { totalCard.updateUpperBound(i, this); break; } } } } private final IntProcedure pruneUnionOnSetEnv = new IntProcedure() { @Override public void execute(int env) throws ContradictionException { int maxEnv = PropUtil.maxEnv(sets[sets.length - 1]); for (int i = sets.length - 2; i >= 0; i--) { maxEnv = Math.max(maxEnv, PropUtil.maxEnv(sets[i])); } totalCard.updateUpperBound(maxEnv == SetVar.END ? 0 : maxEnv + 1, PropContinuousUnion.this); int lb = totalCard.getLB(); if (env < lb) { findMate(env); } if (!support(env)) { totalCard.updateUpperBound(env, PropContinuousUnion.this); } } }; private final IntProcedure pickUnionOnSetKer = new IntProcedure() { @Override public void execute(int ker) throws ContradictionException { int f = totalCard.getLB(); if (totalCard.updateLowerBound(ker + 1, PropContinuousUnion.this)) { int t = totalCard.getLB(); for (int i = f; i < t; i++) { findMate(i); } } } }; @Override public ESat isEntailed() { for (SetVar set : sets) { if (set.getKernelSize() > 0) { if (set.getKernelFirst() < 0 || PropUtil.maxKer(set) >= totalCard.getUB()) { return ESat.FALSE; } } } if (!totalCard.isInstantiated()) { return ESat.UNDEFINED; } for (SetVar set : sets) { if (set.getEnvelopeSize() > 0) { if (set.getEnvelopeFirst() < 0 || PropUtil.maxEnv(set) >= totalCard.getUB()) { return ESat.UNDEFINED; } } } int tc = totalCard.getValue(); boolean allRealized = true; for (int i = 0; i < tc; i++) { boolean realized = false; boolean support = false; for (SetVar set : sets) { if (set.kernelContains(i)) { realized = true; support = true; break; } else if (set.envelopeContains(i)) { support = true; } } allRealized &= realized; if (!support) { return ESat.FALSE; } } return allRealized ? ESat.TRUE : ESat.UNDEFINED; } @Override public String toString() { return "union(" + Arrays.toString(sets) + ") = {0, 1, ..., " + totalCard + " - 1}"; } }
Fixed PropContinuousUnion to work when values are larger than expetced.
src/main/java/org/clafer/choco/constraint/propagator/PropContinuousUnion.java
Fixed PropContinuousUnion to work when values are larger than expetced.
<ide><path>rc/main/java/org/clafer/choco/constraint/propagator/PropContinuousUnion.java <ide> boolean isTotalCardVar(int idx) { <ide> return idx == sets.length; <ide> } <del> <add> <ide> //TODO: Sept16 <ide> // @Override <ide> // public int getPropagationConditions(int vIdx) { <ide> // assert isTotalCardVar(vIdx); <ide> // return IntEventType.all(); <ide> // } <del> <ide> private boolean support(int value) { <add> if (value >= supports.length) { <add> return false; <add> } <ide> int support = supports[value]; <ide> if (sets[support].envelopeContains(value)) { <ide> return true;
Java
lgpl-2.1
3525d843c12d93258514f69663dc5f7ad05155b6
0
SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer,viktorbahr/jaer,viktorbahr/jaer,SensorsINI/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer,viktorbahr/jaer
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.sf.jaer.hardwareinterface.serial.eDVS128; import java.io.*; import java.beans.*; import java.util.Observable; import java.util.logging.Level; import java.util.logging.Logger; import java.util.prefs.*; import net.sf.jaer.aemonitor.*; import net.sf.jaer.chip.*; import net.sf.jaer.biasgen.*; import net.sf.jaer.hardwareinterface.*; import net.sf.jaer.hardwareinterface.serial.*; import gnu.io.CommPort; import gnu.io.CommPortIdentifier; import gnu.io.SerialPort; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.Math.*; import java.util.ArrayList; import java.util.Observer; import ch.unizh.ini.jaer.chip.retina.DVS128; /** * Interface to eDVS128 camera. * * This camera uses 4Mbaud 8 bits 1 stop no parity with RTS/CTS. * * The camera returns the following help * <pre> * DVS128 - LPC2106/01 Interface Board, V6.0: Apr 25 2011, 13:09:50 System Clock: 64MHz / 64 -> 1000ns event time resolution Modules: Supported Commands: E+/- - enable/disable event sending !Ex - specify event data format, ??E to list options B - send bias settings to DVS !Bx=y - set bias register x[0..11] to value y[0..0xFFFFFF] ?Bx - get bias register x current value !R+/- - transmit event rate on/off 0,1,2 - LED off/on/blinking !S=x - set baudrate to x R - reset board P - enter reprogramming mode ?? - display help ??E !E0 - 2 bytes per event binary 0yyyyyyy.pxxxxxxx (default) !E1 - 4 bytes per event (as above followed by 16bit timestamp) !E10 - 3 bytes per event, 6bit encoded !E11 - 6 bytes per event+timestamp, 6bit encoded !E12 - 4 bytes per event, 6bit encoded; new-line !E13 - 7 bytes per event+timestamp, 6bit encoded; new-line !E20 - 4 bytes per event, hex encoded !E21 - 8 bytes per event+timestamp, hex encoded !E22 - 5 bytes per event, hex encoded; new-line !E23 - 8 bytes per event+timestamp, hex encoded; new-line !E30 - 10 bytes per event, ASCII <1p> <3y> <3x>; new-line !E31 - 10 bytes per event+timestamp, ASCII <1p> <3y> <3x> <5ts>; new-line * </pre> * * @author lou */ public class eDVS128_HardwareInterface implements SerialInterface, HardwareInterface, AEMonitorInterface, BiasgenHardwareInterface, Observer { public static final int BAUD_RATE = 4000000; protected static Preferences prefs = Preferences.userNodeForPackage(eDVS128_HardwareInterface.class); public PropertyChangeSupport support = new PropertyChangeSupport(this); protected Logger log = Logger.getLogger("eDVS128"); protected AEChip chip; /** Amount by which we need to divide the received timestamp values to get us timestamps. */ public final int TICK_DIVIDER = 1; protected AEPacketRaw lastEventsAcquired = new AEPacketRaw(); public static final int AE_BUFFER_SIZE = 100000; // should handle 5Meps at 30FPS protected int aeBufferSize = prefs.getInt("eDVS128.aeBufferSize", AE_BUFFER_SIZE); protected int interfaceNumber = 0; public static boolean isOpen = false; public static boolean eventAcquisitionEnabled = false; public static boolean overrunOccuredFlag = false; protected byte cHighBitMask = (byte) 0x80; protected byte cLowerBitsMask = (byte) 0x7F; int eventCounter = 0; int bCalibrated = 0; protected String devicName; protected InputStream retina; protected OutputStream retinaVendor; public final PropertyChangeEvent NEW_EVENTS_PROPERTY_CHANGE = new PropertyChangeEvent(this, "NewEvents", null, null); protected AEPacketRawPool aePacketRawPool = new AEPacketRawPool(); private int lastshortts = 0; private final int NUM_BIASES = 12; // number of biases, to renumber biases for bias command private boolean DEBUG = false; //AEUnicastInput input = null; //InetSocketAddress client = null; public eDVS128_HardwareInterface(String deviceName) throws FileNotFoundException { //this.interfaceNumber = devNumber; try { CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(deviceName); if (portIdentifier.isCurrentlyOwned()) { log.warning("Error: Port " + deviceName + " is currently in use"); } else { CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000); if (commPort instanceof SerialPort) { SerialPort serialPort = (SerialPort) commPort; serialPort.setSerialPortParams(BAUD_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN); serialPort.setFlowControlMode(serialPort.FLOWCONTROL_RTSCTS_OUT); retina = serialPort.getInputStream(); retinaVendor = serialPort.getOutputStream(); } } } catch (Exception e) { log.warning("When trying to construct an interface on port " + deviceName + " caught " + e.toString()); throw new FileNotFoundException("Port "+deviceName+" already owned by another process?"); } catch(Error er){ log.warning("Caught error "+er.toString()+"; this usually means port is owned by another process"); throw new FileNotFoundException("Port "+deviceName+" already owned by another process?"); } } @Override public void open() throws HardwareInterfaceException { if (retinaVendor == null) { throw new HardwareInterfaceException("no serial interface to open"); } if (!isOpen) { try { String s = "!E1\n"; byte[] b = s.getBytes(); retinaVendor.write(b, 0, 4); s = "E+\n"; b = s.getBytes(); retinaVendor.write(b, 0, 3); isOpen = true; } catch (Exception e) { e.printStackTrace(); } } /* if (!isOpen){ try{ if ( input != null ){ input.close(); } input = new AEUnicastInput(STREAM_PORT); input.setSequenceNumberEnabled(false); input.setAddressFirstEnabled(true); input.setSwapBytesEnabled(true); input.set4ByteAddrTimestampEnabled(true); input.setTimestampsEnabled(true); input.setLocalTimestampEnabled(true); input.setBufferSize(1200); input.setTimestampMultiplier(0.001f); input.open(); isOpen = true; } catch ( IOException ex ){ throw new HardwareInterfaceException(ex.toString()); } }*/ } @Override public boolean isOpen() { return true; } @Override public void close() { if (retinaVendor == null) { return; } try { String s = "E-\n"; byte[] b = s.getBytes(); retinaVendor.write(b, 0, 3); isOpen = false; } catch (Exception e) { e.printStackTrace(); } } @Override public String getTypeName() { return "eDVS128"; } @Override public void setChip(AEChip chip) { this.chip = chip; if(chip==null) return; if (!addedBiasListeners && chip instanceof DVS128) { addedBiasListeners = true; DVS128 dvs128=(DVS128)chip; ArrayList<Pot> pots = dvs128.getBiasgen().getPotArray().getPots(); for (Pot p : pots) { p.addObserver(this); // TODO first send won't work } } } @Override public AEChip getChip() { return chip; } @Override final public int getTimestampTickUs() { return 1; } private int estimatedEventRate = 0; @Override public int getEstimatedEventRate() { return estimatedEventRate; } @Override public int getMaxCapacity() { return 156250000; } @Override public void addAEListener(AEListener listener) { support.addPropertyChangeListener(listener); } @Override public void removeAEListener(AEListener listener) { support.removePropertyChangeListener(listener); } @Override public void setEventAcquisitionEnabled(boolean enable) throws HardwareInterfaceException { if (enable) { //startAer(); startAEReader(); } else { //stopAer(); stopAEReader(); } } @Override public boolean isEventAcquisitionEnabled() { return eventAcquisitionEnabled; } @Override public int getAEBufferSize() { return aeBufferSize; // aePacketRawPool.writeBuffer().getCapacity(); } @Override public void setAEBufferSize(int size) { if (size < 1000 || size > 1000000) { log.warning("ignoring unreasonable aeBufferSize of " + size + ", choose a more reasonable size between 1000 and 1000000"); return; } this.aeBufferSize = size; prefs.putInt("eDVS128.aeBufferSize", aeBufferSize); } @Override public boolean overrunOccurred() { return overrunOccuredFlag; } /** Resets the timestamp unwrap value, and resets the AEPacketRawPool. */ @Override synchronized public void resetTimestamps() { wrapAdd=0; //TODO call TDS to reset timestamps aePacketRawPool.reset(); } /** returns last events from {@link #acquireAvailableEventsFromDriver} *@return the event packet */ @Override public AEPacketRaw getEvents() { return this.lastEventsAcquired; } /** Returns the number of events acquired by the last call to {@link * #acquireAvailableEventsFromDriver } * @return number of events acquired */ @Override public int getNumEventsAcquired() { return lastEventsAcquired.getNumEvents(); } @Override public AEPacketRaw acquireAvailableEventsFromDriver() throws HardwareInterfaceException { if (!eventAcquisitionEnabled) { setEventAcquisitionEnabled(true); } int nEvents; aePacketRawPool.swap(); lastEventsAcquired = aePacketRawPool.readBuffer(); nEvents = lastEventsAcquired.getNumEvents(); eventCounter = 0; computeEstimatedEventRate(lastEventsAcquired); if (nEvents != 0) { support.firePropertyChange(NEW_EVENTS_PROPERTY_CHANGE); // call listeners } return lastEventsAcquired; } synchronized public void vendorRequest(int cmd) { try { switch (cmd) { case 1: byte[] command = new byte[]{'E', '+', '\r', '\n'}; retinaVendor.write(command, 0, 4); break; case 2: //byte[] command = new byte[]{'E','-','\n'}; //retinaVendor.write(command,0,3); break; } } catch (Exception e) { e.printStackTrace(); } } /** computes the estimated event rate for a packet of events */ void computeEstimatedEventRate(AEPacketRaw events) { if (events == null || events.getNumEvents() < 2) { estimatedEventRate = 0; } else { int[] ts = events.getTimestamps(); int n = events.getNumEvents(); int dt = ts[n - 1] - ts[0]; estimatedEventRate = (int) (1e6f * (float) n / (float) dt); } } @Override public void setPowerDown(boolean powerDown) { log.warning("Power down not supported by eDVS128 devices."); } private boolean addedBiasListeners = false; @Override public void sendConfiguration(Biasgen biasgen) throws HardwareInterfaceException { // comes here when bias values should be sent, but we don't know which one should be sent from this call. } @Override public void flashConfiguration(Biasgen biasgen) { log.warning("Flash configuration not supported by eDVS128 devices."); } @Override public byte[] formatConfigurationBytes(Biasgen biasgen) { throw new UnsupportedOperationException("Not supported yet.");// TODO use this to send all biases at once? yes, this is how the on-chip bias generator works } @Override public String toString() { return "Serial: eDVS128"; } protected boolean running = true; final int WRAP = 0x10000; // amount of timestamp wrap to add for each overflow of 1 bit timestamps final int WRAP_START = 0; //(int)(0xFFFFFFFFL&(2147483648L-0x400000L)); // set high to test big wrap 1<<30; volatile int wrapAdd = WRAP_START; //0; protected AEReader aeReader = null; public AEReader getAeReader() { return aeReader; } public void setAeReader(AEReader aeReader) { this.aeReader = aeReader; } public void startAEReader() { setAeReader(new AEReader(this)); log.info("Start AE reader..."); getAeReader().start(); eventAcquisitionEnabled = true; } public void stopAEReader() { if (getAeReader() != null) { // close device getAeReader().finish(); setAeReader(null); releaseInterface(); } } synchronized void claimInterface() { } synchronized public void releaseInterface() { } /** Called when notifyObservers is called in Observable we are watching, e.g. biasgen */ @Override synchronized public void update(Observable o, Object arg) { if (o instanceof IPot) { if (retinaVendor == null) { log.warning("no connection; null serial device"); return; } IPot p = (IPot) o; int v = p.getBitValue(); int n = NUM_BIASES-1-p.getShiftRegisterNumber(); // eDVS firmware numbers in reverse order from DVS firmware, we want shift register 0 to become 11 on the eDVS String s = String.format("!B%d=%d\n", n, v); // LPC210 has 16-byte serial buffer, hopefully fits if(DEBUG) log.info("sending command "+s+" for pot "+p+" at bias position "+n); // note that eDVS must have rev1 firmware for BF command to work. byte[] b = s.getBytes(); if(b.length>16) log.warning("sending "+b.length+" bytes, might not fit in eDVS LPC2016 16-byte buffer"); try { retinaVendor.write(b, 0, b.length); } catch (IOException ex) { log.warning(ex.toString()); } s="!BF\n"; b=s.getBytes(); try { retinaVendor.write(b, 0, b.length); } catch (IOException ex) { log.warning(ex.toString()); } } } public class AEReader extends Thread implements Runnable { private byte[] buffer = null; eDVS128_HardwareInterface monitor; public AEReader(eDVS128_HardwareInterface monitor) { this.monitor = monitor; /* This is a list of all this interface's endpoints. */ allocateAEBuffers(); buffer = new byte[8192 * 4];//UsbUtil.unsignedInt(usbPipe.getUsbEndpoint().getUsbEndpointDescriptor().wMaxPacketSize())]; } public void run() { int offset = 0; int length = 0; int len = 0; while (running) { try { len = retina.available(); if(len==0){ try { Thread.sleep(10); } catch (InterruptedException ex) { log.warning("sleep interrupted while waiting events"); } continue; } length = retina.read(buffer, 0, len - (len % 4)); // System.out.println(length); } catch (IOException e) { e.printStackTrace(); } int nDump = 0; if (len > 3) { // try { // length = retina.read(buffer, 0, len - (len % 4)); // } catch (IOException e) { // e.printStackTrace(); // } translateEvents_code(buffer, length); if (bCalibrated == 0) { int diff = 0; if (length > 100) { for (int i = 0; i <= 3; i++) { //offset=i; diff = 0; for (int m = 0; m < 10; m++) { diff += (int) (buffer[4 * (m + 1) + i] - buffer[4 * m + i]) * (int) (buffer[4 * (m + 1) + i] - buffer[4 * m + i]); } //System.out.println(diff); if (diff < 20) { //10 offset = i; //break; } } } //System.out.println("length: " + length + " tail: " + nTail + " offset: " + offset); switch (offset) { case 0: nDump = 2; break; case 1: nDump = 3; break; case 2: nDump = 0; break; case 3: nDump = 1; break; default: log.info("Achtung, error"); } if (nDump != 0) { long length1 = 0; long len1 = 0; try { while (length1 != nDump) { //len = retina.read(buffer, length1, nDump - length1); len1 = retina.skip(nDump - length1); length1 = length1 + len1; } } catch (IOException e) { e.printStackTrace(); } log.info("Dumped: " + length1 + " bytes / " + nDump); } else { bCalibrated = 1; log.info("Calibrated"); } } } if (timestampsReset) { log.info("timestampsReset: flushing aePacketRawPool buffers"); aePacketRawPool.reset(); timestampsReset = false; } } } /** * Stop/abort listening for data events. */ synchronized public void finish() { running = false; } synchronized public void resetTimestamps() { log.info(eDVS128_HardwareInterface.this + ": wrapAdd=" + wrapAdd + ", zeroing it"); wrapAdd = WRAP_START; timestampsReset = true; // will inform reader thread that timestamps are reset } protected boolean running = true; volatile boolean timestampsReset = false; // used to tell processData that another thread has reset timestamps } private int inputProcessingIndex = 0; private int pixelX, pixelY, pixelP; private String specialData; private int bCali = 1; private long lastWrapTime=0; protected void translateEvents_code(byte[] b, int bytesSent) { synchronized (aePacketRawPool) { AEPacketRaw buffer = aePacketRawPool.writeBuffer(); int shortts; int[] addresses = buffer.getAddresses(); int[] timestamps = buffer.getTimestamps(); // write the start of the packet buffer.lastCaptureIndex = eventCounter; // log.info("entering translateEvents_code with "+eventCounter+" events"); StringBuilder sb = null; if (DEBUG) { sb = new StringBuilder(String.format("%d events: Timestamp deltas are ", bytesSent / 4)); } for (int i = 0; i < bytesSent; i += 4) { /* event polarity is encoded in the msb of the second byte. i.e. Byte0, bit 7: always zero Byte0, bits 6-0: event address y Byte1, bit 7: event polarity Byte1, bits 6-0: event address x Bytes2+3: 16 bit timestamp, MSB first */ int y_ = (0xff & b[i]); // & with 0xff to prevent sign bit from extending to int (treat byte as unsigned) int x_ = (0xff & b[i + 1]); int c_ = (0xff & b[i + 2]); int d_ = (0xff & b[i + 3]); // if ( (y_ & 0x80) != 0){ // System.out.println("Data not aligned!"); // } if(eventCounter>=buffer.getCapacity()){ buffer.overrunOccuredFlag=true; continue; } addresses[eventCounter] = (int) ((x_ & cHighBitMask) >> 7 | ((y_ & cLowerBitsMask) << 8) | ((x_ & cLowerBitsMask) << 1)) & 0x7FFF; //timestamps[eventCounter] = (c_ | (d_ << 8)); shortts = ((c_ << 8) + d_); // should be unsigned since c_ and d_ are unsigned, timestamp is sent big endian, MSB first at index 3 if (lastshortts > shortts) { // timetamp wrapped wrapAdd+=WRAP; long thisWrapTime=System.nanoTime(); if(DEBUG) log.info("This timestamp was less than last one by "+(shortts-lastshortts)+" and system deltaT="+(thisWrapTime-lastWrapTime)/1000+"us, wrapAdd="+(wrapAdd/WRAP)+" wraps"); lastWrapTime=thisWrapTime; } timestamps[eventCounter] = (wrapAdd + shortts) / TICK_DIVIDER; if (DEBUG) { sb.append(String.format("%d ", shortts-lastshortts)); } lastshortts = shortts; eventCounter++; } if (DEBUG) { log.info(sb.toString()); } buffer.setNumEvents(eventCounter); // write capture size buffer.lastCaptureLength = eventCounter - buffer.lastCaptureIndex; } // sync on aePacketRawPool } void allocateAEBuffers() { synchronized (aePacketRawPool) { aePacketRawPool.allocateMemory(); } } /** Double buffer for writing and reading events. */ private class AEPacketRawPool { int capacity; AEPacketRaw[] buffers; AEPacketRaw lastBufferReference; volatile int readBuffer = 0, writeBuffer = 1; // this buffer is the one currently being read from AEPacketRawPool() { allocateMemory(); reset(); } /** Swaps read and write buffers in preparation for reading last captured bufffer of events. * */ synchronized final void swap() { lastBufferReference = buffers[readBuffer]; if (readBuffer == 0) { readBuffer = 1; writeBuffer = 0; } else { readBuffer = 0; writeBuffer = 1; } writeBuffer().clear(); writeBuffer().overrunOccuredFlag = false; // mark new write buffer clean, no overrun happened yet. writer sets this if it happens // log.info("swapped buffers - new read buffer has "+readBuffer().getNumEvents()+" events"); } /** Returns the current read buffer. * @return buffer to read from */ synchronized final AEPacketRaw readBuffer() { return buffers[readBuffer]; } /** Returns the current writing buffer. Does not swap buffers. * @return buffer to write to @see #swap */ synchronized final AEPacketRaw writeBuffer() { return buffers[writeBuffer]; } /** Set the current buffer to be the first one and clear the write buffer */ synchronized final void reset() { readBuffer = 0; writeBuffer = 1; buffers[writeBuffer].clear(); // new events go into this buffer which should be empty buffers[readBuffer].clear(); // clear read buffer in case this buffer was reset by resetTimestamps // log.info("buffers reset"); } // allocates AEPacketRaw each with capacity AE_BUFFER_SIZE private void allocateMemory() { buffers = new AEPacketRaw[2]; for (int i = 0; i < buffers.length; i++) { buffers[i] = new AEPacketRaw(); buffers[i].ensureCapacity(getAEBufferSize()); // preallocate this memory for capture thread and to try to make it contiguous } } } }
src/net/sf/jaer/hardwareinterface/serial/eDVS128/eDVS128_HardwareInterface.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.sf.jaer.hardwareinterface.serial.eDVS128; import java.io.*; import java.beans.*; import java.util.Observable; import java.util.logging.Logger; import java.util.prefs.*; import net.sf.jaer.aemonitor.*; import net.sf.jaer.chip.*; import net.sf.jaer.biasgen.*; import net.sf.jaer.hardwareinterface.*; import net.sf.jaer.hardwareinterface.serial.*; import gnu.io.CommPort; import gnu.io.CommPortIdentifier; import gnu.io.SerialPort; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.Math.*; import java.util.ArrayList; import java.util.Observer; import ch.unizh.ini.jaer.chip.retina.DVS128; /** * Interface to eDVS128 camera. * * This camera uses 4Mbaud 8 bits 1 stop no parity with RTS/CTS. * * The camera returns the following help * <pre> * DVS128 - LPC2106/01 Interface Board, V6.0: Apr 25 2011, 13:09:50 System Clock: 64MHz / 64 -> 1000ns event time resolution Modules: Supported Commands: E+/- - enable/disable event sending !Ex - specify event data format, ??E to list options B - send bias settings to DVS !Bx=y - set bias register x[0..11] to value y[0..0xFFFFFF] ?Bx - get bias register x current value !R+/- - transmit event rate on/off 0,1,2 - LED off/on/blinking !S=x - set baudrate to x R - reset board P - enter reprogramming mode ?? - display help ??E !E0 - 2 bytes per event binary 0yyyyyyy.pxxxxxxx (default) !E1 - 4 bytes per event (as above followed by 16bit timestamp) !E10 - 3 bytes per event, 6bit encoded !E11 - 6 bytes per event+timestamp, 6bit encoded !E12 - 4 bytes per event, 6bit encoded; new-line !E13 - 7 bytes per event+timestamp, 6bit encoded; new-line !E20 - 4 bytes per event, hex encoded !E21 - 8 bytes per event+timestamp, hex encoded !E22 - 5 bytes per event, hex encoded; new-line !E23 - 8 bytes per event+timestamp, hex encoded; new-line !E30 - 10 bytes per event, ASCII <1p> <3y> <3x>; new-line !E31 - 10 bytes per event+timestamp, ASCII <1p> <3y> <3x> <5ts>; new-line * </pre> * * @author lou */ public class eDVS128_HardwareInterface implements SerialInterface, HardwareInterface, AEMonitorInterface, BiasgenHardwareInterface, Observer { public static final int BAUD_RATE = 4000000; protected static Preferences prefs = Preferences.userNodeForPackage(eDVS128_HardwareInterface.class); public PropertyChangeSupport support = new PropertyChangeSupport(this); protected Logger log = Logger.getLogger("eDVS128"); protected AEChip chip; /** Timestamp tick on eDVS in us - this is default value */ public final int TICK_US = 1; protected AEPacketRaw lastEventsAcquired = new AEPacketRaw(); public static final int AE_BUFFER_SIZE = 100000; // should handle 5Meps at 30FPS protected int aeBufferSize = prefs.getInt("eDVS128.aeBufferSize", AE_BUFFER_SIZE); protected int interfaceNumber = 0; public static boolean isOpen = false; public static boolean eventAcquisitionEnabled = false; public static boolean overrunOccuredFlag = false; protected byte cHighBitMask = (byte) 0x80; protected byte cLowerBitsMask = (byte) 0x7F; int eventCounter = 0; int bCalibrated = 0; protected String devicName; protected InputStream retina; protected OutputStream retinaVendor; public final PropertyChangeEvent NEW_EVENTS_PROPERTY_CHANGE = new PropertyChangeEvent(this, "NewEvents", null, null); protected AEPacketRawPool aePacketRawPool = new AEPacketRawPool(); private int lastshortts = 0; private final int NUM_BIASES = 12; // number of biases, to renumber biases for bias command private boolean DEBUG = false; //AEUnicastInput input = null; //InetSocketAddress client = null; public eDVS128_HardwareInterface(String deviceName) throws FileNotFoundException { //this.interfaceNumber = devNumber; try { CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(deviceName); if (portIdentifier.isCurrentlyOwned()) { log.warning("Error: Port " + deviceName + " is currently in use"); } else { CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000); if (commPort instanceof SerialPort) { SerialPort serialPort = (SerialPort) commPort; serialPort.setSerialPortParams(BAUD_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN); serialPort.setFlowControlMode(serialPort.FLOWCONTROL_RTSCTS_OUT); retina = serialPort.getInputStream(); retinaVendor = serialPort.getOutputStream(); } } } catch (Exception e) { log.warning("When trying to construct an interface on port " + deviceName + " caught " + e.toString()); throw new FileNotFoundException("Port "+deviceName+" already owned by another process?"); } catch(Error er){ log.warning("Caught error "+er.toString()+"; this usually means port is owned by another process"); throw new FileNotFoundException("Port "+deviceName+" already owned by another process?"); } } @Override public void open() throws HardwareInterfaceException { if (retinaVendor == null) { throw new HardwareInterfaceException("no serial interface to open"); } if (!isOpen) { try { String s = "!E1\n"; byte[] b = s.getBytes(); retinaVendor.write(b, 0, 4); s = "E+\n"; b = s.getBytes(); retinaVendor.write(b, 0, 3); isOpen = true; } catch (Exception e) { e.printStackTrace(); } } /* if (!isOpen){ try{ if ( input != null ){ input.close(); } input = new AEUnicastInput(STREAM_PORT); input.setSequenceNumberEnabled(false); input.setAddressFirstEnabled(true); input.setSwapBytesEnabled(true); input.set4ByteAddrTimestampEnabled(true); input.setTimestampsEnabled(true); input.setLocalTimestampEnabled(true); input.setBufferSize(1200); input.setTimestampMultiplier(0.001f); input.open(); isOpen = true; } catch ( IOException ex ){ throw new HardwareInterfaceException(ex.toString()); } }*/ } @Override public boolean isOpen() { return true; } @Override public void close() { if (retinaVendor == null) { return; } try { String s = "E-\n"; byte[] b = s.getBytes(); retinaVendor.write(b, 0, 3); isOpen = false; } catch (Exception e) { e.printStackTrace(); } } @Override public String getTypeName() { return "eDVS128"; } @Override public void setChip(AEChip chip) { this.chip = chip; if(chip==null) return; if (!addedBiasListeners && chip instanceof DVS128) { addedBiasListeners = true; DVS128 dvs128=(DVS128)chip; ArrayList<Pot> pots = dvs128.getBiasgen().getPotArray().getPots(); for (Pot p : pots) { p.addObserver(this); // TODO first send won't work } } } @Override public AEChip getChip() { return chip; } @Override final public int getTimestampTickUs() { return TICK_US; } private int estimatedEventRate = 0; @Override public int getEstimatedEventRate() { return estimatedEventRate; } @Override public int getMaxCapacity() { return 156250000; } @Override public void addAEListener(AEListener listener) { support.addPropertyChangeListener(listener); } @Override public void removeAEListener(AEListener listener) { support.removePropertyChangeListener(listener); } @Override public void setEventAcquisitionEnabled(boolean enable) throws HardwareInterfaceException { if (enable) { //startAer(); startAEReader(); } else { //stopAer(); stopAEReader(); } } @Override public boolean isEventAcquisitionEnabled() { return eventAcquisitionEnabled; } @Override public int getAEBufferSize() { return aeBufferSize; // aePacketRawPool.writeBuffer().getCapacity(); } @Override public void setAEBufferSize(int size) { if (size < 1000 || size > 1000000) { log.warning("ignoring unreasonable aeBufferSize of " + size + ", choose a more reasonable size between 1000 and 1000000"); return; } this.aeBufferSize = size; prefs.putInt("eDVS128.aeBufferSize", aeBufferSize); } @Override public boolean overrunOccurred() { return overrunOccuredFlag; } /** Resets the timestamp unwrap value, and resets the AEPacketRawPool. */ @Override synchronized public void resetTimestamps() { wrapAdd=0; //TODO call TDS to reset timestamps aePacketRawPool.reset(); } /** returns last events from {@link #acquireAvailableEventsFromDriver} *@return the event packet */ @Override public AEPacketRaw getEvents() { return this.lastEventsAcquired; } /** Returns the number of events acquired by the last call to {@link * #acquireAvailableEventsFromDriver } * @return number of events acquired */ @Override public int getNumEventsAcquired() { return lastEventsAcquired.getNumEvents(); } @Override public AEPacketRaw acquireAvailableEventsFromDriver() throws HardwareInterfaceException { if (!eventAcquisitionEnabled) { setEventAcquisitionEnabled(true); } int nEvents; aePacketRawPool.swap(); lastEventsAcquired = aePacketRawPool.readBuffer(); nEvents = lastEventsAcquired.getNumEvents(); eventCounter = 0; computeEstimatedEventRate(lastEventsAcquired); if (nEvents != 0) { support.firePropertyChange(NEW_EVENTS_PROPERTY_CHANGE); // call listeners } return lastEventsAcquired; } synchronized public void vendorRequest(int cmd) { try { switch (cmd) { case 1: byte[] command = new byte[]{'E', '+', '\r', '\n'}; retinaVendor.write(command, 0, 4); break; case 2: //byte[] command = new byte[]{'E','-','\n'}; //retinaVendor.write(command,0,3); break; } } catch (Exception e) { e.printStackTrace(); } } /** computes the estimated event rate for a packet of events */ void computeEstimatedEventRate(AEPacketRaw events) { if (events == null || events.getNumEvents() < 2) { estimatedEventRate = 0; } else { int[] ts = events.getTimestamps(); int n = events.getNumEvents(); int dt = ts[n - 1] - ts[0]; estimatedEventRate = (int) (1e6f * (float) n / (float) dt); } } @Override public void setPowerDown(boolean powerDown) { log.warning("Power down not supported by eDVS128 devices."); } private boolean addedBiasListeners = false; @Override public void sendConfiguration(Biasgen biasgen) throws HardwareInterfaceException { // comes here when bias values should be sent, but we don't know which one should be sent from this call. } @Override public void flashConfiguration(Biasgen biasgen) { log.warning("Flash configuration not supported by eDVS128 devices."); } @Override public byte[] formatConfigurationBytes(Biasgen biasgen) { throw new UnsupportedOperationException("Not supported yet.");// TODO use this to send all biases at once? yes, this is how the on-chip bias generator works } @Override public String toString() { return "Serial: eDVS128"; } protected boolean running = true; final int WRAP = 0x10000; // amount of timestamp wrap to add for each overflow of 1 bit timestamps final int WRAP_START = 0; //(int)(0xFFFFFFFFL&(2147483648L-0x400000L)); // set high to test big wrap 1<<30; volatile int wrapAdd = WRAP_START; //0; protected AEReader aeReader = null; public AEReader getAeReader() { return aeReader; } public void setAeReader(AEReader aeReader) { this.aeReader = aeReader; } public void startAEReader() { setAeReader(new AEReader(this)); log.info("Start AE reader..."); getAeReader().start(); eventAcquisitionEnabled = true; } public void stopAEReader() { if (getAeReader() != null) { // close device getAeReader().finish(); setAeReader(null); releaseInterface(); } } synchronized void claimInterface() { } synchronized public void releaseInterface() { } /** Called when notifyObservers is called in Observable we are watching, e.g. biasgen */ @Override synchronized public void update(Observable o, Object arg) { if (o instanceof IPot) { if (retinaVendor == null) { log.warning("no connection; null serial device"); return; } IPot p = (IPot) o; int v = p.getBitValue(); int n = NUM_BIASES-1-p.getShiftRegisterNumber(); // eDVS firmware numbers in reverse order from DVS firmware, we want shift register 0 to become 11 on the eDVS String s = String.format("!B%d=%d\n", n, v); // LPC210 has 16-byte serial buffer, hopefully fits if(DEBUG) log.info("sending command "+s+" for pot "+p+" at bias position "+n); // note that eDVS must have rev1 firmware for BF command to work. byte[] b = s.getBytes(); if(b.length>16) log.warning("sending "+b.length+" bytes, might not fit in eDVS LPC2016 16-byte buffer"); try { retinaVendor.write(b, 0, b.length); } catch (IOException ex) { log.warning(ex.toString()); } s="!BF\n"; b=s.getBytes(); try { retinaVendor.write(b, 0, b.length); } catch (IOException ex) { log.warning(ex.toString()); } } } public class AEReader extends Thread implements Runnable { private byte[] buffer = null; eDVS128_HardwareInterface monitor; public AEReader(eDVS128_HardwareInterface monitor) { this.monitor = monitor; /* This is a list of all this interface's endpoints. */ allocateAEBuffers(); buffer = new byte[8192 * 4];//UsbUtil.unsignedInt(usbPipe.getUsbEndpoint().getUsbEndpointDescriptor().wMaxPacketSize())]; } public void run() { int offset = 0; int length = 0; int len = 0; while (running) { try { len = retina.available(); length = retina.read(buffer, 0, len - (len % 4)); // System.out.println(length); } catch (IOException e) { e.printStackTrace(); } int nDump = 0; if (len > 3) { // try { // length = retina.read(buffer, 0, len - (len % 4)); // } catch (IOException e) { // e.printStackTrace(); // } translateEvents_code(buffer, length); if (bCalibrated == 0) { int diff = 0; if (length > 100) { for (int i = 0; i <= 3; i++) { //offset=i; diff = 0; for (int m = 0; m < 10; m++) { diff += (int) (buffer[4 * (m + 1) + i] - buffer[4 * m + i]) * (int) (buffer[4 * (m + 1) + i] - buffer[4 * m + i]); } //System.out.println(diff); if (diff < 20) { //10 offset = i; //break; } } } //System.out.println("length: " + length + " tail: " + nTail + " offset: " + offset); switch (offset) { case 0: nDump = 2; break; case 1: nDump = 3; break; case 2: nDump = 0; break; case 3: nDump = 1; break; default: log.info("Achtung, error"); } if (nDump != 0) { long length1 = 0; long len1 = 0; try { while (length1 != nDump) { //len = retina.read(buffer, length1, nDump - length1); len1 = retina.skip(nDump - length1); length1 = length1 + len1; } } catch (IOException e) { e.printStackTrace(); } log.info("Dumped: " + length1 + " bytes / " + nDump); } else { bCalibrated = 1; log.info("Calibrated"); } } } if (timestampsReset) { log.info("timestampsReset: flushing aePacketRawPool buffers"); aePacketRawPool.reset(); timestampsReset = false; } } } synchronized private void submit(int BufNumber) { } /** * Stop/abort listening for data events. */ synchronized public void finish() { running = false; } synchronized public void resetTimestamps() { log.info(eDVS128_HardwareInterface.this + ": wrapAdd=" + wrapAdd + ", zeroing it"); wrapAdd = WRAP_START; timestampsReset = true; // will inform reader thread that timestamps are reset } protected boolean running = true; volatile boolean timestampsReset = false; // used to tell processData that another thread has reset timestamps } private int inputProcessingIndex = 0; private int pixelX, pixelY, pixelP; private String specialData; private int bCali = 1; private long lastWrapTime=0; protected void translateEvents_code(byte[] b, int bytesSent) { synchronized (aePacketRawPool) { eventCounter = 0; AEPacketRaw buffer = aePacketRawPool.writeBuffer(); int shortts; int[] addresses = buffer.getAddresses(); int[] timestamps = buffer.getTimestamps(); // write the start of the packet buffer.lastCaptureIndex = eventCounter; StringBuilder sb = null; if (DEBUG) { sb = new StringBuilder(String.format("%d events: Timestamp deltas are ", bytesSent / 4)); } for (int i = 0; i < bytesSent; i += 4) { /* event polarity is encoded in the msb of the second byte. i.e. Byte0, bit 7: always zero Byte0, bits 6-0: event address y Byte1, bit 7: event polarity Byte1, bits 6-0: event address x Bytes2+3: 16 bit timestamp, MSB first */ int y_ = (0xff & b[i]); // & with 0xff to prevent sign bit from extending to int (treat byte as unsigned) int x_ = (0xff & b[i + 1]); int c_ = (0xff & b[i + 2]); int d_ = (0xff & b[i + 3]); // if ( (y_ & 0x80) != 0){ // System.out.println("Data not aligned!"); // } addresses[eventCounter] = (int) ((x_ & cHighBitMask) >> 7 | ((y_ & cLowerBitsMask) << 8) | ((x_ & cLowerBitsMask) << 1)) & 0x7FFF; //timestamps[eventCounter] = (c_ | (d_ << 8)); shortts = ((0xffff & (d_ << 8)) + c_); // should be unsigned since c_ and d_ are unsigned if (lastshortts > shortts) { // timetamp wrapped wrapAdd+=WRAP; long thisWrapTime=System.nanoTime(); if(DEBUG) log.info("This timestamp was less than last one by "+(shortts-lastshortts)+" and system deltaT="+(thisWrapTime-lastWrapTime)/1000+"us, wrapAdd="+(wrapAdd/WRAP)+" wraps"); lastWrapTime=thisWrapTime; } timestamps[eventCounter] = (wrapAdd + shortts) * TICK_US; if (DEBUG) { sb.append(String.format("%d ", shortts-lastshortts)); } lastshortts = shortts; eventCounter++; } if (DEBUG) { log.info(sb.toString()); } buffer.setNumEvents(eventCounter); // write capture size buffer.lastCaptureLength = eventCounter - buffer.lastCaptureIndex; } // sync on aePacketRawPool } void allocateAEBuffers() { synchronized (aePacketRawPool) { aePacketRawPool.allocateMemory(); } } private class AEPacketRawPool { int capacity; AEPacketRaw[] buffers; AEPacketRaw lastBufferReference; volatile int readBuffer = 0, writeBuffer = 1; // this buffer is the one currently being read from AEPacketRawPool() { allocateMemory(); reset(); } synchronized final void swap() { lastBufferReference = buffers[readBuffer]; if (readBuffer == 0) { readBuffer = 1; writeBuffer = 0; } else { readBuffer = 0; writeBuffer = 1; } writeBuffer().clear(); writeBuffer().overrunOccuredFlag = false; // mark new write buffer clean, no overrun happened yet. writer sets this if it happens } /** @return buffer to read from */ synchronized final AEPacketRaw readBuffer() { return buffers[readBuffer]; } /** @return buffer to write to */ synchronized final AEPacketRaw writeBuffer() { return buffers[writeBuffer]; } /** Set the current buffer to be the first one and clear the write buffer */ synchronized final void reset() { readBuffer = 0; writeBuffer = 1; buffers[writeBuffer].clear(); // new events go into this buffer which should be empty buffers[readBuffer].clear(); // clear read buffer in case this buffer was reset by resetTimestamps // log.info("buffers reset"); } // allocates AEPacketRaw each with capacity AE_BUFFER_SIZE private void allocateMemory() { buffers = new AEPacketRaw[2]; for (int i = 0; i < buffers.length; i++) { buffers[i] = new AEPacketRaw(); buffers[i].ensureCapacity(getAEBufferSize()); // preallocate this memory for capture thread and to try to make it contiguous } } } }
added fix from jorg for timestamp and added check for packet overrun in reader thread. now working! git-svn-id: e3d3b427d532171a6bd7557d8a4952a393b554a2@2857 b7f4320f-462c-0410-a916-d9f35bb82d52
src/net/sf/jaer/hardwareinterface/serial/eDVS128/eDVS128_HardwareInterface.java
added fix from jorg for timestamp and added check for packet overrun in reader thread. now working!
<ide><path>rc/net/sf/jaer/hardwareinterface/serial/eDVS128/eDVS128_HardwareInterface.java <ide> import java.io.*; <ide> import java.beans.*; <ide> import java.util.Observable; <add>import java.util.logging.Level; <ide> import java.util.logging.Logger; <ide> import java.util.prefs.*; <ide> <ide> public PropertyChangeSupport support = new PropertyChangeSupport(this); <ide> protected Logger log = Logger.getLogger("eDVS128"); <ide> protected AEChip chip; <del> /** Timestamp tick on eDVS in us - this is default value */ <del> public final int TICK_US = 1; <add> /** Amount by which we need to divide the received timestamp values to get us timestamps. */ <add> public final int TICK_DIVIDER = 1; <ide> protected AEPacketRaw lastEventsAcquired = new AEPacketRaw(); <ide> public static final int AE_BUFFER_SIZE = 100000; // should handle 5Meps at 30FPS <ide> protected int aeBufferSize = prefs.getInt("eDVS128.aeBufferSize", AE_BUFFER_SIZE); <ide> <ide> @Override <ide> final public int getTimestampTickUs() { <del> return TICK_US; <add> return 1; <ide> } <ide> private int estimatedEventRate = 0; <ide> <ide> while (running) { <ide> try { <ide> len = retina.available(); <add> if(len==0){ <add> try { <add> Thread.sleep(10); <add> } catch (InterruptedException ex) { <add> log.warning("sleep interrupted while waiting events"); <add> } <add> continue; <add> } <ide> length = retina.read(buffer, 0, len - (len % 4)); <ide> // System.out.println(length); <ide> } catch (IOException e) { <ide> <ide> } <ide> <del> synchronized private void submit(int BufNumber) { <del> } <del> <ide> /** <ide> * Stop/abort listening for data events. <ide> */ <ide> <ide> protected void translateEvents_code(byte[] b, int bytesSent) { <ide> synchronized (aePacketRawPool) { <del> eventCounter = 0; <ide> <ide> AEPacketRaw buffer = aePacketRawPool.writeBuffer(); <ide> int shortts; <ide> <ide> // write the start of the packet <ide> buffer.lastCaptureIndex = eventCounter; <add>// log.info("entering translateEvents_code with "+eventCounter+" events"); <ide> <ide> StringBuilder sb = null; <ide> if (DEBUG) { <ide> // System.out.println("Data not aligned!"); <ide> // } <ide> <add> if(eventCounter>=buffer.getCapacity()){ <add> buffer.overrunOccuredFlag=true; <add> continue; <add> } <ide> addresses[eventCounter] = (int) ((x_ & cHighBitMask) >> 7 | ((y_ & cLowerBitsMask) << 8) | ((x_ & cLowerBitsMask) << 1)) & 0x7FFF; <ide> //timestamps[eventCounter] = (c_ | (d_ << 8)); <ide> <del> shortts = ((0xffff & (d_ << 8)) + c_); // should be unsigned since c_ and d_ are unsigned <add> shortts = ((c_ << 8) + d_); // should be unsigned since c_ and d_ are unsigned, timestamp is sent big endian, MSB first at index 3 <ide> if (lastshortts > shortts) { // timetamp wrapped <ide> wrapAdd+=WRAP; <ide> long thisWrapTime=System.nanoTime(); <ide> if(DEBUG) log.info("This timestamp was less than last one by "+(shortts-lastshortts)+" and system deltaT="+(thisWrapTime-lastWrapTime)/1000+"us, wrapAdd="+(wrapAdd/WRAP)+" wraps"); <ide> lastWrapTime=thisWrapTime; <ide> } <del> timestamps[eventCounter] = (wrapAdd + shortts) * TICK_US; <add> timestamps[eventCounter] = (wrapAdd + shortts) / TICK_DIVIDER; <ide> if (DEBUG) { <ide> sb.append(String.format("%d ", shortts-lastshortts)); <ide> } <ide> } <ide> } <ide> <add> /** Double buffer for writing and reading events. */ <ide> private class AEPacketRawPool { <ide> <ide> int capacity; <ide> reset(); <ide> } <ide> <add> /** Swaps read and write buffers in preparation for reading last captured bufffer of events. <add> * <add> */ <ide> synchronized final void swap() { <ide> lastBufferReference = buffers[readBuffer]; <ide> if (readBuffer == 0) { <ide> } <ide> writeBuffer().clear(); <ide> writeBuffer().overrunOccuredFlag = false; // mark new write buffer clean, no overrun happened yet. writer sets this if it happens <del> <del> } <del> <del> /** @return buffer to read from */ <add>// log.info("swapped buffers - new read buffer has "+readBuffer().getNumEvents()+" events"); <add> } <add> <add> /** Returns the current read buffer. <add> * @return buffer to read from */ <ide> synchronized final AEPacketRaw readBuffer() { <ide> return buffers[readBuffer]; <ide> } <ide> <del> /** @return buffer to write to */ <add> /** Returns the current writing buffer. Does not swap buffers. <add> * @return buffer to write to <add> @see #swap <add> */ <ide> synchronized final AEPacketRaw writeBuffer() { <ide> return buffers[writeBuffer]; <ide> }
Java
bsd-2-clause
e9c112b4c8a82a36004d3c8f5b321d830efe1f7a
0
FXMisc/RichTextFX,afester/RichTextFX,afester/RichTextFX,FXMisc/RichTextFX
package org.fxmisc.richtext; import static org.reactfx.EventStreams.*; import static org.reactfx.util.Tuples.*; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Optional; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.IntFunction; import java.util.function.IntSupplier; import java.util.function.IntUnaryOperator; import java.util.function.Predicate; import java.util.function.UnaryOperator; import javafx.application.ConditionalFeature; import javafx.application.Platform; import javafx.beans.NamedArg; import javafx.beans.binding.Bindings; import javafx.beans.property.BooleanProperty; import javafx.beans.property.DoubleProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener.Change; import javafx.collections.ObservableSet; import javafx.css.CssMetaData; import javafx.css.PseudoClass; import javafx.css.StyleConverter; import javafx.css.Styleable; import javafx.css.StyleableObjectProperty; import javafx.event.Event; import javafx.event.EventHandler; import javafx.geometry.BoundingBox; import javafx.geometry.Bounds; import javafx.geometry.Insets; import javafx.geometry.Point2D; import javafx.scene.Node; import javafx.scene.control.ContextMenu; import javafx.scene.control.IndexRange; import javafx.scene.input.InputMethodEvent; import javafx.scene.input.InputMethodRequests; import javafx.scene.input.InputMethodTextRun; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.CornerRadii; import javafx.scene.layout.Region; import javafx.scene.paint.Color; import javafx.scene.paint.Paint; import javafx.scene.shape.LineTo; import javafx.scene.shape.PathElement; import javafx.scene.text.TextFlow; import org.fxmisc.flowless.Cell; import org.fxmisc.flowless.VirtualFlow; import org.fxmisc.flowless.VirtualFlowHit; import org.fxmisc.flowless.Virtualized; import org.fxmisc.flowless.VirtualizedScrollPane; import org.fxmisc.richtext.model.Codec; import org.fxmisc.richtext.model.EditableStyledDocument; import org.fxmisc.richtext.model.GenericEditableStyledDocument; import org.fxmisc.richtext.model.Paragraph; import org.fxmisc.richtext.model.ReadOnlyStyledDocument; import org.fxmisc.richtext.model.PlainTextChange; import org.fxmisc.richtext.model.Replacement; import org.fxmisc.richtext.model.RichTextChange; import org.fxmisc.richtext.model.StyleSpans; import org.fxmisc.richtext.model.StyledDocument; import org.fxmisc.richtext.model.StyledSegment; import org.fxmisc.richtext.model.TextOps; import org.fxmisc.richtext.model.TwoDimensional; import org.fxmisc.richtext.model.TwoLevelNavigator; import org.fxmisc.richtext.event.MouseOverTextEvent; import org.fxmisc.richtext.util.SubscribeableContentsObsSet; import org.fxmisc.richtext.util.UndoUtils; import org.fxmisc.undo.UndoManager; import org.reactfx.EventStream; import org.reactfx.EventStreams; import org.reactfx.Guard; import org.reactfx.Subscription; import org.reactfx.Suspendable; import org.reactfx.SuspendableEventStream; import org.reactfx.SuspendableNo; import org.reactfx.collection.LiveList; import org.reactfx.collection.SuspendableList; import org.reactfx.util.Tuple2; import org.reactfx.value.Val; import org.reactfx.value.Var; /** * Text editing control that renders and edits a {@link EditableStyledDocument}. * * Accepts user input (keyboard, mouse) and provides API to assign style to text ranges. It is suitable for * syntax highlighting and rich-text editors. * * <h3>Adding Scrollbars to the Area</h3> * * <p>By default, scroll bars do not appear when the content spans outside of the viewport. * To add scroll bars, the area needs to be wrapped in a {@link VirtualizedScrollPane}. For example, </p> * <pre><code> * // shows area without scroll bars * InlineCssTextArea area = new InlineCssTextArea(); * * // add scroll bars that will display as needed * VirtualizedScrollPane&lt;InlineCssTextArea&gt; vsPane = new VirtualizedScrollPane&lt;&gt;(area); * * Parent parent = // creation code * parent.getChildren().add(vsPane) * </code></pre> * * <h3>Auto-Scrolling to the Caret</h3> * * <p>Every time the underlying {@link EditableStyledDocument} changes via user interaction (e.g. typing) through * the {@code GenericStyledArea}, the area will scroll to insure the caret is kept in view. However, this does not * occur if changes are done programmatically. For example, let's say the area is displaying the bottom part * of the area's {@link EditableStyledDocument} and some code changes something in the top part of the document * that is not currently visible. If there is no call to {@link #requestFollowCaret()} at the end of that code, * the area will not auto-scroll to that section of the document. The change will occur, and the user will continue * to see the bottom part of the document as before. If such a call is there, then the area will scroll * to the top of the document and no longer display the bottom part of it.</p> * <p>For example...</p> * <pre><code> * // assuming the user is currently seeing the top of the area * * // then changing the bottom, currently not visible part of the area... * int startParIdx = 40; * int startColPosition = 2; * int endParIdx = 42; * int endColPosition = 10; * * // ...by itself will not scroll the viewport to where the change occurs * area.replaceText(startParIdx, startColPosition, endParIdx, endColPosition, "replacement text"); * * // adding this line after the last modification to the area will cause the viewport to scroll to that change * // leaving the following line out will leave the viewport unaffected and the user will not notice any difference * area.requestFollowCaret(); * </code></pre> * * <p>Additionally, when overriding the default user-interaction behavior, remember to include a call * to {@link #requestFollowCaret()}.</p> * * <h3>Setting the area's {@link UndoManager}</h3> * * <p> * The default UndoManager can undo/redo either {@link PlainTextChange}s or {@link RichTextChange}s. To create * your own specialized version that may use changes different than these (or a combination of these changes * with others), create them using the convenient factory methods in {@link UndoUtils}. * </p> * * <h3>Overriding default keyboard behavior</h3> * * {@code GenericStyledArea} uses {@link javafx.scene.input.KeyEvent#KEY_TYPED KEY_TYPED} to handle ordinary * character input and {@link javafx.scene.input.KeyEvent#KEY_PRESSED KEY_PRESSED} to handle control key * combinations (including Enter and Tab). To add or override some keyboard * shortcuts, while keeping the rest in place, you would combine the default * event handler with a new one that adds or overrides some of the default * key combinations. * <p> * For example, this is how to bind {@code Ctrl+S} to the {@code save()} operation: * </p> * <pre><code> * import static javafx.scene.input.KeyCode.*; * import static javafx.scene.input.KeyCombination.*; * import static org.fxmisc.wellbehaved.event.EventPattern.*; * import static org.fxmisc.wellbehaved.event.InputMap.*; * * import org.fxmisc.wellbehaved.event.Nodes; * * // installs the following consume InputMap, * // so that a CTRL+S event saves the document and consumes the event * Nodes.addInputMap(area, consume(keyPressed(S, CONTROL_DOWN), event -&gt; save())); * </code></pre> * * <h3>Overriding default mouse behavior</h3> * * The area's default mouse behavior properly handles auto-scrolling and dragging the selected text to a new location. * As such, some parts cannot be partially overridden without it affecting other behavior. * * <p>The following lists either {@link org.fxmisc.wellbehaved.event.EventPattern}s that cannot be * overridden without negatively affecting the default mouse behavior or describe how to safely override things * in a special way without disrupting the auto scroll behavior.</p> * <ul> * <li> * <em>First (1 click count) Primary Button Mouse Pressed Events:</em> * (<code>EventPattern.mousePressed(MouseButton.PRIMARY).onlyIf(e -&gt; e.getClickCount() == 1)</code>). * Do not override. Instead, use {@link #onOutsideSelectionMousePressed}, * {@link #onInsideSelectionMousePressReleased}, or see next item. * </li> * <li>( * <em>All Other Mouse Pressed Events (e.g., Primary with 2+ click count):</em> * Aside from hiding the context menu if it is showing (use {@link #hideContextMenu()} some((where in your * overriding InputMap to maintain this behavior), these can be safely overridden via any of the * {@link org.fxmisc.wellbehaved.event.template.InputMapTemplate InputMapTemplate's factory methods} or * {@link org.fxmisc.wellbehaved.event.InputMap InputMap's factory methods}. * </li> * <li> * <em>Primary-Button-only Mouse Drag Detection Events:</em> * (<code>EventPattern.eventType(MouseEvent.DRAG_DETECTED).onlyIf(e -&gt; e.getButton() == MouseButton.PRIMARY &amp;&amp; !e.isMiddleButtonDown() &amp;&amp; !e.isSecondaryButtonDown())</code>). * Do not override. Instead, use {@link #onNewSelectionDrag} or {@link #onSelectionDrag}. * </li> * <li> * <em>Primary-Button-only Mouse Drag Events:</em> * (<code>EventPattern.mouseDragged().onlyIf(e -&gt; e.getButton() == MouseButton.PRIMARY &amp;&amp; !e.isMiddleButtonDown() &amp;&amp; !e.isSecondaryButtonDown())</code>) * Do not override, but see next item. * </li> * <li> * <em>All Other Mouse Drag Events:</em> * You may safely override other Mouse Drag Events using different * {@link org.fxmisc.wellbehaved.event.EventPattern}s without affecting default behavior only if * process InputMaps ( * {@link org.fxmisc.wellbehaved.event.template.InputMapTemplate#process(javafx.event.EventType, BiFunction)}, * {@link org.fxmisc.wellbehaved.event.template.InputMapTemplate#process(org.fxmisc.wellbehaved.event.EventPattern, BiFunction)}, * {@link org.fxmisc.wellbehaved.event.InputMap#process(javafx.event.EventType, Function)}, or * {@link org.fxmisc.wellbehaved.event.InputMap#process(org.fxmisc.wellbehaved.event.EventPattern, Function)} * ) are used and {@link org.fxmisc.wellbehaved.event.InputHandler.Result#PROCEED} is returned. * The area has a "catch all" Mouse Drag InputMap that will auto scroll towards the mouse drag event when it * occurs outside the bounds of the area and will stop auto scrolling when the mouse event occurs within the * area. However, this only works if the event is not consumed before the event reaches that InputMap. * To insure the auto scroll feature is enabled, set {@link #isAutoScrollOnDragDesired()} to true in your * process InputMap. If the feature is not desired for that specific drag event, set it to false in the * process InputMap. * <em>Note: Due to this "catch-all" nature, all Mouse Drag Events are consumed.</em> * </li> * <li> * <em>Primary-Button-only Mouse Released Events:</em> * (<code>EventPattern.mouseReleased().onlyIf(e -&gt; e.getButton() == MouseButton.PRIMARY &amp;&amp; !e.isMiddleButtonDown() &amp;&amp; !e.isSecondaryButtonDown())</code>). * Do not override. Instead, use {@link #onNewSelectionDragFinished}, {@link #onSelectionDropped}, or see next item. * </li> * <li> * <em>All other Mouse Released Events:</em> * You may override other Mouse Released Events using different * {@link org.fxmisc.wellbehaved.event.EventPattern}s without affecting default behavior only if * process InputMaps ( * {@link org.fxmisc.wellbehaved.event.template.InputMapTemplate#process(javafx.event.EventType, BiFunction)}, * {@link org.fxmisc.wellbehaved.event.template.InputMapTemplate#process(org.fxmisc.wellbehaved.event.EventPattern, BiFunction)}, * {@link org.fxmisc.wellbehaved.event.InputMap#process(javafx.event.EventType, Function)}, or * {@link org.fxmisc.wellbehaved.event.InputMap#process(org.fxmisc.wellbehaved.event.EventPattern, Function)} * ) are used and {@link org.fxmisc.wellbehaved.event.InputHandler.Result#PROCEED} is returned. * The area has a "catch-all" InputMap that will consume all mouse released events and stop auto scroll if it * was scrolling. However, this only works if the event is not consumed before the event reaches that InputMap. * <em>Note: Due to this "catch-all" nature, all Mouse Released Events are consumed.</em> * </li> * </ul> * * <h3>CSS, Style Classes, and Pseudo Classes</h3> * <p> * Refer to the <a href="https://github.com/FXMisc/RichTextFX/wiki/RichTextFX-CSS-Reference-Guide"> * RichTextFX CSS Reference Guide * </a>. * </p> * * <h3>Area Actions and Other Operations</h3> * <p> * To distinguish the actual operations one can do on this area from the boilerplate methods * within this area (e.g. properties and their getters/setters, etc.), look at the interfaces * this area implements. Each lists and documents methods that fall under that category. * </p> * <p> * To update multiple portions of the area's underlying document in one call, see {@link #createMultiChange()}. * </p> * * <h3>Calculating a Position Within the Area</h3> * <p> * To calculate a position or index within the area, read through the javadoc of * {@link org.fxmisc.richtext.model.TwoDimensional} and {@link org.fxmisc.richtext.model.TwoDimensional.Bias}. * Also, read the difference between "position" and "index" in * {@link org.fxmisc.richtext.model.StyledDocument#getAbsolutePosition(int, int)}. * </p> * * @see EditableStyledDocument * @see TwoDimensional * @see org.fxmisc.richtext.model.TwoDimensional.Bias * @see VirtualFlow * @see VirtualizedScrollPane * @see Caret * @see Selection * @see CaretSelectionBind * * @param <PS> type of style that can be applied to paragraphs (e.g. {@link TextFlow}. * @param <SEG> type of segment used in {@link Paragraph}. Can be only text (plain or styled) or * a type that combines text and other {@link Node}s. * @param <S> type of style that can be applied to a segment. */ public class GenericStyledArea<PS, SEG, S> extends Region implements TextEditingArea<PS, SEG, S>, EditActions<PS, SEG, S>, ClipboardActions<PS, SEG, S>, NavigationActions<PS, SEG, S>, StyleActions<PS, S>, UndoActions, ViewActions<PS, SEG, S>, TwoDimensional, Virtualized { /** * Index range [0, 0). */ public static final IndexRange EMPTY_RANGE = new IndexRange(0, 0); private static final PseudoClass READ_ONLY = PseudoClass.getPseudoClass("readonly"); private static final PseudoClass HAS_CARET = PseudoClass.getPseudoClass("has-caret"); private static final PseudoClass FIRST_PAR = PseudoClass.getPseudoClass("first-paragraph"); private static final PseudoClass LAST_PAR = PseudoClass.getPseudoClass("last-paragraph"); /* ********************************************************************** * * * * Properties * * * * Properties affect behavior and/or appearance of this control. * * * * They are readable and writable by the client code and never change by * * other means, i.e. they contain either the default value or the value * * set by the client code. * * * * ********************************************************************** */ /** * Text color for highlighted text. */ private final StyleableObjectProperty<Paint> highlightTextFill = new CustomStyleableProperty<>(Color.WHITE, "highlightTextFill", this, HIGHLIGHT_TEXT_FILL); // editable property private final BooleanProperty editable = new SimpleBooleanProperty(this, "editable", true) { @Override protected void invalidated() { ((Region) getBean()).pseudoClassStateChanged(READ_ONLY, !get()); } }; @Override public final BooleanProperty editableProperty() { return editable; } // Don't remove as FXMLLoader doesn't recognise default methods ! @Override public void setEditable(boolean value) { editable.set(value); } @Override public boolean isEditable() { return editable.get(); } // wrapText property private final BooleanProperty wrapText = new SimpleBooleanProperty(this, "wrapText"); @Override public final BooleanProperty wrapTextProperty() { return wrapText; } // Don't remove as FXMLLoader doesn't recognise default methods ! @Override public void setWrapText(boolean value) { wrapText.set(value); } @Override public boolean isWrapText() { return wrapText.get(); } // undo manager private UndoManager undoManager; @Override public UndoManager getUndoManager() { return undoManager; } /** * @param undoManager may be null in which case a no op undo manager will be set. */ @Override public void setUndoManager(UndoManager undoManager) { this.undoManager.close(); this.undoManager = undoManager != null ? undoManager : UndoUtils.noOpUndoManager(); } private Locale textLocale = Locale.getDefault(); /** * This is used to determine word and sentence breaks while navigating or selecting. * Override this method if your paragraph or text style accommodates Locales as well. * @return Locale.getDefault() by default */ @Override public Locale getLocale() { return textLocale; } public void setLocale( Locale editorLocale ) { textLocale = editorLocale; } private final ObjectProperty<Duration> mouseOverTextDelay = new SimpleObjectProperty<>(null); @Override public ObjectProperty<Duration> mouseOverTextDelayProperty() { return mouseOverTextDelay; } private final ObjectProperty<IntFunction<? extends Node>> paragraphGraphicFactory = new SimpleObjectProperty<>(null); @Override public ObjectProperty<IntFunction<? extends Node>> paragraphGraphicFactoryProperty() { return paragraphGraphicFactory; } public void recreateParagraphGraphic( int parNdx ) { ObjectProperty<IntFunction<? extends Node>> gProp; gProp = getCell(parNdx).graphicFactoryProperty(); gProp.unbind(); gProp.bind(paragraphGraphicFactoryProperty()); } public Node getParagraphGraphic( int parNdx ) { return getCell(parNdx).getGraphic(); } /** * This Node is shown to the user, centered over the area, when the area has no text content. */ private ObjectProperty<Node> placeHolderProp = new SimpleObjectProperty<>(this, "placeHolder", null); public final ObjectProperty<Node> placeholderProperty() { return placeHolderProp; } public final void setPlaceholder(Node value) { placeHolderProp.set(value); } public final Node getPlaceholder() { return placeHolderProp.get(); } private ObjectProperty<ContextMenu> contextMenu = new SimpleObjectProperty<>(null); @Override public final ObjectProperty<ContextMenu> contextMenuObjectProperty() { return contextMenu; } // Don't remove as FXMLLoader doesn't recognise default methods ! @Override public void setContextMenu(ContextMenu menu) { contextMenu.set(menu); } @Override public ContextMenu getContextMenu() { return contextMenu.get(); } protected final boolean isContextMenuPresent() { return contextMenu.get() != null; } private DoubleProperty contextMenuXOffset = new SimpleDoubleProperty(2); @Override public final DoubleProperty contextMenuXOffsetProperty() { return contextMenuXOffset; } // Don't remove as FXMLLoader doesn't recognise default methods ! @Override public void setContextMenuXOffset(double offset) { contextMenuXOffset.set(offset); } @Override public double getContextMenuXOffset() { return contextMenuXOffset.get(); } private DoubleProperty contextMenuYOffset = new SimpleDoubleProperty(2); @Override public final DoubleProperty contextMenuYOffsetProperty() { return contextMenuYOffset; } // Don't remove as FXMLLoader doesn't recognise default methods ! @Override public void setContextMenuYOffset(double offset) { contextMenuYOffset.set(offset); } @Override public double getContextMenuYOffset() { return contextMenuYOffset.get(); } private final BooleanProperty useInitialStyleForInsertion = new SimpleBooleanProperty(); @Override public BooleanProperty useInitialStyleForInsertionProperty() { return useInitialStyleForInsertion; } private Optional<Tuple2<Codec<PS>, Codec<StyledSegment<SEG, S>>>> styleCodecs = Optional.empty(); @Override public void setStyleCodecs(Codec<PS> paragraphStyleCodec, Codec<StyledSegment<SEG, S>> styledSegCodec) { styleCodecs = Optional.of(t(paragraphStyleCodec, styledSegCodec)); } @Override public Optional<Tuple2<Codec<PS>, Codec<StyledSegment<SEG, S>>>> getStyleCodecs() { return styleCodecs; } @Override public Var<Double> estimatedScrollXProperty() { return virtualFlow.estimatedScrollXProperty(); } @Override public Var<Double> estimatedScrollYProperty() { return virtualFlow.estimatedScrollYProperty(); } private final SubscribeableContentsObsSet<CaretNode> caretSet; private final SubscribeableContentsObsSet<Selection<PS, SEG, S>> selectionSet; public final boolean addCaret(CaretNode caret) { if (caret.getArea() != this) { throw new IllegalArgumentException(String.format( "The caret (%s) is associated with a different area (%s), " + "not this area (%s)", caret, caret.getArea(), this)); } return caretSet.add(caret); } public final boolean removeCaret(CaretNode caret) { if (caret != caretSelectionBind.getUnderlyingCaret()) { return caretSet.remove(caret); } else { return false; } } public final boolean addSelection(Selection<PS, SEG, S> selection) { if (selection.getArea() != this) { throw new IllegalArgumentException(String.format( "The selection (%s) is associated with a different area (%s), " + "not this area (%s)", selection, selection.getArea(), this)); } return selectionSet.add(selection); } public final boolean removeSelection(Selection<PS, SEG, S> selection) { if (selection != caretSelectionBind.getUnderlyingSelection()) { return selectionSet.remove(selection); } else { return false; } } /* ********************************************************************** * * * * Mouse Behavior Hooks * * * * Hooks for overriding some of the default mouse behavior * * * * ********************************************************************** */ @Override public final EventHandler<MouseEvent> getOnOutsideSelectionMousePressed() { return onOutsideSelectionMousePressed.get(); } @Override public final void setOnOutsideSelectionMousePressed(EventHandler<MouseEvent> handler) { onOutsideSelectionMousePressed.set( handler ); } @Override public final ObjectProperty<EventHandler<MouseEvent>> onOutsideSelectionMousePressedProperty() { return onOutsideSelectionMousePressed; } private final ObjectProperty<EventHandler<MouseEvent>> onOutsideSelectionMousePressed = new SimpleObjectProperty<>( e -> { moveTo( hit( e.getX(), e.getY() ).getInsertionIndex(), SelectionPolicy.CLEAR ); }); @Override public final EventHandler<MouseEvent> getOnInsideSelectionMousePressReleased() { return onInsideSelectionMousePressReleased.get(); } @Override public final void setOnInsideSelectionMousePressReleased(EventHandler<MouseEvent> handler) { onInsideSelectionMousePressReleased.set( handler ); } @Override public final ObjectProperty<EventHandler<MouseEvent>> onInsideSelectionMousePressReleasedProperty() { return onInsideSelectionMousePressReleased; } private final ObjectProperty<EventHandler<MouseEvent>> onInsideSelectionMousePressReleased = new SimpleObjectProperty<>( e -> { moveTo( hit( e.getX(), e.getY() ).getInsertionIndex(), SelectionPolicy.CLEAR ); }); private final ObjectProperty<Consumer<Point2D>> onNewSelectionDrag = new SimpleObjectProperty<>(p -> { CharacterHit hit = hit(p.getX(), p.getY()); moveTo(hit.getInsertionIndex(), SelectionPolicy.ADJUST); }); @Override public final ObjectProperty<Consumer<Point2D>> onNewSelectionDragProperty() { return onNewSelectionDrag; } @Override public final EventHandler<MouseEvent> getOnNewSelectionDragFinished() { return onNewSelectionDragFinished.get(); } @Override public final void setOnNewSelectionDragFinished(EventHandler<MouseEvent> handler) { onNewSelectionDragFinished.set( handler ); } @Override public final ObjectProperty<EventHandler<MouseEvent>> onNewSelectionDragFinishedProperty() { return onNewSelectionDragFinished; } private final ObjectProperty<EventHandler<MouseEvent>> onNewSelectionDragFinished = new SimpleObjectProperty<>( e -> { CharacterHit hit = hit(e.getX(), e.getY()); moveTo(hit.getInsertionIndex(), SelectionPolicy.ADJUST); }); private final ObjectProperty<Consumer<Point2D>> onSelectionDrag = new SimpleObjectProperty<>(p -> { CharacterHit hit = hit(p.getX(), p.getY()); displaceCaret(hit.getInsertionIndex()); }); @Override public final ObjectProperty<Consumer<Point2D>> onSelectionDragProperty() { return onSelectionDrag; } @Override public final EventHandler<MouseEvent> getOnSelectionDropped() { return onSelectionDropped.get(); } @Override public final void setOnSelectionDropped(EventHandler<MouseEvent> handler) { onSelectionDropped.set( handler ); } @Override public final ObjectProperty<EventHandler<MouseEvent>> onSelectionDroppedProperty() { return onSelectionDropped; } private final ObjectProperty<EventHandler<MouseEvent>> onSelectionDropped = new SimpleObjectProperty<>( e -> { moveSelectedText( hit( e.getX(), e.getY() ).getInsertionIndex() ); }); // not a hook, but still plays a part in the default mouse behavior private final BooleanProperty autoScrollOnDragDesired = new SimpleBooleanProperty(true); @Override public final BooleanProperty autoScrollOnDragDesiredProperty() { return autoScrollOnDragDesired; } // Don't remove as FXMLLoader doesn't recognise default methods ! @Override public void setAutoScrollOnDragDesired(boolean val) { autoScrollOnDragDesired.set(val); } @Override public boolean isAutoScrollOnDragDesired() { return autoScrollOnDragDesired.get(); } /* ********************************************************************** * * * * Observables * * * * Observables are "dynamic" (i.e. changing) characteristics of this * * control. They are not directly settable by the client code, but change * * in response to user input and/or API actions. * * * * ********************************************************************** */ // text @Override public final ObservableValue<String> textProperty() { return content.textProperty(); } // rich text @Override public final StyledDocument<PS, SEG, S> getDocument() { return content; } private CaretSelectionBind<PS, SEG, S> caretSelectionBind; @Override public final CaretSelectionBind<PS, SEG, S> getCaretSelectionBind() { return caretSelectionBind; } // length @Override public final ObservableValue<Integer> lengthProperty() { return content.lengthProperty(); } // paragraphs @Override public LiveList<Paragraph<PS, SEG, S>> getParagraphs() { return content.getParagraphs(); } private final SuspendableList<Paragraph<PS, SEG, S>> visibleParagraphs; @Override public final LiveList<Paragraph<PS, SEG, S>> getVisibleParagraphs() { return visibleParagraphs; } // beingUpdated private final SuspendableNo beingUpdated = new SuspendableNo(); @Override public final SuspendableNo beingUpdatedProperty() { return beingUpdated; } // total width estimate @Override public Val<Double> totalWidthEstimateProperty() { return virtualFlow.totalWidthEstimateProperty(); } // total height estimate @Override public Val<Double> totalHeightEstimateProperty() { return virtualFlow.totalHeightEstimateProperty(); } /* ********************************************************************** * * * * Event streams * * * * ********************************************************************** */ @Override public EventStream<List<RichTextChange<PS, SEG, S>>> multiRichChanges() { return content.multiRichChanges(); } @Override public EventStream<List<PlainTextChange>> multiPlainChanges() { return content.multiPlainChanges(); } // text changes @Override public final EventStream<PlainTextChange> plainTextChanges() { return content.plainChanges(); } // rich text changes @Override public final EventStream<RichTextChange<PS, SEG, S>> richChanges() { return content.richChanges(); } private final SuspendableEventStream<?> viewportDirty; @Override public final EventStream<?> viewportDirtyEvents() { return viewportDirty; } /* ********************************************************************** * * * * Private fields * * * * ********************************************************************** */ private Subscription subscriptions = () -> {}; private final VirtualFlow<Paragraph<PS, SEG, S>, Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>> virtualFlow; // used for two-level navigation, where on the higher level are // paragraphs and on the lower level are lines within a paragraph private final TwoLevelNavigator paragraphLineNavigator; private boolean paging, followCaretRequested = false; /* ********************************************************************** * * * * Fields necessary for Cloning * * * * ********************************************************************** */ private final EditableStyledDocument<PS, SEG, S> content; @Override public final EditableStyledDocument<PS, SEG, S> getContent() { return content; } private final S initialTextStyle; @Override public final S getInitialTextStyle() { return initialTextStyle; } private final PS initialParagraphStyle; @Override public final PS getInitialParagraphStyle() { return initialParagraphStyle; } private final BiConsumer<TextFlow, PS> applyParagraphStyle; @Override public final BiConsumer<TextFlow, PS> getApplyParagraphStyle() { return applyParagraphStyle; } // TODO: Currently, only undo/redo respect this flag. private final boolean preserveStyle; @Override public final boolean isPreserveStyle() { return preserveStyle; } /* ********************************************************************** * * * * Miscellaneous * * * * ********************************************************************** */ private final TextOps<SEG, S> segmentOps; @Override public final TextOps<SEG, S> getSegOps() { return segmentOps; } private final EventStream<Boolean> autoCaretBlinksSteam; final EventStream<Boolean> autoCaretBlink() { return autoCaretBlinksSteam; } /* ********************************************************************** * * * * Constructors * * * * ********************************************************************** */ /** * Creates a text area with empty text content. * * @param initialParagraphStyle style to use in places where no other style is * specified (yet). * @param applyParagraphStyle function that, given a {@link TextFlow} node and * a style, applies the style to the paragraph node. This function is * used by the default skin to apply style to paragraph nodes. * @param initialTextStyle style to use in places where no other style is * specified (yet). * @param segmentOps The operations which are defined on the text segment objects. * @param nodeFactory A function which is used to create the JavaFX scene nodes for a * particular segment. */ public GenericStyledArea(@NamedArg("initialParagraphStyle") PS initialParagraphStyle, @NamedArg("applyParagraphStyle") BiConsumer<TextFlow, PS> applyParagraphStyle, @NamedArg("initialTextStyle") S initialTextStyle, @NamedArg("segmentOps") TextOps<SEG, S> segmentOps, @NamedArg("nodeFactory") Function<StyledSegment<SEG, S>, Node> nodeFactory) { this(initialParagraphStyle, applyParagraphStyle, initialTextStyle, segmentOps, true, nodeFactory); } /** * Same as {@link #GenericStyledArea(Object, BiConsumer, Object, TextOps, Function)} but also allows one * to specify whether the undo manager should be a plain or rich undo manager via {@code preserveStyle}. * * @param initialParagraphStyle style to use in places where no other style is specified (yet). * @param applyParagraphStyle function that, given a {@link TextFlow} node and * a style, applies the style to the paragraph node. This function is * used by the default skin to apply style to paragraph nodes. * @param initialTextStyle style to use in places where no other style is specified (yet). * @param segmentOps The operations which are defined on the text segment objects. * @param preserveStyle whether to use an undo manager that can undo/redo {@link RichTextChange}s or * {@link PlainTextChange}s * @param nodeFactory A function which is used to create the JavaFX scene node for a particular segment. */ public GenericStyledArea(@NamedArg("initialParagraphStyle") PS initialParagraphStyle, @NamedArg("applyParagraphStyle") BiConsumer<TextFlow, PS> applyParagraphStyle, @NamedArg("initialTextStyle") S initialTextStyle, @NamedArg("segmentOps") TextOps<SEG, S> segmentOps, @NamedArg("preserveStyle") boolean preserveStyle, @NamedArg("nodeFactory") Function<StyledSegment<SEG, S>, Node> nodeFactory) { this(initialParagraphStyle, applyParagraphStyle, initialTextStyle, new GenericEditableStyledDocument<>(initialParagraphStyle, initialTextStyle, segmentOps), segmentOps, preserveStyle, nodeFactory); } /** * The same as {@link #GenericStyledArea(Object, BiConsumer, Object, TextOps, Function)} except that * this constructor can be used to create another {@code GenericStyledArea} that renders and edits the same * {@link EditableStyledDocument} or when one wants to use a custom {@link EditableStyledDocument} implementation. */ public GenericStyledArea( @NamedArg("initialParagraphStyle") PS initialParagraphStyle, @NamedArg("applyParagraphStyle") BiConsumer<TextFlow, PS> applyParagraphStyle, @NamedArg("initialTextStyle") S initialTextStyle, @NamedArg("document") EditableStyledDocument<PS, SEG, S> document, @NamedArg("segmentOps") TextOps<SEG, S> segmentOps, @NamedArg("nodeFactory") Function<StyledSegment<SEG, S>, Node> nodeFactory) { this(initialParagraphStyle, applyParagraphStyle, initialTextStyle, document, segmentOps, true, nodeFactory); } /** * Creates an area with flexibility in all of its options. * * @param initialParagraphStyle style to use in places where no other style is specified (yet). * @param applyParagraphStyle function that, given a {@link TextFlow} node and * a style, applies the style to the paragraph node. This function is * used by the default skin to apply style to paragraph nodes. * @param initialTextStyle style to use in places where no other style is specified (yet). * @param document the document to render and edit * @param segmentOps The operations which are defined on the text segment objects. * @param preserveStyle whether to use an undo manager that can undo/redo {@link RichTextChange}s or * {@link PlainTextChange}s * @param nodeFactory A function which is used to create the JavaFX scene node for a particular segment. */ public GenericStyledArea( @NamedArg("initialParagraphStyle") PS initialParagraphStyle, @NamedArg("applyParagraphStyle") BiConsumer<TextFlow, PS> applyParagraphStyle, @NamedArg("initialTextStyle") S initialTextStyle, @NamedArg("document") EditableStyledDocument<PS, SEG, S> document, @NamedArg("segmentOps") TextOps<SEG, S> segmentOps, @NamedArg("preserveStyle") boolean preserveStyle, @NamedArg("nodeFactory") Function<StyledSegment<SEG, S>, Node> nodeFactory) { this.initialTextStyle = initialTextStyle; this.initialParagraphStyle = initialParagraphStyle; this.preserveStyle = preserveStyle; this.content = document; this.applyParagraphStyle = applyParagraphStyle; this.segmentOps = segmentOps; undoManager = UndoUtils.defaultUndoManager(this); // allow tab traversal into area setFocusTraversable(true); this.setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY))); getStyleClass().add("styled-text-area"); getStylesheets().add(StyledTextArea.class.getResource("styled-text-area.css").toExternalForm()); // keeps track of currently used non-empty cells @SuppressWarnings("unchecked") ObservableSet<ParagraphBox<PS, SEG, S>> nonEmptyCells = FXCollections.observableSet(); caretSet = new SubscribeableContentsObsSet<>(); manageSubscription(() -> { List<CaretNode> l = new ArrayList<>(caretSet); caretSet.clear(); l.forEach(CaretNode::dispose); }); selectionSet = new SubscribeableContentsObsSet<>(); manageSubscription(() -> { List<Selection<PS, SEG, S>> l = new ArrayList<>(selectionSet); selectionSet.clear(); l.forEach(Selection::dispose); }); // Initialize content virtualFlow = VirtualFlow.createVertical( getParagraphs(), par -> { Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = createCell( par, applyParagraphStyle, nodeFactory); nonEmptyCells.add(cell.getNode()); return cell.beforeReset(() -> nonEmptyCells.remove(cell.getNode())) .afterUpdateItem(p -> nonEmptyCells.add(cell.getNode())); }); getChildren().add(virtualFlow); // initialize navigator IntSupplier cellCount = () -> getParagraphs().size(); IntUnaryOperator cellLength = i -> virtualFlow.getCell(i).getNode().getLineCount(); paragraphLineNavigator = new TwoLevelNavigator(cellCount, cellLength); viewportDirty = merge( // no need to check for width & height invalidations as scroll values update when these do // scale invalidationsOf(scaleXProperty()), invalidationsOf(scaleYProperty()), // scroll invalidationsOf(estimatedScrollXProperty()), invalidationsOf(estimatedScrollYProperty()) ).suppressible(); autoCaretBlinksSteam = EventStreams.valuesOf(focusedProperty() .and(editableProperty()) .and(disabledProperty().not()) ); caretSelectionBind = new CaretSelectionBindImpl<>("main-caret", "main-selection",this); caretSelectionBind.paragraphIndexProperty().addListener( this::skipOverFoldedParagraphs ); caretSet.add(caretSelectionBind.getUnderlyingCaret()); selectionSet.add(caretSelectionBind.getUnderlyingSelection()); visibleParagraphs = LiveList.map(virtualFlow.visibleCells(), c -> c.getNode().getParagraph()).suspendable(); final Suspendable omniSuspendable = Suspendable.combine( beingUpdated, // must be first, to be the last one to release visibleParagraphs ); manageSubscription(omniSuspendable.suspendWhen(content.beingUpdatedProperty())); // dispatch MouseOverTextEvents when mouseOverTextDelay is not null EventStreams.valuesOf(mouseOverTextDelayProperty()) .flatMap(delay -> delay != null ? mouseOverTextEvents(nonEmptyCells, delay) : EventStreams.never()) .subscribe(evt -> Event.fireEvent(this, evt)); new GenericStyledAreaBehavior(this); // Setup place holder visibility & placement final Val<Boolean> showPlaceholder = Val.create ( () -> getLength() == 0 && ! isFocused(), lengthProperty(), focusedProperty() ); placeHolderProp.addListener( (ob,ov,newNode) -> displayPlaceHolder( showPlaceholder.getValue(), newNode ) ); showPlaceholder.addListener( (ob,ov,show) -> displayPlaceHolder( show, getPlaceholder() ) ); if ( Platform.isFxApplicationThread() ) initInputMethodHandling(); else Platform.runLater( () -> initInputMethodHandling() ); } private void initInputMethodHandling() { if( Platform.isSupported( ConditionalFeature.INPUT_METHOD ) ) { setOnInputMethodTextChanged( event -> handleInputMethodEvent(event) ); // Both of these have to be set for input composition to work ! setInputMethodRequests( new InputMethodRequests() { @Override public Point2D getTextLocation( int offset ) { Bounds charBounds = getCaretBounds().get(); return new Point2D( charBounds.getMaxX() - 5, charBounds.getMaxY() ); } @Override public int getLocationOffset( int x, int y ) { return 0; } @Override public void cancelLatestCommittedText() {} @Override public String getSelectedText() { return getSelectedText(); } }); } } // Start/Length of the text under input method composition private int imstart; private int imlength; protected void handleInputMethodEvent( InputMethodEvent event ) { if ( isEditable() && !isDisabled() ) { // remove previous input method text (if any) or selected text if ( imlength != 0 ) { selectRange( imstart, imstart + imlength ); } // Insert committed text if ( event.getCommitted().length() != 0 ) { replaceText( getSelection(), event.getCommitted() ); } // Replace composed text imstart = getSelection().getStart(); StringBuilder composed = new StringBuilder(); for ( InputMethodTextRun run : event.getComposed() ) { composed.append( run.getText() ); } replaceText( getSelection(), composed.toString() ); imlength = composed.length(); if ( imlength != 0 ) { int pos = imstart; for ( InputMethodTextRun run : event.getComposed() ) { int endPos = pos + run.getText().length(); pos = endPos; } // Set caret position in composed text int caretPos = event.getCaretPosition(); if ( caretPos >= 0 && caretPos < imlength ) { selectRange( imstart + caretPos, imstart + caretPos ); } } } } private Node placeholder; private void displayPlaceHolder( boolean show, Node newNode ) { if ( placeholder != null && (! show || newNode != placeholder) ) { placeholder.layoutXProperty().unbind(); placeholder.layoutYProperty().unbind(); getChildren().remove( placeholder ); placeholder = null; setClip( null ); } if ( newNode != null && show && newNode != placeholder ) { configurePlaceholder( newNode ); getChildren().add( newNode ); placeholder = newNode; } } protected void configurePlaceholder( Node placeholder ) { placeholder.layoutYProperty().bind( Bindings.createDoubleBinding( () -> (getHeight() - placeholder.getLayoutBounds().getHeight()) / 2, heightProperty(), placeholder.layoutBoundsProperty() ) ); placeholder.layoutXProperty().bind( Bindings.createDoubleBinding( () -> (getWidth() - placeholder.getLayoutBounds().getWidth()) / 2, widthProperty(), placeholder.layoutBoundsProperty() ) ); } /* ********************************************************************** * * * * Queries * * * * Queries are parameterized observables. * * * * ********************************************************************** */ @Override public final double getViewportHeight() { return virtualFlow.getHeight(); } @Override public final Optional<Integer> allParToVisibleParIndex(int allParIndex) { if (allParIndex < 0) { throw new IllegalArgumentException("The given paragraph index (allParIndex) cannot be negative but was " + allParIndex); } if (allParIndex >= getParagraphs().size()) { throw new IllegalArgumentException(String.format( "Paragraphs' last index is [%s] but allParIndex was [%s]", getParagraphs().size() - 1, allParIndex) ); } List<Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>> visibleList = virtualFlow.visibleCells(); int firstVisibleParIndex = visibleList.get( 0 ).getNode().getIndex(); int targetIndex = allParIndex - firstVisibleParIndex; if ( allParIndex >= firstVisibleParIndex && targetIndex < visibleList.size() ) { if ( visibleList.get( targetIndex ).getNode().getIndex() == allParIndex ) { return Optional.of( targetIndex ); } } return Optional.empty(); } @Override public final int visibleParToAllParIndex(int visibleParIndex) { if (visibleParIndex < 0) { throw new IllegalArgumentException("Visible paragraph index cannot be negative but was " + visibleParIndex); } if (visibleParIndex >= getVisibleParagraphs().size()) { throw new IllegalArgumentException(String.format( "Visible paragraphs' last index is [%s] but visibleParIndex was [%s]", getVisibleParagraphs().size() - 1, visibleParIndex) ); } Cell<Paragraph<PS,SEG,S>, ParagraphBox<PS,SEG,S>> visibleCell = null; if ( visibleParIndex > 0 ) visibleCell = virtualFlow.visibleCells().get( visibleParIndex ); else visibleCell = virtualFlow.getCellIfVisible( virtualFlow.getFirstVisibleIndex() ) .orElseGet( () -> virtualFlow.visibleCells().get( visibleParIndex ) ); return visibleCell.getNode().getIndex(); } @Override public CharacterHit hit(double x, double y) { // mouse position used, so account for padding double adjustedX = x - getInsets().getLeft(); double adjustedY = y - getInsets().getTop(); VirtualFlowHit<Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>> hit = virtualFlow.hit(adjustedX, adjustedY); if(hit.isBeforeCells()) { return CharacterHit.insertionAt(0); } else if(hit.isAfterCells()) { return CharacterHit.insertionAt(getLength()); } else { int parIdx = hit.getCellIndex(); int parOffset = getParagraphOffset(parIdx); ParagraphBox<PS, SEG, S> cell = hit.getCell().getNode(); Point2D cellOffset = hit.getCellOffset(); CharacterHit parHit = cell.hit(cellOffset); return parHit.offset(parOffset); } } @Override public final int lineIndex(int paragraphIndex, int columnPosition) { Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = virtualFlow.getCell(paragraphIndex); return cell.getNode().getCurrentLineIndex(columnPosition); } @Override public int getParagraphLinesCount(int paragraphIndex) { return virtualFlow.getCell(paragraphIndex).getNode().getLineCount(); } @Override public Optional<Bounds> getCharacterBoundsOnScreen(int from, int to) { if (from < 0) { throw new IllegalArgumentException("From is negative: " + from); } if (from > to) { throw new IllegalArgumentException(String.format("From is greater than to. from=%s to=%s", from, to)); } if (to > getLength()) { throw new IllegalArgumentException(String.format("To is greater than area's length. length=%s, to=%s", getLength(), to)); } // no bounds exist if range is just a newline character if (getText(from, to).equals("\n")) { return Optional.empty(); } // if 'from' is the newline character at the end of a multi-line paragraph, it returns a Bounds that whose // minX & minY are the minX and minY of the paragraph itself, not the newline character. So, ignore it. int realFrom = getText(from, from + 1).equals("\n") ? from + 1 : from; Position startPosition = offsetToPosition(realFrom, Bias.Forward); int startRow = startPosition.getMajor(); Position endPosition = startPosition.offsetBy(to - realFrom, Bias.Forward); int endRow = endPosition.getMajor(); if (startRow == endRow) { return getRangeBoundsOnScreen(startRow, startPosition.getMinor(), endPosition.getMinor()); } else { Optional<Bounds> rangeBounds = getRangeBoundsOnScreen(startRow, startPosition.getMinor(), getParagraph(startRow).length()); for (int i = startRow + 1; i <= endRow; i++) { Optional<Bounds> nextLineBounds = getRangeBoundsOnScreen(i, 0, i == endRow ? endPosition.getMinor() : getParagraph(i).length() ); if (nextLineBounds.isPresent()) { if (rangeBounds.isPresent()) { Bounds lineBounds = nextLineBounds.get(); rangeBounds = rangeBounds.map(b -> { double minX = Math.min(b.getMinX(), lineBounds.getMinX()); double minY = Math.min(b.getMinY(), lineBounds.getMinY()); double maxX = Math.max(b.getMaxX(), lineBounds.getMaxX()); double maxY = Math.max(b.getMaxY(), lineBounds.getMaxY()); return new BoundingBox(minX, minY, maxX - minX, maxY - minY); }); } else { rangeBounds = nextLineBounds; } } } return rangeBounds; } } @Override public final String getText(int start, int end) { return content.getText(start, end); } @Override public String getText(int paragraph) { return content.getText(paragraph); } @Override public String getText(IndexRange range) { return content.getText(range); } @Override public StyledDocument<PS, SEG, S> subDocument(int start, int end) { return content.subSequence(start, end); } @Override public StyledDocument<PS, SEG, S> subDocument(int paragraphIndex) { return content.subDocument(paragraphIndex); } @Override public IndexRange getParagraphSelection(Selection selection, int paragraph) { int startPar = selection.getStartParagraphIndex(); int endPar = selection.getEndParagraphIndex(); if(selection.getLength() == 0 || paragraph < startPar || paragraph > endPar) { return EMPTY_RANGE; } int start = paragraph == startPar ? selection.getStartColumnPosition() : 0; int end = paragraph == endPar ? selection.getEndColumnPosition() : getParagraphLength(paragraph) + 1; // force rangeProperty() to be valid selection.getRange(); return new IndexRange(start, end); } @Override public S getStyleOfChar(int index) { return content.getStyleOfChar(index); } @Override public S getStyleAtPosition(int position) { return content.getStyleAtPosition(position); } @Override public IndexRange getStyleRangeAtPosition(int position) { return content.getStyleRangeAtPosition(position); } @Override public StyleSpans<S> getStyleSpans(int from, int to) { return content.getStyleSpans(from, to); } @Override public S getStyleOfChar(int paragraph, int index) { return content.getStyleOfChar(paragraph, index); } @Override public S getStyleAtPosition(int paragraph, int position) { return content.getStyleAtPosition(paragraph, position); } @Override public IndexRange getStyleRangeAtPosition(int paragraph, int position) { return content.getStyleRangeAtPosition(paragraph, position); } @Override public StyleSpans<S> getStyleSpans(int paragraph) { return content.getStyleSpans(paragraph); } @Override public StyleSpans<S> getStyleSpans(int paragraph, int from, int to) { return content.getStyleSpans(paragraph, from, to); } @Override public int getAbsolutePosition(int paragraphIndex, int columnIndex) { return content.getAbsolutePosition(paragraphIndex, columnIndex); } @Override public Position position(int row, int col) { return content.position(row, col); } @Override public Position offsetToPosition(int charOffset, Bias bias) { return content.offsetToPosition(charOffset, bias); } @Override public Bounds getVisibleParagraphBoundsOnScreen(int visibleParagraphIndex) { return getParagraphBoundsOnScreen(virtualFlow.visibleCells().get(visibleParagraphIndex)); } @Override public Optional<Bounds> getParagraphBoundsOnScreen(int paragraphIndex) { return virtualFlow.getCellIfVisible(paragraphIndex).map(this::getParagraphBoundsOnScreen); } @Override public final <T extends Node & Caret> Optional<Bounds> getCaretBoundsOnScreen(T caret) { return virtualFlow.getCellIfVisible(caret.getParagraphIndex()) .map(c -> c.getNode().getCaretBoundsOnScreen(caret)); } /* ********************************************************************** * * * * Actions * * * * Actions change the state of this control. They typically cause a * * change of one or more observables and/or produce an event. * * * * ********************************************************************** */ @Override public void scrollXToPixel(double pixel) { suspendVisibleParsWhile(() -> virtualFlow.scrollXToPixel(pixel)); } @Override public void scrollYToPixel(double pixel) { suspendVisibleParsWhile(() -> virtualFlow.scrollYToPixel(pixel)); } @Override public void scrollXBy(double deltaX) { suspendVisibleParsWhile(() -> virtualFlow.scrollXBy(deltaX)); } @Override public void scrollYBy(double deltaY) { suspendVisibleParsWhile(() -> virtualFlow.scrollYBy(deltaY)); } @Override public void scrollBy(Point2D deltas) { suspendVisibleParsWhile(() -> virtualFlow.scrollBy(deltas)); } @Override public void showParagraphInViewport(int paragraphIndex) { suspendVisibleParsWhile(() -> virtualFlow.show(paragraphIndex)); } @Override public void showParagraphAtTop(int paragraphIndex) { suspendVisibleParsWhile(() -> virtualFlow.showAsFirst(paragraphIndex)); } @Override public void showParagraphAtBottom(int paragraphIndex) { suspendVisibleParsWhile(() -> virtualFlow.showAsLast(paragraphIndex)); } @Override public void showParagraphRegion(int paragraphIndex, Bounds region) { suspendVisibleParsWhile(() -> virtualFlow.show(paragraphIndex, region)); } @Override public void requestFollowCaret() { followCaretRequested = true; requestLayout(); } @Override public void lineStart(SelectionPolicy policy) { moveTo(getCurrentParagraph(), getCurrentLineStartInParargraph(), policy); } @Override public void lineEnd(SelectionPolicy policy) { moveTo(getCurrentParagraph(), getCurrentLineEndInParargraph(), policy); } public int getCurrentLineStartInParargraph() { return virtualFlow.getCell(getCurrentParagraph()).getNode().getCurrentLineStartPosition(caretSelectionBind.getUnderlyingCaret()); } public int getCurrentLineEndInParargraph() { return virtualFlow.getCell(getCurrentParagraph()).getNode().getCurrentLineEndPosition(caretSelectionBind.getUnderlyingCaret()); } private double caretPrevY = -1; private LineSelection<PS, SEG, S> lineHighlighter; private ObjectProperty<Paint> lineHighlighterFill; /** * The default fill is "highlighter" yellow. It can also be styled using CSS with:<br> * <code>.styled-text-area .line-highlighter { -fx-fill: lime; }</code><br> * CSS selectors from Path, Shape, and Node can also be used. */ public void setLineHighlighterFill( Paint highlight ) { if ( lineHighlighterFill != null && highlight != null ) { lineHighlighterFill.set( highlight ); } else { boolean lineHighlightOn = isLineHighlighterOn(); if ( lineHighlightOn ) setLineHighlighterOn( false ); if ( highlight == null ) lineHighlighterFill = null; else lineHighlighterFill = new SimpleObjectProperty( highlight ); if ( lineHighlightOn ) setLineHighlighterOn( true ); } } public boolean isLineHighlighterOn() { return lineHighlighter != null && selectionSet.contains( lineHighlighter ) ; } /** * Highlights the line that the main caret is on.<br> * Line highlighting automatically follows the caret. */ public void setLineHighlighterOn( boolean show ) { if ( show ) { if ( lineHighlighter != null ) return; lineHighlighter = new LineSelection<>( this, lineHighlighterFill ); Consumer<Bounds> caretListener = b -> { if ( lineHighlighter != null && (b.getMinY() != caretPrevY || getCaretColumn() == 1) ) { lineHighlighter.selectCurrentLine(); caretPrevY = b.getMinY(); } }; caretBoundsProperty().addListener( (ob,ov,nv) -> nv.ifPresent( caretListener ) ); getCaretBounds().ifPresent( caretListener ); selectionSet.add( lineHighlighter ); } else if ( lineHighlighter != null ) { selectionSet.remove( lineHighlighter ); lineHighlighter.deselect(); lineHighlighter = null; caretPrevY = -1; } } @Override public void prevPage(SelectionPolicy selectionPolicy) { // Paging up and we're in the first frame then move/select to start. if ( firstVisibleParToAllParIndex() == 0 ) { caretSelectionBind.moveTo( 0, selectionPolicy ); } else page( -1, selectionPolicy ); } @Override public void nextPage(SelectionPolicy selectionPolicy) { // Paging down and we're in the last frame then move/select to end. if ( lastVisibleParToAllParIndex() == getParagraphs().size()-1 ) { caretSelectionBind.moveTo( getLength(), selectionPolicy ); } else page( +1, selectionPolicy ); } /** * @param pgCount the number of pages to page up/down. * <br>Negative numbers for paging up and positive for down. */ private void page(int pgCount, SelectionPolicy selectionPolicy) { // Use underlying caret to get the same behaviour as navigating up/down a line where the x position is sticky Optional<Bounds> cb = caretSelectionBind.getUnderlyingCaret().getCaretBounds(); paging = true; // Prevent scroll from reverting back to the current caret position scrollYBy( pgCount * getViewportHeight() ); cb.map( this::screenToLocal ) // Place caret near the same on screen position as before .map( b -> hit( b.getMinX(), b.getMinY()+b.getHeight()/2.0 ).getInsertionIndex() ) .ifPresent( i -> caretSelectionBind.moveTo( i, selectionPolicy ) ); // Adjust scroll by a few pixels to get the caret at the exact on screen location as before cb.ifPresent( prev -> getCaretBounds().map( newB -> newB.getMinY() - prev.getMinY() ) .filter( delta -> delta != 0.0 ).ifPresent( delta -> scrollYBy( delta ) ) ); } @Override public void displaceCaret(int pos) { caretSelectionBind.displaceCaret(pos); } @Override public void setStyle(int from, int to, S style) { content.setStyle(from, to, style); } @Override public void setStyle(int paragraph, S style) { content.setStyle(paragraph, style); } @Override public void setStyle(int paragraph, int from, int to, S style) { content.setStyle(paragraph, from, to, style); } @Override public void setStyleSpans(int from, StyleSpans<? extends S> styleSpans) { content.setStyleSpans(from, styleSpans); } @Override public void setStyleSpans(int paragraph, int from, StyleSpans<? extends S> styleSpans) { content.setStyleSpans(paragraph, from, styleSpans); } @Override public void setParagraphStyle(int paragraph, PS paragraphStyle) { content.setParagraphStyle(paragraph, paragraphStyle); } /** * If you want to preset the style to be used for inserted text. Note that useInitialStyleForInsertion overrides this if true. */ public final void setTextInsertionStyle( S txtStyle ) { insertionTextStyle = txtStyle; } public final S getTextInsertionStyle() { return insertionTextStyle; } private S insertionTextStyle; @Override public final S getTextStyleForInsertionAt(int pos) { if ( insertionTextStyle != null ) { return insertionTextStyle; } else if ( useInitialStyleForInsertion.get() ) { return initialTextStyle; } else { return content.getStyleAtPosition(pos); } } private PS insertionParagraphStyle; /** * If you want to preset the style to be used. Note that useInitialStyleForInsertion overrides this if true. */ public final void setParagraphInsertionStyle( PS paraStyle ) { insertionParagraphStyle = paraStyle; } public final PS getParagraphInsertionStyle() { return insertionParagraphStyle; } @Override public final PS getParagraphStyleForInsertionAt(int pos) { if ( insertionParagraphStyle != null ) { return insertionParagraphStyle; } else if ( useInitialStyleForInsertion.get() ) { return initialParagraphStyle; } else { return content.getParagraphStyleAtPosition(pos); } } @Override public void replaceText(int start, int end, String text) { StyledDocument<PS, SEG, S> doc = ReadOnlyStyledDocument.fromString( text, getParagraphStyleForInsertionAt(start), getTextStyleForInsertionAt(start), segmentOps ); replace(start, end, doc); } @Override public void replace(int start, int end, SEG seg, S style) { StyledDocument<PS, SEG, S> doc = ReadOnlyStyledDocument.fromSegment( seg, getParagraphStyleForInsertionAt(start), style, segmentOps ); replace(start, end, doc); } @Override public void replace(int start, int end, StyledDocument<PS, SEG, S> replacement) { content.replace(start, end, replacement); int newCaretPos = start + replacement.length(); selectRange(newCaretPos, newCaretPos); } void replaceMulti(List<Replacement<PS, SEG, S>> replacements) { content.replaceMulti(replacements); // don't update selection as this is not the main method through which the area is updated // leave that up to the developer using it to determine what to do } @Override public MultiChangeBuilder<PS, SEG, S> createMultiChange() { return new MultiChangeBuilder<>(this); } @Override public MultiChangeBuilder<PS, SEG, S> createMultiChange(int initialNumOfChanges) { return new MultiChangeBuilder<>(this, initialNumOfChanges); } /** * Convenience method to fold (hide/collapse) the currently selected paragraphs, * into (i.e. excluding) the first paragraph of the range. * * @param styleMixin Given a paragraph style PS, return a <b>new</b> PS that will activate folding. * * <p>See {@link #fold(int, int, UnaryOperator)} for more info.</p> */ protected void foldSelectedParagraphs( UnaryOperator<PS> styleMixin ) { IndexRange range = getSelection(); fold( range.getStart(), range.getEnd(), styleMixin ); } /** * Folds (hides/collapses) paragraphs from <code>start</code> to <code> * end</code>, into (i.e. excluding) the first paragraph of the range. * * @param styleMixin Given a paragraph style PS, return a <b>new</b> PS that will activate folding. * * <p>See {@link #fold(int, int, UnaryOperator)} for more info.</p> */ protected void foldParagraphs( int start, int end, UnaryOperator<PS> styleMixin ) { start = getAbsolutePosition( start, 0 ); end = getAbsolutePosition( end, getParagraphLength( end ) ); fold( start, end, styleMixin ); } /** * Folds (hides/collapses) paragraphs from character position <code>startPos</code> * to <code>endPos</code>, into (i.e. excluding) the first paragraph of the range. * * <p>Folding is achieved with the help of paragraph styling, which is applied to the paragraph's * TextFlow object through the applyParagraphStyle BiConsumer (supplied in the constructor to * GenericStyledArea). When applyParagraphStyle is to apply fold styling it just needs to set * the TextFlow's visibility to collapsed for it to be folded. See {@code InlineCssTextArea}, * {@code StyleClassedTextArea}, and {@code RichTextDemo} for different ways of doing this. * Also read the GitHub Wiki.</p> * * <p>The UnaryOperator <code>styleMixin</code> must return a * different paragraph style Object to what was submitted.</p> * * @param styleMixin Given a paragraph style PS, return a <b>new</b> PS that will activate folding. */ protected void fold( int startPos, int endPos, UnaryOperator<PS> styleMixin ) { ReadOnlyStyledDocument<PS, SEG, S> subDoc; UnaryOperator<Paragraph<PS, SEG, S>> mapper; subDoc = (ReadOnlyStyledDocument<PS, SEG, S>) subDocument( startPos, endPos ); mapper = p -> p.setParagraphStyle( styleMixin.apply( p.getParagraphStyle() ) ); for ( int p = 1; p < subDoc.getParagraphCount(); p++ ) { subDoc = subDoc.replaceParagraph( p, mapper ).get1(); } replace( startPos, endPos, subDoc ); recreateParagraphGraphic( offsetToPosition( startPos, Bias.Backward ).getMajor() ); moveTo( startPos ); } private void skipOverFoldedParagraphs( ObservableValue<? extends Integer> ob, Integer prevParagraph, Integer newParagraph ) { if ( getCell( newParagraph ).isFolded() ) { // Prevent Ctrl+A and Ctrl+End breaking when the last paragraph is folded // github.com/FXMisc/RichTextFX/pull/965#issuecomment-706268116 if ( newParagraph == getParagraphs().size() - 1 ) return; int skip = (newParagraph - prevParagraph > 0) ? +1 : -1; int p = newParagraph + skip; while ( p > 0 && p < getParagraphs().size() ) { if ( getCell( p ).isFolded() ) p += skip; else break; } if ( p < 0 || p == getParagraphs().size() ) p = prevParagraph; int col = Math.min( getCaretColumn(), getParagraphLength( p ) ); if ( getSelection().getLength() == 0 ) moveTo( p, col ); else moveTo( p, col, SelectionPolicy.EXTEND ); } } /** * Unfolds paragraphs <code>startingFrom</code> onwards for the currently folded block. * * <p>The UnaryOperator <code>styleMixin</code> must return a * different paragraph style Object to what was submitted.</p> * * @param isFolded Given a paragraph style PS check if it's folded. * @param styleMixin Given a paragraph style PS, return a <b>new</b> PS that excludes fold styling. */ protected void unfoldParagraphs( int startingFrom, Predicate<PS> isFolded, UnaryOperator<PS> styleMixin ) { LiveList<Paragraph<PS, SEG, S>> pList = getParagraphs(); int to = startingFrom; while ( ++to < pList.size() ) { if ( ! isFolded.test( pList.get( to ).getParagraphStyle() ) ) break; } if ( --to > startingFrom ) { ReadOnlyStyledDocument<PS, SEG, S> subDoc; UnaryOperator<Paragraph<PS, SEG, S>> mapper; int startPos = getAbsolutePosition( startingFrom, 0 ); int endPos = getAbsolutePosition( to, getParagraphLength( to ) ); subDoc = (ReadOnlyStyledDocument<PS, SEG, S>) subDocument( startPos, endPos ); mapper = p -> p.setParagraphStyle( styleMixin.apply( p.getParagraphStyle() ) ); for ( int p = 1; p < subDoc.getParagraphCount(); p++ ) { subDoc = subDoc.replaceParagraph( p, mapper ).get1(); } replace( startPos, endPos, subDoc ); moveTo( startingFrom, getParagraphLength( startingFrom ) ); recreateParagraphGraphic( startingFrom ); } } /* ********************************************************************** * * * * Public API * * * * ********************************************************************** */ @Override public void dispose() { if (undoManager != null) { undoManager.close(); } subscriptions.unsubscribe(); virtualFlow.dispose(); } /* ********************************************************************** * * * * Layout * * * * ********************************************************************** */ private BooleanProperty autoHeightProp = new SimpleBooleanProperty(); public BooleanProperty autoHeightProperty() { return autoHeightProp; } public void setAutoHeight( boolean value ) { autoHeightProp.set( value ); } public boolean isAutoHeight() { return autoHeightProp.get(); } @Override protected double computePrefHeight( double width ) { if ( autoHeightProp.get() ) { if ( getWidth() == 0.0 ) Platform.runLater( () -> requestLayout() ); else { double height = 0.0; Insets in = getInsets(); for ( int p = 0; p < getParagraphs().size(); p++ ) { height += getCell( p ).getHeight(); } if ( height > 0.0 ) { return height + in.getTop() + in.getBottom(); } } } return super.computePrefHeight( width ); } @Override protected void layoutChildren() { Insets ins = getInsets(); visibleParagraphs.suspendWhile(() -> { virtualFlow.resizeRelocate( ins.getLeft(), ins.getTop(), getWidth() - ins.getLeft() - ins.getRight(), getHeight() - ins.getTop() - ins.getBottom()); if(followCaretRequested && ! paging) { try (Guard g = viewportDirty.suspend()) { followCaret(); } } followCaretRequested = false; paging = false; }); Node holder = placeholder; if (holder != null && holder.isResizable() && holder.isManaged()) { holder.autosize(); } } /* ********************************************************************** * * * * Package-Private methods * * * * ********************************************************************** */ /** * Returns the current line as a two-level index. * The major number is the paragraph index, the minor * number is the line number within the paragraph. * * <p>This method has a side-effect of bringing the current * paragraph to the viewport if it is not already visible. */ TwoDimensional.Position currentLine() { int parIdx = getCurrentParagraph(); Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = virtualFlow.getCell(parIdx); int lineIdx = cell.getNode().getCurrentLineIndex(caretSelectionBind.getUnderlyingCaret()); return paragraphLineNavigator.position(parIdx, lineIdx); } void showCaretAtBottom() { int parIdx = getCurrentParagraph(); Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = virtualFlow.getCell(parIdx); Bounds caretBounds = cell.getNode().getCaretBounds(caretSelectionBind.getUnderlyingCaret()); double y = caretBounds.getMaxY(); suspendVisibleParsWhile(() -> virtualFlow.showAtOffset(parIdx, getViewportHeight() - y)); } void showCaretAtTop() { int parIdx = getCurrentParagraph(); Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = virtualFlow.getCell(parIdx); Bounds caretBounds = cell.getNode().getCaretBounds(caretSelectionBind.getUnderlyingCaret()); double y = caretBounds.getMinY(); suspendVisibleParsWhile(() -> virtualFlow.showAtOffset(parIdx, -y)); } /** * Returns x coordinate of the caret in the current paragraph. */ final ParagraphBox.CaretOffsetX getCaretOffsetX(CaretNode caret) { return getCell(caret.getParagraphIndex()).getCaretOffsetX(caret); } CharacterHit hit(ParagraphBox.CaretOffsetX x, TwoDimensional.Position targetLine) { int parIdx = targetLine.getMajor(); ParagraphBox<PS, SEG, S> cell = virtualFlow.getCell(parIdx).getNode(); CharacterHit parHit = cell.hitTextLine(x, targetLine.getMinor()); return parHit.offset(getParagraphOffset(parIdx)); } CharacterHit hit(ParagraphBox.CaretOffsetX x, double y) { // don't account for padding here since height of virtualFlow is used, not area + potential padding VirtualFlowHit<Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>> hit = virtualFlow.hit(0.0, y); if(hit.isBeforeCells()) { return CharacterHit.insertionAt(0); } else if(hit.isAfterCells()) { return CharacterHit.insertionAt(getLength()); } else { int parIdx = hit.getCellIndex(); int parOffset = getParagraphOffset(parIdx); ParagraphBox<PS, SEG, S> cell = hit.getCell().getNode(); Point2D cellOffset = hit.getCellOffset(); CharacterHit parHit = cell.hitText(x, cellOffset.getY()); return parHit.offset(parOffset); } } final Optional<Bounds> getSelectionBoundsOnScreen(Selection<PS, SEG, S> selection) { if (selection.getLength() == 0) { return Optional.empty(); } List<Bounds> bounds = new ArrayList<>(selection.getParagraphSpan()); for (int i = selection.getStartParagraphIndex(); i <= selection.getEndParagraphIndex(); i++) { virtualFlow.getCellIfVisible(i) .ifPresent(c -> c.getNode() .getSelectionBoundsOnScreen(selection) .ifPresent(bounds::add) ); } if(bounds.size() == 0) { return Optional.empty(); } double minX = bounds.stream().mapToDouble(Bounds::getMinX).min().getAsDouble(); double maxX = bounds.stream().mapToDouble(Bounds::getMaxX).max().getAsDouble(); double minY = bounds.stream().mapToDouble(Bounds::getMinY).min().getAsDouble(); double maxY = bounds.stream().mapToDouble(Bounds::getMaxY).max().getAsDouble(); return Optional.of(new BoundingBox(minX, minY, maxX-minX, maxY-minY)); } void clearTargetCaretOffset() { caretSelectionBind.clearTargetOffset(); } ParagraphBox.CaretOffsetX getTargetCaretOffset() { return caretSelectionBind.getTargetOffset(); } /* ********************************************************************** * * * * Private methods * * * * ********************************************************************** */ private Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> createCell( Paragraph<PS, SEG, S> paragraph, BiConsumer<TextFlow, PS> applyParagraphStyle, Function<StyledSegment<SEG, S>, Node> nodeFactory) { ParagraphBox<PS, SEG, S> box = new ParagraphBox<>(paragraph, applyParagraphStyle, nodeFactory); box.highlightTextFillProperty().bind(highlightTextFill); box.wrapTextProperty().bind(wrapTextProperty()); box.graphicFactoryProperty().bind(paragraphGraphicFactoryProperty()); box.graphicOffset.bind(virtualFlow.breadthOffsetProperty()); EventStream<Integer> boxIndexValues = box.indexProperty().values().filter(i -> i != -1); Subscription firstParPseudoClass = boxIndexValues.subscribe(idx -> box.pseudoClassStateChanged(FIRST_PAR, idx == 0)); Subscription lastParPseudoClass = EventStreams.combine( boxIndexValues, getParagraphs().sizeProperty().values() ).subscribe(in -> in.exec((i, n) -> box.pseudoClassStateChanged(LAST_PAR, i == n-1))); // set up caret Function<CaretNode, Subscription> subscribeToCaret = caret -> { EventStream<Integer> caretIndexStream = EventStreams.nonNullValuesOf(caret.paragraphIndexProperty()); // a new event stream needs to be created for each caret added, so that it will immediately // fire the box's current index value as an event, thereby running the code in the subscribe block // Reusing boxIndexValues will not fire its most recent event, leading to a caret not being added // Thus, we'll call the new event stream "fresh" box index values EventStream<Integer> freshBoxIndexValues = box.indexProperty().values().filter(i -> i != -1); return EventStreams.combine(caretIndexStream, freshBoxIndexValues) .subscribe(t -> { int caretParagraphIndex = t.get1(); int boxIndex = t.get2(); if (caretParagraphIndex == boxIndex) { box.caretsProperty().add(caret); } else { box.caretsProperty().remove(caret); } }); }; Subscription caretSubscription = caretSet.addSubscriber(subscribeToCaret); // TODO: how should 'hasCaret' be handled now? Subscription hasCaretPseudoClass = EventStreams .combine(boxIndexValues, Val.wrap(currentParagraphProperty()).values()) // box index (t1) == caret paragraph index (t2) .map(t -> t.get1().equals(t.get2())) .subscribe(value -> box.pseudoClassStateChanged(HAS_CARET, value)); Function<Selection<PS, SEG, S>, Subscription> subscribeToSelection = selection -> { EventStream<Integer> startParagraphValues = EventStreams.nonNullValuesOf(selection.startParagraphIndexProperty()); EventStream<Integer> endParagraphValues = EventStreams.nonNullValuesOf(selection.endParagraphIndexProperty()); // see comment in caret section about why a new box index EventStream is needed EventStream<Integer> freshBoxIndexValues = box.indexProperty().values().filter(i -> i != -1); return EventStreams.combine(startParagraphValues, endParagraphValues, freshBoxIndexValues) .subscribe(t -> { int startPar = t.get1(); int endPar = t.get2(); int boxIndex = t.get3(); if (startPar <= boxIndex && boxIndex <= endPar) { // So that we don't add multiple paths for the same selection, // which leads to not removing the additional paths when selection is removed, // this is a `Map#putIfAbsent(Key, Value)` implementation that creates the path lazily SelectionPath p = box.selectionsProperty().get(selection); if (p == null) { // create & configure path Val<IndexRange> range = Val.create( () -> box.getIndex() != -1 ? getParagraphSelection(selection, box.getIndex()) : EMPTY_RANGE, selection.rangeProperty() ); SelectionPath path = new SelectionPath(range); path.getStyleClass().add( selection.getSelectionName() ); selection.configureSelectionPath(path); box.selectionsProperty().put(selection, path); } } else { box.selectionsProperty().remove(selection); } }); }; Subscription selectionSubscription = selectionSet.addSubscriber(subscribeToSelection); return new Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>() { @Override public ParagraphBox<PS, SEG, S> getNode() { return box; } @Override public void updateIndex(int index) { box.setIndex(index); } @Override public void dispose() { box.highlightTextFillProperty().unbind(); box.wrapTextProperty().unbind(); box.graphicFactoryProperty().unbind(); box.graphicOffset.unbind(); box.dispose(); firstParPseudoClass.unsubscribe(); lastParPseudoClass.unsubscribe(); caretSubscription.unsubscribe(); hasCaretPseudoClass.unsubscribe(); selectionSubscription.unsubscribe(); } }; } /** Assumes this method is called within a {@link #suspendVisibleParsWhile(Runnable)} block */ private void followCaret() { int parIdx = getCurrentParagraph(); Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = virtualFlow.getCell(parIdx); Bounds caretBounds = caretSelectionBind.getUnderlyingCaret().getLayoutBounds(); double graphicWidth = cell.getNode().getGraphicPrefWidth(); Bounds region = extendLeft(caretBounds, graphicWidth); double scrollX = virtualFlow.getEstimatedScrollX(); // Ordinarily when a caret ends a selection in the target paragraph and scrolling left is required to follow // the caret then the selection won't be visible. So here we check for this scenario and adjust if needed. if ( ! isWrapText() && scrollX > 0.0 && getParagraphSelection( parIdx ).getLength() > 0 ) { double visibleLeftX = cell.getNode().getWidth() * scrollX / 100 - getWidth() + graphicWidth; CaretNode selectionStart = new CaretNode( "", this, getSelection().getStart() ); cell.getNode().caretsProperty().add( selectionStart ); Bounds startBounds = cell.getNode().getCaretBounds( selectionStart ); cell.getNode().caretsProperty().remove( selectionStart ); if ( startBounds.getMinX() - graphicWidth < visibleLeftX ) { region = extendLeft( startBounds, graphicWidth ); } } // Addresses https://github.com/FXMisc/RichTextFX/issues/937#issuecomment-674319602 if ( parIdx == getParagraphs().size()-1 && cell.getNode().getLineCount() == 1 ) { region = new BoundingBox // Correcting the region's height ( region.getMinX(), region.getMinY(), region.getWidth(), cell.getNode().getLayoutBounds().getHeight() ); } virtualFlow.show(parIdx, region); } private ParagraphBox<PS, SEG, S> getCell(int index) { return virtualFlow.getCell(index).getNode(); } private EventStream<MouseOverTextEvent> mouseOverTextEvents(ObservableSet<ParagraphBox<PS, SEG, S>> cells, Duration delay) { return merge(cells, c -> c.stationaryIndices(delay).map(e -> e.unify( l -> l.map((pos, charIdx) -> MouseOverTextEvent.beginAt(c.localToScreen(pos), getParagraphOffset(c.getIndex()) + charIdx)), r -> MouseOverTextEvent.end()))); } private int getParagraphOffset(int parIdx) { return position(parIdx, 0).toOffset(); } private Bounds getParagraphBoundsOnScreen(Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell) { Bounds nodeLocal = cell.getNode().getBoundsInLocal(); Bounds nodeScreen = cell.getNode().localToScreen(nodeLocal); Bounds areaLocal = getBoundsInLocal(); Bounds areaScreen = localToScreen(areaLocal); // use area's minX if scrolled right and paragraph's left is not visible double minX = nodeScreen.getMinX() < areaScreen.getMinX() ? areaScreen.getMinX() : nodeScreen.getMinX(); // use area's minY if scrolled down vertically and paragraph's top is not visible double minY = nodeScreen.getMinY() < areaScreen.getMinY() ? areaScreen.getMinY() : nodeScreen.getMinY(); // use area's width whether paragraph spans outside of it or not // so that short or long paragraph takes up the entire space double width = areaScreen.getWidth(); // use area's maxY if scrolled up vertically and paragraph's bottom is not visible double maxY = nodeScreen.getMaxY() < areaScreen.getMaxY() ? nodeScreen.getMaxY() : areaScreen.getMaxY(); return new BoundingBox(minX, minY, width, maxY - minY); } private Optional<Bounds> getRangeBoundsOnScreen(int paragraphIndex, int from, int to) { return virtualFlow.getCellIfVisible(paragraphIndex) .map(c -> c.getNode().getRangeBoundsOnScreen(from, to)); } private void manageSubscription(Subscription subscription) { subscriptions = subscriptions.and(subscription); } private static Bounds extendLeft(Bounds b, double w) { if(w == 0) { return b; } else { return new BoundingBox( b.getMinX() - w, b.getMinY(), b.getWidth() + w, b.getHeight()); } } private void suspendVisibleParsWhile(Runnable runnable) { Suspendable.combine(beingUpdated, visibleParagraphs).suspendWhile(runnable); } /* ********************************************************************** * * * * CSS * * * * ********************************************************************** */ private static final CssMetaData<GenericStyledArea<?, ?, ?>, Paint> HIGHLIGHT_TEXT_FILL = new CustomCssMetaData<>( "-fx-highlight-text-fill", StyleConverter.getPaintConverter(), Color.WHITE, s -> s.highlightTextFill ); private static final List<CssMetaData<? extends Styleable, ?>> CSS_META_DATA_LIST; static { List<CssMetaData<? extends Styleable, ?>> styleables = new ArrayList<>(Region.getClassCssMetaData()); styleables.add(HIGHLIGHT_TEXT_FILL); CSS_META_DATA_LIST = Collections.unmodifiableList(styleables); } @Override public List<CssMetaData<? extends Styleable, ?>> getCssMetaData() { return CSS_META_DATA_LIST; } public static List<CssMetaData<? extends Styleable, ?>> getClassCssMetaData() { return CSS_META_DATA_LIST; } }
richtextfx/src/main/java/org/fxmisc/richtext/GenericStyledArea.java
package org.fxmisc.richtext; import static org.reactfx.EventStreams.*; import static org.reactfx.util.Tuples.*; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Optional; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.IntFunction; import java.util.function.IntSupplier; import java.util.function.IntUnaryOperator; import java.util.function.Predicate; import java.util.function.UnaryOperator; import javafx.application.ConditionalFeature; import javafx.application.Platform; import javafx.beans.NamedArg; import javafx.beans.binding.Bindings; import javafx.beans.property.BooleanProperty; import javafx.beans.property.DoubleProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener.Change; import javafx.collections.ObservableSet; import javafx.css.CssMetaData; import javafx.css.PseudoClass; import javafx.css.StyleConverter; import javafx.css.Styleable; import javafx.css.StyleableObjectProperty; import javafx.event.Event; import javafx.event.EventHandler; import javafx.geometry.BoundingBox; import javafx.geometry.Bounds; import javafx.geometry.Insets; import javafx.geometry.Point2D; import javafx.scene.Node; import javafx.scene.control.ContextMenu; import javafx.scene.control.IndexRange; import javafx.scene.input.InputMethodEvent; import javafx.scene.input.InputMethodRequests; import javafx.scene.input.InputMethodTextRun; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.CornerRadii; import javafx.scene.layout.Region; import javafx.scene.paint.Color; import javafx.scene.paint.Paint; import javafx.scene.shape.LineTo; import javafx.scene.shape.PathElement; import javafx.scene.text.TextFlow; import org.fxmisc.flowless.Cell; import org.fxmisc.flowless.VirtualFlow; import org.fxmisc.flowless.VirtualFlowHit; import org.fxmisc.flowless.Virtualized; import org.fxmisc.flowless.VirtualizedScrollPane; import org.fxmisc.richtext.model.Codec; import org.fxmisc.richtext.model.EditableStyledDocument; import org.fxmisc.richtext.model.GenericEditableStyledDocument; import org.fxmisc.richtext.model.Paragraph; import org.fxmisc.richtext.model.ReadOnlyStyledDocument; import org.fxmisc.richtext.model.PlainTextChange; import org.fxmisc.richtext.model.Replacement; import org.fxmisc.richtext.model.RichTextChange; import org.fxmisc.richtext.model.StyleSpans; import org.fxmisc.richtext.model.StyledDocument; import org.fxmisc.richtext.model.StyledSegment; import org.fxmisc.richtext.model.TextOps; import org.fxmisc.richtext.model.TwoDimensional; import org.fxmisc.richtext.model.TwoLevelNavigator; import org.fxmisc.richtext.event.MouseOverTextEvent; import org.fxmisc.richtext.util.SubscribeableContentsObsSet; import org.fxmisc.richtext.util.UndoUtils; import org.fxmisc.undo.UndoManager; import org.reactfx.EventStream; import org.reactfx.EventStreams; import org.reactfx.Guard; import org.reactfx.Subscription; import org.reactfx.Suspendable; import org.reactfx.SuspendableEventStream; import org.reactfx.SuspendableNo; import org.reactfx.collection.LiveList; import org.reactfx.collection.SuspendableList; import org.reactfx.util.Tuple2; import org.reactfx.value.Val; import org.reactfx.value.Var; /** * Text editing control that renders and edits a {@link EditableStyledDocument}. * * Accepts user input (keyboard, mouse) and provides API to assign style to text ranges. It is suitable for * syntax highlighting and rich-text editors. * * <h3>Adding Scrollbars to the Area</h3> * * <p>By default, scroll bars do not appear when the content spans outside of the viewport. * To add scroll bars, the area needs to be wrapped in a {@link VirtualizedScrollPane}. For example, </p> * <pre><code> * // shows area without scroll bars * InlineCssTextArea area = new InlineCssTextArea(); * * // add scroll bars that will display as needed * VirtualizedScrollPane&lt;InlineCssTextArea&gt; vsPane = new VirtualizedScrollPane&lt;&gt;(area); * * Parent parent = // creation code * parent.getChildren().add(vsPane) * </code></pre> * * <h3>Auto-Scrolling to the Caret</h3> * * <p>Every time the underlying {@link EditableStyledDocument} changes via user interaction (e.g. typing) through * the {@code GenericStyledArea}, the area will scroll to insure the caret is kept in view. However, this does not * occur if changes are done programmatically. For example, let's say the area is displaying the bottom part * of the area's {@link EditableStyledDocument} and some code changes something in the top part of the document * that is not currently visible. If there is no call to {@link #requestFollowCaret()} at the end of that code, * the area will not auto-scroll to that section of the document. The change will occur, and the user will continue * to see the bottom part of the document as before. If such a call is there, then the area will scroll * to the top of the document and no longer display the bottom part of it.</p> * <p>For example...</p> * <pre><code> * // assuming the user is currently seeing the top of the area * * // then changing the bottom, currently not visible part of the area... * int startParIdx = 40; * int startColPosition = 2; * int endParIdx = 42; * int endColPosition = 10; * * // ...by itself will not scroll the viewport to where the change occurs * area.replaceText(startParIdx, startColPosition, endParIdx, endColPosition, "replacement text"); * * // adding this line after the last modification to the area will cause the viewport to scroll to that change * // leaving the following line out will leave the viewport unaffected and the user will not notice any difference * area.requestFollowCaret(); * </code></pre> * * <p>Additionally, when overriding the default user-interaction behavior, remember to include a call * to {@link #requestFollowCaret()}.</p> * * <h3>Setting the area's {@link UndoManager}</h3> * * <p> * The default UndoManager can undo/redo either {@link PlainTextChange}s or {@link RichTextChange}s. To create * your own specialized version that may use changes different than these (or a combination of these changes * with others), create them using the convenient factory methods in {@link UndoUtils}. * </p> * * <h3>Overriding default keyboard behavior</h3> * * {@code GenericStyledArea} uses {@link javafx.scene.input.KeyEvent#KEY_TYPED KEY_TYPED} to handle ordinary * character input and {@link javafx.scene.input.KeyEvent#KEY_PRESSED KEY_PRESSED} to handle control key * combinations (including Enter and Tab). To add or override some keyboard * shortcuts, while keeping the rest in place, you would combine the default * event handler with a new one that adds or overrides some of the default * key combinations. * <p> * For example, this is how to bind {@code Ctrl+S} to the {@code save()} operation: * </p> * <pre><code> * import static javafx.scene.input.KeyCode.*; * import static javafx.scene.input.KeyCombination.*; * import static org.fxmisc.wellbehaved.event.EventPattern.*; * import static org.fxmisc.wellbehaved.event.InputMap.*; * * import org.fxmisc.wellbehaved.event.Nodes; * * // installs the following consume InputMap, * // so that a CTRL+S event saves the document and consumes the event * Nodes.addInputMap(area, consume(keyPressed(S, CONTROL_DOWN), event -&gt; save())); * </code></pre> * * <h3>Overriding default mouse behavior</h3> * * The area's default mouse behavior properly handles auto-scrolling and dragging the selected text to a new location. * As such, some parts cannot be partially overridden without it affecting other behavior. * * <p>The following lists either {@link org.fxmisc.wellbehaved.event.EventPattern}s that cannot be * overridden without negatively affecting the default mouse behavior or describe how to safely override things * in a special way without disrupting the auto scroll behavior.</p> * <ul> * <li> * <em>First (1 click count) Primary Button Mouse Pressed Events:</em> * (<code>EventPattern.mousePressed(MouseButton.PRIMARY).onlyIf(e -&gt; e.getClickCount() == 1)</code>). * Do not override. Instead, use {@link #onOutsideSelectionMousePressed}, * {@link #onInsideSelectionMousePressReleased}, or see next item. * </li> * <li>( * <em>All Other Mouse Pressed Events (e.g., Primary with 2+ click count):</em> * Aside from hiding the context menu if it is showing (use {@link #hideContextMenu()} some((where in your * overriding InputMap to maintain this behavior), these can be safely overridden via any of the * {@link org.fxmisc.wellbehaved.event.template.InputMapTemplate InputMapTemplate's factory methods} or * {@link org.fxmisc.wellbehaved.event.InputMap InputMap's factory methods}. * </li> * <li> * <em>Primary-Button-only Mouse Drag Detection Events:</em> * (<code>EventPattern.eventType(MouseEvent.DRAG_DETECTED).onlyIf(e -&gt; e.getButton() == MouseButton.PRIMARY &amp;&amp; !e.isMiddleButtonDown() &amp;&amp; !e.isSecondaryButtonDown())</code>). * Do not override. Instead, use {@link #onNewSelectionDrag} or {@link #onSelectionDrag}. * </li> * <li> * <em>Primary-Button-only Mouse Drag Events:</em> * (<code>EventPattern.mouseDragged().onlyIf(e -&gt; e.getButton() == MouseButton.PRIMARY &amp;&amp; !e.isMiddleButtonDown() &amp;&amp; !e.isSecondaryButtonDown())</code>) * Do not override, but see next item. * </li> * <li> * <em>All Other Mouse Drag Events:</em> * You may safely override other Mouse Drag Events using different * {@link org.fxmisc.wellbehaved.event.EventPattern}s without affecting default behavior only if * process InputMaps ( * {@link org.fxmisc.wellbehaved.event.template.InputMapTemplate#process(javafx.event.EventType, BiFunction)}, * {@link org.fxmisc.wellbehaved.event.template.InputMapTemplate#process(org.fxmisc.wellbehaved.event.EventPattern, BiFunction)}, * {@link org.fxmisc.wellbehaved.event.InputMap#process(javafx.event.EventType, Function)}, or * {@link org.fxmisc.wellbehaved.event.InputMap#process(org.fxmisc.wellbehaved.event.EventPattern, Function)} * ) are used and {@link org.fxmisc.wellbehaved.event.InputHandler.Result#PROCEED} is returned. * The area has a "catch all" Mouse Drag InputMap that will auto scroll towards the mouse drag event when it * occurs outside the bounds of the area and will stop auto scrolling when the mouse event occurs within the * area. However, this only works if the event is not consumed before the event reaches that InputMap. * To insure the auto scroll feature is enabled, set {@link #isAutoScrollOnDragDesired()} to true in your * process InputMap. If the feature is not desired for that specific drag event, set it to false in the * process InputMap. * <em>Note: Due to this "catch-all" nature, all Mouse Drag Events are consumed.</em> * </li> * <li> * <em>Primary-Button-only Mouse Released Events:</em> * (<code>EventPattern.mouseReleased().onlyIf(e -&gt; e.getButton() == MouseButton.PRIMARY &amp;&amp; !e.isMiddleButtonDown() &amp;&amp; !e.isSecondaryButtonDown())</code>). * Do not override. Instead, use {@link #onNewSelectionDragFinished}, {@link #onSelectionDropped}, or see next item. * </li> * <li> * <em>All other Mouse Released Events:</em> * You may override other Mouse Released Events using different * {@link org.fxmisc.wellbehaved.event.EventPattern}s without affecting default behavior only if * process InputMaps ( * {@link org.fxmisc.wellbehaved.event.template.InputMapTemplate#process(javafx.event.EventType, BiFunction)}, * {@link org.fxmisc.wellbehaved.event.template.InputMapTemplate#process(org.fxmisc.wellbehaved.event.EventPattern, BiFunction)}, * {@link org.fxmisc.wellbehaved.event.InputMap#process(javafx.event.EventType, Function)}, or * {@link org.fxmisc.wellbehaved.event.InputMap#process(org.fxmisc.wellbehaved.event.EventPattern, Function)} * ) are used and {@link org.fxmisc.wellbehaved.event.InputHandler.Result#PROCEED} is returned. * The area has a "catch-all" InputMap that will consume all mouse released events and stop auto scroll if it * was scrolling. However, this only works if the event is not consumed before the event reaches that InputMap. * <em>Note: Due to this "catch-all" nature, all Mouse Released Events are consumed.</em> * </li> * </ul> * * <h3>CSS, Style Classes, and Pseudo Classes</h3> * <p> * Refer to the <a href="https://github.com/FXMisc/RichTextFX/wiki/RichTextFX-CSS-Reference-Guide"> * RichTextFX CSS Reference Guide * </a>. * </p> * * <h3>Area Actions and Other Operations</h3> * <p> * To distinguish the actual operations one can do on this area from the boilerplate methods * within this area (e.g. properties and their getters/setters, etc.), look at the interfaces * this area implements. Each lists and documents methods that fall under that category. * </p> * <p> * To update multiple portions of the area's underlying document in one call, see {@link #createMultiChange()}. * </p> * * <h3>Calculating a Position Within the Area</h3> * <p> * To calculate a position or index within the area, read through the javadoc of * {@link org.fxmisc.richtext.model.TwoDimensional} and {@link org.fxmisc.richtext.model.TwoDimensional.Bias}. * Also, read the difference between "position" and "index" in * {@link org.fxmisc.richtext.model.StyledDocument#getAbsolutePosition(int, int)}. * </p> * * @see EditableStyledDocument * @see TwoDimensional * @see org.fxmisc.richtext.model.TwoDimensional.Bias * @see VirtualFlow * @see VirtualizedScrollPane * @see Caret * @see Selection * @see CaretSelectionBind * * @param <PS> type of style that can be applied to paragraphs (e.g. {@link TextFlow}. * @param <SEG> type of segment used in {@link Paragraph}. Can be only text (plain or styled) or * a type that combines text and other {@link Node}s. * @param <S> type of style that can be applied to a segment. */ public class GenericStyledArea<PS, SEG, S> extends Region implements TextEditingArea<PS, SEG, S>, EditActions<PS, SEG, S>, ClipboardActions<PS, SEG, S>, NavigationActions<PS, SEG, S>, StyleActions<PS, S>, UndoActions, ViewActions<PS, SEG, S>, TwoDimensional, Virtualized { /** * Index range [0, 0). */ public static final IndexRange EMPTY_RANGE = new IndexRange(0, 0); private static final PseudoClass READ_ONLY = PseudoClass.getPseudoClass("readonly"); private static final PseudoClass HAS_CARET = PseudoClass.getPseudoClass("has-caret"); private static final PseudoClass FIRST_PAR = PseudoClass.getPseudoClass("first-paragraph"); private static final PseudoClass LAST_PAR = PseudoClass.getPseudoClass("last-paragraph"); /* ********************************************************************** * * * * Properties * * * * Properties affect behavior and/or appearance of this control. * * * * They are readable and writable by the client code and never change by * * other means, i.e. they contain either the default value or the value * * set by the client code. * * * * ********************************************************************** */ /** * Text color for highlighted text. */ private final StyleableObjectProperty<Paint> highlightTextFill = new CustomStyleableProperty<>(Color.WHITE, "highlightTextFill", this, HIGHLIGHT_TEXT_FILL); // editable property private final BooleanProperty editable = new SimpleBooleanProperty(this, "editable", true) { @Override protected void invalidated() { ((Region) getBean()).pseudoClassStateChanged(READ_ONLY, !get()); } }; @Override public final BooleanProperty editableProperty() { return editable; } // Don't remove as FXMLLoader doesn't recognise default methods ! @Override public void setEditable(boolean value) { editable.set(value); } @Override public boolean isEditable() { return editable.get(); } // wrapText property private final BooleanProperty wrapText = new SimpleBooleanProperty(this, "wrapText"); @Override public final BooleanProperty wrapTextProperty() { return wrapText; } // Don't remove as FXMLLoader doesn't recognise default methods ! @Override public void setWrapText(boolean value) { wrapText.set(value); } @Override public boolean isWrapText() { return wrapText.get(); } // undo manager private UndoManager undoManager; @Override public UndoManager getUndoManager() { return undoManager; } /** * @param undoManager may be null in which case a no op undo manager will be set. */ @Override public void setUndoManager(UndoManager undoManager) { this.undoManager.close(); this.undoManager = undoManager != null ? undoManager : UndoUtils.noOpUndoManager(); } private Locale textLocale = Locale.getDefault(); /** * This is used to determine word and sentence breaks while navigating or selecting. * Override this method if your paragraph or text style accommodates Locales as well. * @return Locale.getDefault() by default */ @Override public Locale getLocale() { return textLocale; } public void setLocale( Locale editorLocale ) { textLocale = editorLocale; } private final ObjectProperty<Duration> mouseOverTextDelay = new SimpleObjectProperty<>(null); @Override public ObjectProperty<Duration> mouseOverTextDelayProperty() { return mouseOverTextDelay; } private final ObjectProperty<IntFunction<? extends Node>> paragraphGraphicFactory = new SimpleObjectProperty<>(null); @Override public ObjectProperty<IntFunction<? extends Node>> paragraphGraphicFactoryProperty() { return paragraphGraphicFactory; } public void recreateParagraphGraphic( int parNdx ) { ObjectProperty<IntFunction<? extends Node>> gProp; gProp = getCell(parNdx).graphicFactoryProperty(); gProp.unbind(); gProp.bind(paragraphGraphicFactoryProperty()); } public Node getParagraphGraphic( int parNdx ) { return getCell(parNdx).getGraphic(); } /** * This Node is shown to the user, centered over the area, when the area has no text content. */ private ObjectProperty<Node> placeHolderProp = new SimpleObjectProperty<>(this, "placeHolder", null); public final ObjectProperty<Node> placeholderProperty() { return placeHolderProp; } public final void setPlaceholder(Node value) { placeHolderProp.set(value); } public final Node getPlaceholder() { return placeHolderProp.get(); } private ObjectProperty<ContextMenu> contextMenu = new SimpleObjectProperty<>(null); @Override public final ObjectProperty<ContextMenu> contextMenuObjectProperty() { return contextMenu; } // Don't remove as FXMLLoader doesn't recognise default methods ! @Override public void setContextMenu(ContextMenu menu) { contextMenu.set(menu); } @Override public ContextMenu getContextMenu() { return contextMenu.get(); } protected final boolean isContextMenuPresent() { return contextMenu.get() != null; } private DoubleProperty contextMenuXOffset = new SimpleDoubleProperty(2); @Override public final DoubleProperty contextMenuXOffsetProperty() { return contextMenuXOffset; } // Don't remove as FXMLLoader doesn't recognise default methods ! @Override public void setContextMenuXOffset(double offset) { contextMenuXOffset.set(offset); } @Override public double getContextMenuXOffset() { return contextMenuXOffset.get(); } private DoubleProperty contextMenuYOffset = new SimpleDoubleProperty(2); @Override public final DoubleProperty contextMenuYOffsetProperty() { return contextMenuYOffset; } // Don't remove as FXMLLoader doesn't recognise default methods ! @Override public void setContextMenuYOffset(double offset) { contextMenuYOffset.set(offset); } @Override public double getContextMenuYOffset() { return contextMenuYOffset.get(); } private final BooleanProperty useInitialStyleForInsertion = new SimpleBooleanProperty(); @Override public BooleanProperty useInitialStyleForInsertionProperty() { return useInitialStyleForInsertion; } private Optional<Tuple2<Codec<PS>, Codec<StyledSegment<SEG, S>>>> styleCodecs = Optional.empty(); @Override public void setStyleCodecs(Codec<PS> paragraphStyleCodec, Codec<StyledSegment<SEG, S>> styledSegCodec) { styleCodecs = Optional.of(t(paragraphStyleCodec, styledSegCodec)); } @Override public Optional<Tuple2<Codec<PS>, Codec<StyledSegment<SEG, S>>>> getStyleCodecs() { return styleCodecs; } @Override public Var<Double> estimatedScrollXProperty() { return virtualFlow.estimatedScrollXProperty(); } @Override public Var<Double> estimatedScrollYProperty() { return virtualFlow.estimatedScrollYProperty(); } private final SubscribeableContentsObsSet<CaretNode> caretSet; private final SubscribeableContentsObsSet<Selection<PS, SEG, S>> selectionSet; public final boolean addCaret(CaretNode caret) { if (caret.getArea() != this) { throw new IllegalArgumentException(String.format( "The caret (%s) is associated with a different area (%s), " + "not this area (%s)", caret, caret.getArea(), this)); } return caretSet.add(caret); } public final boolean removeCaret(CaretNode caret) { if (caret != caretSelectionBind.getUnderlyingCaret()) { return caretSet.remove(caret); } else { return false; } } public final boolean addSelection(Selection<PS, SEG, S> selection) { if (selection.getArea() != this) { throw new IllegalArgumentException(String.format( "The selection (%s) is associated with a different area (%s), " + "not this area (%s)", selection, selection.getArea(), this)); } return selectionSet.add(selection); } public final boolean removeSelection(Selection<PS, SEG, S> selection) { if (selection != caretSelectionBind.getUnderlyingSelection()) { return selectionSet.remove(selection); } else { return false; } } /* ********************************************************************** * * * * Mouse Behavior Hooks * * * * Hooks for overriding some of the default mouse behavior * * * * ********************************************************************** */ @Override public final EventHandler<MouseEvent> getOnOutsideSelectionMousePressed() { return onOutsideSelectionMousePressed.get(); } @Override public final void setOnOutsideSelectionMousePressed(EventHandler<MouseEvent> handler) { onOutsideSelectionMousePressed.set( handler ); } @Override public final ObjectProperty<EventHandler<MouseEvent>> onOutsideSelectionMousePressedProperty() { return onOutsideSelectionMousePressed; } private final ObjectProperty<EventHandler<MouseEvent>> onOutsideSelectionMousePressed = new SimpleObjectProperty<>( e -> { moveTo( hit( e.getX(), e.getY() ).getInsertionIndex(), SelectionPolicy.CLEAR ); }); @Override public final EventHandler<MouseEvent> getOnInsideSelectionMousePressReleased() { return onInsideSelectionMousePressReleased.get(); } @Override public final void setOnInsideSelectionMousePressReleased(EventHandler<MouseEvent> handler) { onInsideSelectionMousePressReleased.set( handler ); } @Override public final ObjectProperty<EventHandler<MouseEvent>> onInsideSelectionMousePressReleasedProperty() { return onInsideSelectionMousePressReleased; } private final ObjectProperty<EventHandler<MouseEvent>> onInsideSelectionMousePressReleased = new SimpleObjectProperty<>( e -> { moveTo( hit( e.getX(), e.getY() ).getInsertionIndex(), SelectionPolicy.CLEAR ); }); private final ObjectProperty<Consumer<Point2D>> onNewSelectionDrag = new SimpleObjectProperty<>(p -> { CharacterHit hit = hit(p.getX(), p.getY()); moveTo(hit.getInsertionIndex(), SelectionPolicy.ADJUST); }); @Override public final ObjectProperty<Consumer<Point2D>> onNewSelectionDragProperty() { return onNewSelectionDrag; } @Override public final EventHandler<MouseEvent> getOnNewSelectionDragFinished() { return onNewSelectionDragFinished.get(); } @Override public final void setOnNewSelectionDragFinished(EventHandler<MouseEvent> handler) { onNewSelectionDragFinished.set( handler ); } @Override public final ObjectProperty<EventHandler<MouseEvent>> onNewSelectionDragFinishedProperty() { return onNewSelectionDragFinished; } private final ObjectProperty<EventHandler<MouseEvent>> onNewSelectionDragFinished = new SimpleObjectProperty<>( e -> { CharacterHit hit = hit(e.getX(), e.getY()); moveTo(hit.getInsertionIndex(), SelectionPolicy.ADJUST); }); private final ObjectProperty<Consumer<Point2D>> onSelectionDrag = new SimpleObjectProperty<>(p -> { CharacterHit hit = hit(p.getX(), p.getY()); displaceCaret(hit.getInsertionIndex()); }); @Override public final ObjectProperty<Consumer<Point2D>> onSelectionDragProperty() { return onSelectionDrag; } @Override public final EventHandler<MouseEvent> getOnSelectionDropped() { return onSelectionDropped.get(); } @Override public final void setOnSelectionDropped(EventHandler<MouseEvent> handler) { onSelectionDropped.set( handler ); } @Override public final ObjectProperty<EventHandler<MouseEvent>> onSelectionDroppedProperty() { return onSelectionDropped; } private final ObjectProperty<EventHandler<MouseEvent>> onSelectionDropped = new SimpleObjectProperty<>( e -> { moveSelectedText( hit( e.getX(), e.getY() ).getInsertionIndex() ); }); // not a hook, but still plays a part in the default mouse behavior private final BooleanProperty autoScrollOnDragDesired = new SimpleBooleanProperty(true); @Override public final BooleanProperty autoScrollOnDragDesiredProperty() { return autoScrollOnDragDesired; } // Don't remove as FXMLLoader doesn't recognise default methods ! @Override public void setAutoScrollOnDragDesired(boolean val) { autoScrollOnDragDesired.set(val); } @Override public boolean isAutoScrollOnDragDesired() { return autoScrollOnDragDesired.get(); } /* ********************************************************************** * * * * Observables * * * * Observables are "dynamic" (i.e. changing) characteristics of this * * control. They are not directly settable by the client code, but change * * in response to user input and/or API actions. * * * * ********************************************************************** */ // text @Override public final ObservableValue<String> textProperty() { return content.textProperty(); } // rich text @Override public final StyledDocument<PS, SEG, S> getDocument() { return content; } private CaretSelectionBind<PS, SEG, S> caretSelectionBind; @Override public final CaretSelectionBind<PS, SEG, S> getCaretSelectionBind() { return caretSelectionBind; } // length @Override public final ObservableValue<Integer> lengthProperty() { return content.lengthProperty(); } // paragraphs @Override public LiveList<Paragraph<PS, SEG, S>> getParagraphs() { return content.getParagraphs(); } private final SuspendableList<Paragraph<PS, SEG, S>> visibleParagraphs; @Override public final LiveList<Paragraph<PS, SEG, S>> getVisibleParagraphs() { return visibleParagraphs; } // beingUpdated private final SuspendableNo beingUpdated = new SuspendableNo(); @Override public final SuspendableNo beingUpdatedProperty() { return beingUpdated; } // total width estimate @Override public Val<Double> totalWidthEstimateProperty() { return virtualFlow.totalWidthEstimateProperty(); } // total height estimate @Override public Val<Double> totalHeightEstimateProperty() { return virtualFlow.totalHeightEstimateProperty(); } /* ********************************************************************** * * * * Event streams * * * * ********************************************************************** */ @Override public EventStream<List<RichTextChange<PS, SEG, S>>> multiRichChanges() { return content.multiRichChanges(); } @Override public EventStream<List<PlainTextChange>> multiPlainChanges() { return content.multiPlainChanges(); } // text changes @Override public final EventStream<PlainTextChange> plainTextChanges() { return content.plainChanges(); } // rich text changes @Override public final EventStream<RichTextChange<PS, SEG, S>> richChanges() { return content.richChanges(); } private final SuspendableEventStream<?> viewportDirty; @Override public final EventStream<?> viewportDirtyEvents() { return viewportDirty; } /* ********************************************************************** * * * * Private fields * * * * ********************************************************************** */ private Subscription subscriptions = () -> {}; private final VirtualFlow<Paragraph<PS, SEG, S>, Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>> virtualFlow; // used for two-level navigation, where on the higher level are // paragraphs and on the lower level are lines within a paragraph private final TwoLevelNavigator paragraphLineNavigator; private boolean paging, followCaretRequested = false; /* ********************************************************************** * * * * Fields necessary for Cloning * * * * ********************************************************************** */ private final EditableStyledDocument<PS, SEG, S> content; @Override public final EditableStyledDocument<PS, SEG, S> getContent() { return content; } private final S initialTextStyle; @Override public final S getInitialTextStyle() { return initialTextStyle; } private final PS initialParagraphStyle; @Override public final PS getInitialParagraphStyle() { return initialParagraphStyle; } private final BiConsumer<TextFlow, PS> applyParagraphStyle; @Override public final BiConsumer<TextFlow, PS> getApplyParagraphStyle() { return applyParagraphStyle; } // TODO: Currently, only undo/redo respect this flag. private final boolean preserveStyle; @Override public final boolean isPreserveStyle() { return preserveStyle; } /* ********************************************************************** * * * * Miscellaneous * * * * ********************************************************************** */ private final TextOps<SEG, S> segmentOps; @Override public final TextOps<SEG, S> getSegOps() { return segmentOps; } private final EventStream<Boolean> autoCaretBlinksSteam; final EventStream<Boolean> autoCaretBlink() { return autoCaretBlinksSteam; } /* ********************************************************************** * * * * Constructors * * * * ********************************************************************** */ /** * Creates a text area with empty text content. * * @param initialParagraphStyle style to use in places where no other style is * specified (yet). * @param applyParagraphStyle function that, given a {@link TextFlow} node and * a style, applies the style to the paragraph node. This function is * used by the default skin to apply style to paragraph nodes. * @param initialTextStyle style to use in places where no other style is * specified (yet). * @param segmentOps The operations which are defined on the text segment objects. * @param nodeFactory A function which is used to create the JavaFX scene nodes for a * particular segment. */ public GenericStyledArea(@NamedArg("initialParagraphStyle") PS initialParagraphStyle, @NamedArg("applyParagraphStyle") BiConsumer<TextFlow, PS> applyParagraphStyle, @NamedArg("initialTextStyle") S initialTextStyle, @NamedArg("segmentOps") TextOps<SEG, S> segmentOps, @NamedArg("nodeFactory") Function<StyledSegment<SEG, S>, Node> nodeFactory) { this(initialParagraphStyle, applyParagraphStyle, initialTextStyle, segmentOps, true, nodeFactory); } /** * Same as {@link #GenericStyledArea(Object, BiConsumer, Object, TextOps, Function)} but also allows one * to specify whether the undo manager should be a plain or rich undo manager via {@code preserveStyle}. * * @param initialParagraphStyle style to use in places where no other style is specified (yet). * @param applyParagraphStyle function that, given a {@link TextFlow} node and * a style, applies the style to the paragraph node. This function is * used by the default skin to apply style to paragraph nodes. * @param initialTextStyle style to use in places where no other style is specified (yet). * @param segmentOps The operations which are defined on the text segment objects. * @param preserveStyle whether to use an undo manager that can undo/redo {@link RichTextChange}s or * {@link PlainTextChange}s * @param nodeFactory A function which is used to create the JavaFX scene node for a particular segment. */ public GenericStyledArea(@NamedArg("initialParagraphStyle") PS initialParagraphStyle, @NamedArg("applyParagraphStyle") BiConsumer<TextFlow, PS> applyParagraphStyle, @NamedArg("initialTextStyle") S initialTextStyle, @NamedArg("segmentOps") TextOps<SEG, S> segmentOps, @NamedArg("preserveStyle") boolean preserveStyle, @NamedArg("nodeFactory") Function<StyledSegment<SEG, S>, Node> nodeFactory) { this(initialParagraphStyle, applyParagraphStyle, initialTextStyle, new GenericEditableStyledDocument<>(initialParagraphStyle, initialTextStyle, segmentOps), segmentOps, preserveStyle, nodeFactory); } /** * The same as {@link #GenericStyledArea(Object, BiConsumer, Object, TextOps, Function)} except that * this constructor can be used to create another {@code GenericStyledArea} that renders and edits the same * {@link EditableStyledDocument} or when one wants to use a custom {@link EditableStyledDocument} implementation. */ public GenericStyledArea( @NamedArg("initialParagraphStyle") PS initialParagraphStyle, @NamedArg("applyParagraphStyle") BiConsumer<TextFlow, PS> applyParagraphStyle, @NamedArg("initialTextStyle") S initialTextStyle, @NamedArg("document") EditableStyledDocument<PS, SEG, S> document, @NamedArg("segmentOps") TextOps<SEG, S> segmentOps, @NamedArg("nodeFactory") Function<StyledSegment<SEG, S>, Node> nodeFactory) { this(initialParagraphStyle, applyParagraphStyle, initialTextStyle, document, segmentOps, true, nodeFactory); } /** * Creates an area with flexibility in all of its options. * * @param initialParagraphStyle style to use in places where no other style is specified (yet). * @param applyParagraphStyle function that, given a {@link TextFlow} node and * a style, applies the style to the paragraph node. This function is * used by the default skin to apply style to paragraph nodes. * @param initialTextStyle style to use in places where no other style is specified (yet). * @param document the document to render and edit * @param segmentOps The operations which are defined on the text segment objects. * @param preserveStyle whether to use an undo manager that can undo/redo {@link RichTextChange}s or * {@link PlainTextChange}s * @param nodeFactory A function which is used to create the JavaFX scene node for a particular segment. */ public GenericStyledArea( @NamedArg("initialParagraphStyle") PS initialParagraphStyle, @NamedArg("applyParagraphStyle") BiConsumer<TextFlow, PS> applyParagraphStyle, @NamedArg("initialTextStyle") S initialTextStyle, @NamedArg("document") EditableStyledDocument<PS, SEG, S> document, @NamedArg("segmentOps") TextOps<SEG, S> segmentOps, @NamedArg("preserveStyle") boolean preserveStyle, @NamedArg("nodeFactory") Function<StyledSegment<SEG, S>, Node> nodeFactory) { this.initialTextStyle = initialTextStyle; this.initialParagraphStyle = initialParagraphStyle; this.preserveStyle = preserveStyle; this.content = document; this.applyParagraphStyle = applyParagraphStyle; this.segmentOps = segmentOps; undoManager = UndoUtils.defaultUndoManager(this); // allow tab traversal into area setFocusTraversable(true); this.setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY))); getStyleClass().add("styled-text-area"); getStylesheets().add(StyledTextArea.class.getResource("styled-text-area.css").toExternalForm()); // keeps track of currently used non-empty cells @SuppressWarnings("unchecked") ObservableSet<ParagraphBox<PS, SEG, S>> nonEmptyCells = FXCollections.observableSet(); caretSet = new SubscribeableContentsObsSet<>(); manageSubscription(() -> { List<CaretNode> l = new ArrayList<>(caretSet); caretSet.clear(); l.forEach(CaretNode::dispose); }); selectionSet = new SubscribeableContentsObsSet<>(); manageSubscription(() -> { List<Selection<PS, SEG, S>> l = new ArrayList<>(selectionSet); selectionSet.clear(); l.forEach(Selection::dispose); }); // Initialize content virtualFlow = VirtualFlow.createVertical( getParagraphs(), par -> { Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = createCell( par, applyParagraphStyle, nodeFactory); nonEmptyCells.add(cell.getNode()); return cell.beforeReset(() -> nonEmptyCells.remove(cell.getNode())) .afterUpdateItem(p -> nonEmptyCells.add(cell.getNode())); }); getChildren().add(virtualFlow); // initialize navigator IntSupplier cellCount = () -> getParagraphs().size(); IntUnaryOperator cellLength = i -> virtualFlow.getCell(i).getNode().getLineCount(); paragraphLineNavigator = new TwoLevelNavigator(cellCount, cellLength); viewportDirty = merge( // no need to check for width & height invalidations as scroll values update when these do // scale invalidationsOf(scaleXProperty()), invalidationsOf(scaleYProperty()), // scroll invalidationsOf(estimatedScrollXProperty()), invalidationsOf(estimatedScrollYProperty()) ).suppressible(); autoCaretBlinksSteam = EventStreams.valuesOf(focusedProperty() .and(editableProperty()) .and(disabledProperty().not()) ); caretSelectionBind = new CaretSelectionBindImpl<>("main-caret", "main-selection",this); caretSelectionBind.paragraphIndexProperty().addListener( this::skipOverFoldedParagraphs ); caretSet.add(caretSelectionBind.getUnderlyingCaret()); selectionSet.add(caretSelectionBind.getUnderlyingSelection()); visibleParagraphs = LiveList.map(virtualFlow.visibleCells(), c -> c.getNode().getParagraph()).suspendable(); final Suspendable omniSuspendable = Suspendable.combine( beingUpdated, // must be first, to be the last one to release visibleParagraphs ); manageSubscription(omniSuspendable.suspendWhen(content.beingUpdatedProperty())); // dispatch MouseOverTextEvents when mouseOverTextDelay is not null EventStreams.valuesOf(mouseOverTextDelayProperty()) .flatMap(delay -> delay != null ? mouseOverTextEvents(nonEmptyCells, delay) : EventStreams.never()) .subscribe(evt -> Event.fireEvent(this, evt)); new GenericStyledAreaBehavior(this); // Setup place holder visibility & placement final Val<Boolean> showPlaceholder = Val.create ( () -> getLength() == 0 && ! isFocused(), lengthProperty(), focusedProperty() ); placeHolderProp.addListener( (ob,ov,newNode) -> displayPlaceHolder( showPlaceholder.getValue(), newNode ) ); showPlaceholder.addListener( (ob,ov,show) -> displayPlaceHolder( show, getPlaceholder() ) ); if ( Platform.isFxApplicationThread() ) initInputMethodHandling(); else Platform.runLater( () -> initInputMethodHandling() ); } private void initInputMethodHandling() { if( Platform.isSupported( ConditionalFeature.INPUT_METHOD ) ) { setOnInputMethodTextChanged( event -> handleInputMethodEvent(event) ); // Both of these have to be set for input composition to work ! setInputMethodRequests( new InputMethodRequests() { @Override public Point2D getTextLocation( int offset ) { Bounds charBounds = getCaretBounds().get(); return new Point2D( charBounds.getMaxX() - 5, charBounds.getMaxY() ); } @Override public int getLocationOffset( int x, int y ) { return 0; } @Override public void cancelLatestCommittedText() {} @Override public String getSelectedText() { return getSelectedText(); } }); } } // Start/Length of the text under input method composition private int imstart; private int imlength; protected void handleInputMethodEvent( InputMethodEvent event ) { if ( isEditable() && !isDisabled() ) { // remove previous input method text (if any) or selected text if ( imlength != 0 ) { selectRange( imstart, imstart + imlength ); } // Insert committed text if ( event.getCommitted().length() != 0 ) { replaceText( getSelection(), event.getCommitted() ); } // Replace composed text imstart = getSelection().getStart(); StringBuilder composed = new StringBuilder(); for ( InputMethodTextRun run : event.getComposed() ) { composed.append( run.getText() ); } replaceText( getSelection(), composed.toString() ); imlength = composed.length(); if ( imlength != 0 ) { int pos = imstart; for ( InputMethodTextRun run : event.getComposed() ) { int endPos = pos + run.getText().length(); pos = endPos; } // Set caret position in composed text int caretPos = event.getCaretPosition(); if ( caretPos >= 0 && caretPos < imlength ) { selectRange( imstart + caretPos, imstart + caretPos ); } } } } private Node placeholder; private void displayPlaceHolder( boolean show, Node newNode ) { if ( placeholder != null && (! show || newNode != placeholder) ) { placeholder.layoutXProperty().unbind(); placeholder.layoutYProperty().unbind(); getChildren().remove( placeholder ); placeholder = null; setClip( null ); } if ( newNode != null && show && newNode != placeholder ) { configurePlaceholder( newNode ); getChildren().add( newNode ); placeholder = newNode; } } protected void configurePlaceholder( Node placeholder ) { placeholder.layoutYProperty().bind( Bindings.createDoubleBinding( () -> (getHeight() - placeholder.getLayoutBounds().getHeight()) / 2, heightProperty(), placeholder.layoutBoundsProperty() ) ); placeholder.layoutXProperty().bind( Bindings.createDoubleBinding( () -> (getWidth() - placeholder.getLayoutBounds().getWidth()) / 2, widthProperty(), placeholder.layoutBoundsProperty() ) ); } /* ********************************************************************** * * * * Queries * * * * Queries are parameterized observables. * * * * ********************************************************************** */ @Override public final double getViewportHeight() { return virtualFlow.getHeight(); } @Override public final Optional<Integer> allParToVisibleParIndex(int allParIndex) { if (allParIndex < 0) { throw new IllegalArgumentException("The given paragraph index (allParIndex) cannot be negative but was " + allParIndex); } if (allParIndex >= getParagraphs().size()) { throw new IllegalArgumentException(String.format( "Paragraphs' last index is [%s] but allParIndex was [%s]", getParagraphs().size() - 1, allParIndex) ); } List<Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>> visibleList = virtualFlow.visibleCells(); int firstVisibleParIndex = visibleList.get( 0 ).getNode().getIndex(); int targetIndex = allParIndex - firstVisibleParIndex; if ( allParIndex >= firstVisibleParIndex && targetIndex < visibleList.size() ) { if ( visibleList.get( targetIndex ).getNode().getIndex() == allParIndex ) { return Optional.of( targetIndex ); } } return Optional.empty(); } @Override public final int visibleParToAllParIndex(int visibleParIndex) { if (visibleParIndex < 0) { throw new IllegalArgumentException("Visible paragraph index cannot be negative but was " + visibleParIndex); } if (visibleParIndex >= getVisibleParagraphs().size()) { throw new IllegalArgumentException(String.format( "Visible paragraphs' last index is [%s] but visibleParIndex was [%s]", getVisibleParagraphs().size() - 1, visibleParIndex) ); } return virtualFlow.visibleCells().get( visibleParIndex ).getNode().getIndex(); } @Override public CharacterHit hit(double x, double y) { // mouse position used, so account for padding double adjustedX = x - getInsets().getLeft(); double adjustedY = y - getInsets().getTop(); VirtualFlowHit<Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>> hit = virtualFlow.hit(adjustedX, adjustedY); if(hit.isBeforeCells()) { return CharacterHit.insertionAt(0); } else if(hit.isAfterCells()) { return CharacterHit.insertionAt(getLength()); } else { int parIdx = hit.getCellIndex(); int parOffset = getParagraphOffset(parIdx); ParagraphBox<PS, SEG, S> cell = hit.getCell().getNode(); Point2D cellOffset = hit.getCellOffset(); CharacterHit parHit = cell.hit(cellOffset); return parHit.offset(parOffset); } } @Override public final int lineIndex(int paragraphIndex, int columnPosition) { Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = virtualFlow.getCell(paragraphIndex); return cell.getNode().getCurrentLineIndex(columnPosition); } @Override public int getParagraphLinesCount(int paragraphIndex) { return virtualFlow.getCell(paragraphIndex).getNode().getLineCount(); } @Override public Optional<Bounds> getCharacterBoundsOnScreen(int from, int to) { if (from < 0) { throw new IllegalArgumentException("From is negative: " + from); } if (from > to) { throw new IllegalArgumentException(String.format("From is greater than to. from=%s to=%s", from, to)); } if (to > getLength()) { throw new IllegalArgumentException(String.format("To is greater than area's length. length=%s, to=%s", getLength(), to)); } // no bounds exist if range is just a newline character if (getText(from, to).equals("\n")) { return Optional.empty(); } // if 'from' is the newline character at the end of a multi-line paragraph, it returns a Bounds that whose // minX & minY are the minX and minY of the paragraph itself, not the newline character. So, ignore it. int realFrom = getText(from, from + 1).equals("\n") ? from + 1 : from; Position startPosition = offsetToPosition(realFrom, Bias.Forward); int startRow = startPosition.getMajor(); Position endPosition = startPosition.offsetBy(to - realFrom, Bias.Forward); int endRow = endPosition.getMajor(); if (startRow == endRow) { return getRangeBoundsOnScreen(startRow, startPosition.getMinor(), endPosition.getMinor()); } else { Optional<Bounds> rangeBounds = getRangeBoundsOnScreen(startRow, startPosition.getMinor(), getParagraph(startRow).length()); for (int i = startRow + 1; i <= endRow; i++) { Optional<Bounds> nextLineBounds = getRangeBoundsOnScreen(i, 0, i == endRow ? endPosition.getMinor() : getParagraph(i).length() ); if (nextLineBounds.isPresent()) { if (rangeBounds.isPresent()) { Bounds lineBounds = nextLineBounds.get(); rangeBounds = rangeBounds.map(b -> { double minX = Math.min(b.getMinX(), lineBounds.getMinX()); double minY = Math.min(b.getMinY(), lineBounds.getMinY()); double maxX = Math.max(b.getMaxX(), lineBounds.getMaxX()); double maxY = Math.max(b.getMaxY(), lineBounds.getMaxY()); return new BoundingBox(minX, minY, maxX - minX, maxY - minY); }); } else { rangeBounds = nextLineBounds; } } } return rangeBounds; } } @Override public final String getText(int start, int end) { return content.getText(start, end); } @Override public String getText(int paragraph) { return content.getText(paragraph); } @Override public String getText(IndexRange range) { return content.getText(range); } @Override public StyledDocument<PS, SEG, S> subDocument(int start, int end) { return content.subSequence(start, end); } @Override public StyledDocument<PS, SEG, S> subDocument(int paragraphIndex) { return content.subDocument(paragraphIndex); } @Override public IndexRange getParagraphSelection(Selection selection, int paragraph) { int startPar = selection.getStartParagraphIndex(); int endPar = selection.getEndParagraphIndex(); if(selection.getLength() == 0 || paragraph < startPar || paragraph > endPar) { return EMPTY_RANGE; } int start = paragraph == startPar ? selection.getStartColumnPosition() : 0; int end = paragraph == endPar ? selection.getEndColumnPosition() : getParagraphLength(paragraph) + 1; // force rangeProperty() to be valid selection.getRange(); return new IndexRange(start, end); } @Override public S getStyleOfChar(int index) { return content.getStyleOfChar(index); } @Override public S getStyleAtPosition(int position) { return content.getStyleAtPosition(position); } @Override public IndexRange getStyleRangeAtPosition(int position) { return content.getStyleRangeAtPosition(position); } @Override public StyleSpans<S> getStyleSpans(int from, int to) { return content.getStyleSpans(from, to); } @Override public S getStyleOfChar(int paragraph, int index) { return content.getStyleOfChar(paragraph, index); } @Override public S getStyleAtPosition(int paragraph, int position) { return content.getStyleAtPosition(paragraph, position); } @Override public IndexRange getStyleRangeAtPosition(int paragraph, int position) { return content.getStyleRangeAtPosition(paragraph, position); } @Override public StyleSpans<S> getStyleSpans(int paragraph) { return content.getStyleSpans(paragraph); } @Override public StyleSpans<S> getStyleSpans(int paragraph, int from, int to) { return content.getStyleSpans(paragraph, from, to); } @Override public int getAbsolutePosition(int paragraphIndex, int columnIndex) { return content.getAbsolutePosition(paragraphIndex, columnIndex); } @Override public Position position(int row, int col) { return content.position(row, col); } @Override public Position offsetToPosition(int charOffset, Bias bias) { return content.offsetToPosition(charOffset, bias); } @Override public Bounds getVisibleParagraphBoundsOnScreen(int visibleParagraphIndex) { return getParagraphBoundsOnScreen(virtualFlow.visibleCells().get(visibleParagraphIndex)); } @Override public Optional<Bounds> getParagraphBoundsOnScreen(int paragraphIndex) { return virtualFlow.getCellIfVisible(paragraphIndex).map(this::getParagraphBoundsOnScreen); } @Override public final <T extends Node & Caret> Optional<Bounds> getCaretBoundsOnScreen(T caret) { return virtualFlow.getCellIfVisible(caret.getParagraphIndex()) .map(c -> c.getNode().getCaretBoundsOnScreen(caret)); } /* ********************************************************************** * * * * Actions * * * * Actions change the state of this control. They typically cause a * * change of one or more observables and/or produce an event. * * * * ********************************************************************** */ @Override public void scrollXToPixel(double pixel) { suspendVisibleParsWhile(() -> virtualFlow.scrollXToPixel(pixel)); } @Override public void scrollYToPixel(double pixel) { suspendVisibleParsWhile(() -> virtualFlow.scrollYToPixel(pixel)); } @Override public void scrollXBy(double deltaX) { suspendVisibleParsWhile(() -> virtualFlow.scrollXBy(deltaX)); } @Override public void scrollYBy(double deltaY) { suspendVisibleParsWhile(() -> virtualFlow.scrollYBy(deltaY)); } @Override public void scrollBy(Point2D deltas) { suspendVisibleParsWhile(() -> virtualFlow.scrollBy(deltas)); } @Override public void showParagraphInViewport(int paragraphIndex) { suspendVisibleParsWhile(() -> virtualFlow.show(paragraphIndex)); } @Override public void showParagraphAtTop(int paragraphIndex) { suspendVisibleParsWhile(() -> virtualFlow.showAsFirst(paragraphIndex)); } @Override public void showParagraphAtBottom(int paragraphIndex) { suspendVisibleParsWhile(() -> virtualFlow.showAsLast(paragraphIndex)); } @Override public void showParagraphRegion(int paragraphIndex, Bounds region) { suspendVisibleParsWhile(() -> virtualFlow.show(paragraphIndex, region)); } @Override public void requestFollowCaret() { followCaretRequested = true; requestLayout(); } @Override public void lineStart(SelectionPolicy policy) { moveTo(getCurrentParagraph(), getCurrentLineStartInParargraph(), policy); } @Override public void lineEnd(SelectionPolicy policy) { moveTo(getCurrentParagraph(), getCurrentLineEndInParargraph(), policy); } public int getCurrentLineStartInParargraph() { return virtualFlow.getCell(getCurrentParagraph()).getNode().getCurrentLineStartPosition(caretSelectionBind.getUnderlyingCaret()); } public int getCurrentLineEndInParargraph() { return virtualFlow.getCell(getCurrentParagraph()).getNode().getCurrentLineEndPosition(caretSelectionBind.getUnderlyingCaret()); } private double caretPrevY = -1; private LineSelection<PS, SEG, S> lineHighlighter; private ObjectProperty<Paint> lineHighlighterFill; /** * The default fill is "highlighter" yellow. It can also be styled using CSS with:<br> * <code>.styled-text-area .line-highlighter { -fx-fill: lime; }</code><br> * CSS selectors from Path, Shape, and Node can also be used. */ public void setLineHighlighterFill( Paint highlight ) { if ( lineHighlighterFill != null && highlight != null ) { lineHighlighterFill.set( highlight ); } else { boolean lineHighlightOn = isLineHighlighterOn(); if ( lineHighlightOn ) setLineHighlighterOn( false ); if ( highlight == null ) lineHighlighterFill = null; else lineHighlighterFill = new SimpleObjectProperty( highlight ); if ( lineHighlightOn ) setLineHighlighterOn( true ); } } public boolean isLineHighlighterOn() { return lineHighlighter != null && selectionSet.contains( lineHighlighter ) ; } /** * Highlights the line that the main caret is on.<br> * Line highlighting automatically follows the caret. */ public void setLineHighlighterOn( boolean show ) { if ( show ) { if ( lineHighlighter != null ) return; lineHighlighter = new LineSelection<>( this, lineHighlighterFill ); Consumer<Bounds> caretListener = b -> { if ( lineHighlighter != null && (b.getMinY() != caretPrevY || getCaretColumn() == 1) ) { lineHighlighter.selectCurrentLine(); caretPrevY = b.getMinY(); } }; caretBoundsProperty().addListener( (ob,ov,nv) -> nv.ifPresent( caretListener ) ); getCaretBounds().ifPresent( caretListener ); selectionSet.add( lineHighlighter ); } else if ( lineHighlighter != null ) { selectionSet.remove( lineHighlighter ); lineHighlighter.deselect(); lineHighlighter = null; caretPrevY = -1; } } @Override public void prevPage(SelectionPolicy selectionPolicy) { // Paging up and we're in the first frame then move/select to start. if ( firstVisibleParToAllParIndex() == 0 ) { caretSelectionBind.moveTo( 0, selectionPolicy ); } else page( -1, selectionPolicy ); } @Override public void nextPage(SelectionPolicy selectionPolicy) { // Paging down and we're in the last frame then move/select to end. if ( lastVisibleParToAllParIndex() == getParagraphs().size()-1 ) { caretSelectionBind.moveTo( getLength(), selectionPolicy ); } else page( +1, selectionPolicy ); } /** * @param pgCount the number of pages to page up/down. * <br>Negative numbers for paging up and positive for down. */ private void page(int pgCount, SelectionPolicy selectionPolicy) { // Use underlying caret to get the same behaviour as navigating up/down a line where the x position is sticky Optional<Bounds> cb = caretSelectionBind.getUnderlyingCaret().getCaretBounds(); paging = true; // Prevent scroll from reverting back to the current caret position scrollYBy( pgCount * getViewportHeight() ); cb.map( this::screenToLocal ) // Place caret near the same on screen position as before .map( b -> hit( b.getMinX(), b.getMinY()+b.getHeight()/2.0 ).getInsertionIndex() ) .ifPresent( i -> caretSelectionBind.moveTo( i, selectionPolicy ) ); // Adjust scroll by a few pixels to get the caret at the exact on screen location as before cb.ifPresent( prev -> getCaretBounds().map( newB -> newB.getMinY() - prev.getMinY() ) .filter( delta -> delta != 0.0 ).ifPresent( delta -> scrollYBy( delta ) ) ); } @Override public void displaceCaret(int pos) { caretSelectionBind.displaceCaret(pos); } @Override public void setStyle(int from, int to, S style) { content.setStyle(from, to, style); } @Override public void setStyle(int paragraph, S style) { content.setStyle(paragraph, style); } @Override public void setStyle(int paragraph, int from, int to, S style) { content.setStyle(paragraph, from, to, style); } @Override public void setStyleSpans(int from, StyleSpans<? extends S> styleSpans) { content.setStyleSpans(from, styleSpans); } @Override public void setStyleSpans(int paragraph, int from, StyleSpans<? extends S> styleSpans) { content.setStyleSpans(paragraph, from, styleSpans); } @Override public void setParagraphStyle(int paragraph, PS paragraphStyle) { content.setParagraphStyle(paragraph, paragraphStyle); } /** * If you want to preset the style to be used for inserted text. Note that useInitialStyleForInsertion overrides this if true. */ public final void setTextInsertionStyle( S txtStyle ) { insertionTextStyle = txtStyle; } public final S getTextInsertionStyle() { return insertionTextStyle; } private S insertionTextStyle; @Override public final S getTextStyleForInsertionAt(int pos) { if ( insertionTextStyle != null ) { return insertionTextStyle; } else if ( useInitialStyleForInsertion.get() ) { return initialTextStyle; } else { return content.getStyleAtPosition(pos); } } private PS insertionParagraphStyle; /** * If you want to preset the style to be used. Note that useInitialStyleForInsertion overrides this if true. */ public final void setParagraphInsertionStyle( PS paraStyle ) { insertionParagraphStyle = paraStyle; } public final PS getParagraphInsertionStyle() { return insertionParagraphStyle; } @Override public final PS getParagraphStyleForInsertionAt(int pos) { if ( insertionParagraphStyle != null ) { return insertionParagraphStyle; } else if ( useInitialStyleForInsertion.get() ) { return initialParagraphStyle; } else { return content.getParagraphStyleAtPosition(pos); } } @Override public void replaceText(int start, int end, String text) { StyledDocument<PS, SEG, S> doc = ReadOnlyStyledDocument.fromString( text, getParagraphStyleForInsertionAt(start), getTextStyleForInsertionAt(start), segmentOps ); replace(start, end, doc); } @Override public void replace(int start, int end, SEG seg, S style) { StyledDocument<PS, SEG, S> doc = ReadOnlyStyledDocument.fromSegment( seg, getParagraphStyleForInsertionAt(start), style, segmentOps ); replace(start, end, doc); } @Override public void replace(int start, int end, StyledDocument<PS, SEG, S> replacement) { content.replace(start, end, replacement); int newCaretPos = start + replacement.length(); selectRange(newCaretPos, newCaretPos); } void replaceMulti(List<Replacement<PS, SEG, S>> replacements) { content.replaceMulti(replacements); // don't update selection as this is not the main method through which the area is updated // leave that up to the developer using it to determine what to do } @Override public MultiChangeBuilder<PS, SEG, S> createMultiChange() { return new MultiChangeBuilder<>(this); } @Override public MultiChangeBuilder<PS, SEG, S> createMultiChange(int initialNumOfChanges) { return new MultiChangeBuilder<>(this, initialNumOfChanges); } /** * Convenience method to fold (hide/collapse) the currently selected paragraphs, * into (i.e. excluding) the first paragraph of the range. * * @param styleMixin Given a paragraph style PS, return a <b>new</b> PS that will activate folding. * * <p>See {@link #fold(int, int, UnaryOperator)} for more info.</p> */ protected void foldSelectedParagraphs( UnaryOperator<PS> styleMixin ) { IndexRange range = getSelection(); fold( range.getStart(), range.getEnd(), styleMixin ); } /** * Folds (hides/collapses) paragraphs from <code>start</code> to <code> * end</code>, into (i.e. excluding) the first paragraph of the range. * * @param styleMixin Given a paragraph style PS, return a <b>new</b> PS that will activate folding. * * <p>See {@link #fold(int, int, UnaryOperator)} for more info.</p> */ protected void foldParagraphs( int start, int end, UnaryOperator<PS> styleMixin ) { start = getAbsolutePosition( start, 0 ); end = getAbsolutePosition( end, getParagraphLength( end ) ); fold( start, end, styleMixin ); } /** * Folds (hides/collapses) paragraphs from character position <code>startPos</code> * to <code>endPos</code>, into (i.e. excluding) the first paragraph of the range. * * <p>Folding is achieved with the help of paragraph styling, which is applied to the paragraph's * TextFlow object through the applyParagraphStyle BiConsumer (supplied in the constructor to * GenericStyledArea). When applyParagraphStyle is to apply fold styling it just needs to set * the TextFlow's visibility to collapsed for it to be folded. See {@code InlineCssTextArea}, * {@code StyleClassedTextArea}, and {@code RichTextDemo} for different ways of doing this. * Also read the GitHub Wiki.</p> * * <p>The UnaryOperator <code>styleMixin</code> must return a * different paragraph style Object to what was submitted.</p> * * @param styleMixin Given a paragraph style PS, return a <b>new</b> PS that will activate folding. */ protected void fold( int startPos, int endPos, UnaryOperator<PS> styleMixin ) { ReadOnlyStyledDocument<PS, SEG, S> subDoc; UnaryOperator<Paragraph<PS, SEG, S>> mapper; subDoc = (ReadOnlyStyledDocument<PS, SEG, S>) subDocument( startPos, endPos ); mapper = p -> p.setParagraphStyle( styleMixin.apply( p.getParagraphStyle() ) ); for ( int p = 1; p < subDoc.getParagraphCount(); p++ ) { subDoc = subDoc.replaceParagraph( p, mapper ).get1(); } replace( startPos, endPos, subDoc ); recreateParagraphGraphic( offsetToPosition( startPos, Bias.Backward ).getMajor() ); moveTo( startPos ); } private void skipOverFoldedParagraphs( ObservableValue<? extends Integer> ob, Integer prevParagraph, Integer newParagraph ) { if ( getCell( newParagraph ).isFolded() ) { // Prevent Ctrl+A and Ctrl+End breaking when the last paragraph is folded // github.com/FXMisc/RichTextFX/pull/965#issuecomment-706268116 if ( newParagraph == getParagraphs().size() - 1 ) return; int skip = (newParagraph - prevParagraph > 0) ? +1 : -1; int p = newParagraph + skip; while ( p > 0 && p < getParagraphs().size() ) { if ( getCell( p ).isFolded() ) p += skip; else break; } if ( p < 0 || p == getParagraphs().size() ) p = prevParagraph; int col = Math.min( getCaretColumn(), getParagraphLength( p ) ); if ( getSelection().getLength() == 0 ) moveTo( p, col ); else moveTo( p, col, SelectionPolicy.EXTEND ); } } /** * Unfolds paragraphs <code>startingFrom</code> onwards for the currently folded block. * * <p>The UnaryOperator <code>styleMixin</code> must return a * different paragraph style Object to what was submitted.</p> * * @param isFolded Given a paragraph style PS check if it's folded. * @param styleMixin Given a paragraph style PS, return a <b>new</b> PS that excludes fold styling. */ protected void unfoldParagraphs( int startingFrom, Predicate<PS> isFolded, UnaryOperator<PS> styleMixin ) { LiveList<Paragraph<PS, SEG, S>> pList = getParagraphs(); int to = startingFrom; while ( ++to < pList.size() ) { if ( ! isFolded.test( pList.get( to ).getParagraphStyle() ) ) break; } if ( --to > startingFrom ) { ReadOnlyStyledDocument<PS, SEG, S> subDoc; UnaryOperator<Paragraph<PS, SEG, S>> mapper; int startPos = getAbsolutePosition( startingFrom, 0 ); int endPos = getAbsolutePosition( to, getParagraphLength( to ) ); subDoc = (ReadOnlyStyledDocument<PS, SEG, S>) subDocument( startPos, endPos ); mapper = p -> p.setParagraphStyle( styleMixin.apply( p.getParagraphStyle() ) ); for ( int p = 1; p < subDoc.getParagraphCount(); p++ ) { subDoc = subDoc.replaceParagraph( p, mapper ).get1(); } replace( startPos, endPos, subDoc ); moveTo( startingFrom, getParagraphLength( startingFrom ) ); recreateParagraphGraphic( startingFrom ); } } /* ********************************************************************** * * * * Public API * * * * ********************************************************************** */ @Override public void dispose() { if (undoManager != null) { undoManager.close(); } subscriptions.unsubscribe(); virtualFlow.dispose(); } /* ********************************************************************** * * * * Layout * * * * ********************************************************************** */ private BooleanProperty autoHeightProp = new SimpleBooleanProperty(); public BooleanProperty autoHeightProperty() { return autoHeightProp; } public void setAutoHeight( boolean value ) { autoHeightProp.set( value ); } public boolean isAutoHeight() { return autoHeightProp.get(); } @Override protected double computePrefHeight( double width ) { if ( autoHeightProp.get() ) { if ( getWidth() == 0.0 ) Platform.runLater( () -> requestLayout() ); else { double height = 0.0; Insets in = getInsets(); for ( int p = 0; p < getParagraphs().size(); p++ ) { height += getCell( p ).getHeight(); } if ( height > 0.0 ) { return height + in.getTop() + in.getBottom(); } } } return super.computePrefHeight( width ); } @Override protected void layoutChildren() { Insets ins = getInsets(); visibleParagraphs.suspendWhile(() -> { virtualFlow.resizeRelocate( ins.getLeft(), ins.getTop(), getWidth() - ins.getLeft() - ins.getRight(), getHeight() - ins.getTop() - ins.getBottom()); if(followCaretRequested && ! paging) { try (Guard g = viewportDirty.suspend()) { followCaret(); } } followCaretRequested = false; paging = false; }); Node holder = placeholder; if (holder != null && holder.isResizable() && holder.isManaged()) { holder.autosize(); } } /* ********************************************************************** * * * * Package-Private methods * * * * ********************************************************************** */ /** * Returns the current line as a two-level index. * The major number is the paragraph index, the minor * number is the line number within the paragraph. * * <p>This method has a side-effect of bringing the current * paragraph to the viewport if it is not already visible. */ TwoDimensional.Position currentLine() { int parIdx = getCurrentParagraph(); Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = virtualFlow.getCell(parIdx); int lineIdx = cell.getNode().getCurrentLineIndex(caretSelectionBind.getUnderlyingCaret()); return paragraphLineNavigator.position(parIdx, lineIdx); } void showCaretAtBottom() { int parIdx = getCurrentParagraph(); Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = virtualFlow.getCell(parIdx); Bounds caretBounds = cell.getNode().getCaretBounds(caretSelectionBind.getUnderlyingCaret()); double y = caretBounds.getMaxY(); suspendVisibleParsWhile(() -> virtualFlow.showAtOffset(parIdx, getViewportHeight() - y)); } void showCaretAtTop() { int parIdx = getCurrentParagraph(); Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = virtualFlow.getCell(parIdx); Bounds caretBounds = cell.getNode().getCaretBounds(caretSelectionBind.getUnderlyingCaret()); double y = caretBounds.getMinY(); suspendVisibleParsWhile(() -> virtualFlow.showAtOffset(parIdx, -y)); } /** * Returns x coordinate of the caret in the current paragraph. */ final ParagraphBox.CaretOffsetX getCaretOffsetX(CaretNode caret) { return getCell(caret.getParagraphIndex()).getCaretOffsetX(caret); } CharacterHit hit(ParagraphBox.CaretOffsetX x, TwoDimensional.Position targetLine) { int parIdx = targetLine.getMajor(); ParagraphBox<PS, SEG, S> cell = virtualFlow.getCell(parIdx).getNode(); CharacterHit parHit = cell.hitTextLine(x, targetLine.getMinor()); return parHit.offset(getParagraphOffset(parIdx)); } CharacterHit hit(ParagraphBox.CaretOffsetX x, double y) { // don't account for padding here since height of virtualFlow is used, not area + potential padding VirtualFlowHit<Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>> hit = virtualFlow.hit(0.0, y); if(hit.isBeforeCells()) { return CharacterHit.insertionAt(0); } else if(hit.isAfterCells()) { return CharacterHit.insertionAt(getLength()); } else { int parIdx = hit.getCellIndex(); int parOffset = getParagraphOffset(parIdx); ParagraphBox<PS, SEG, S> cell = hit.getCell().getNode(); Point2D cellOffset = hit.getCellOffset(); CharacterHit parHit = cell.hitText(x, cellOffset.getY()); return parHit.offset(parOffset); } } final Optional<Bounds> getSelectionBoundsOnScreen(Selection<PS, SEG, S> selection) { if (selection.getLength() == 0) { return Optional.empty(); } List<Bounds> bounds = new ArrayList<>(selection.getParagraphSpan()); for (int i = selection.getStartParagraphIndex(); i <= selection.getEndParagraphIndex(); i++) { virtualFlow.getCellIfVisible(i) .ifPresent(c -> c.getNode() .getSelectionBoundsOnScreen(selection) .ifPresent(bounds::add) ); } if(bounds.size() == 0) { return Optional.empty(); } double minX = bounds.stream().mapToDouble(Bounds::getMinX).min().getAsDouble(); double maxX = bounds.stream().mapToDouble(Bounds::getMaxX).max().getAsDouble(); double minY = bounds.stream().mapToDouble(Bounds::getMinY).min().getAsDouble(); double maxY = bounds.stream().mapToDouble(Bounds::getMaxY).max().getAsDouble(); return Optional.of(new BoundingBox(minX, minY, maxX-minX, maxY-minY)); } void clearTargetCaretOffset() { caretSelectionBind.clearTargetOffset(); } ParagraphBox.CaretOffsetX getTargetCaretOffset() { return caretSelectionBind.getTargetOffset(); } /* ********************************************************************** * * * * Private methods * * * * ********************************************************************** */ private Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> createCell( Paragraph<PS, SEG, S> paragraph, BiConsumer<TextFlow, PS> applyParagraphStyle, Function<StyledSegment<SEG, S>, Node> nodeFactory) { ParagraphBox<PS, SEG, S> box = new ParagraphBox<>(paragraph, applyParagraphStyle, nodeFactory); box.highlightTextFillProperty().bind(highlightTextFill); box.wrapTextProperty().bind(wrapTextProperty()); box.graphicFactoryProperty().bind(paragraphGraphicFactoryProperty()); box.graphicOffset.bind(virtualFlow.breadthOffsetProperty()); EventStream<Integer> boxIndexValues = box.indexProperty().values().filter(i -> i != -1); Subscription firstParPseudoClass = boxIndexValues.subscribe(idx -> box.pseudoClassStateChanged(FIRST_PAR, idx == 0)); Subscription lastParPseudoClass = EventStreams.combine( boxIndexValues, getParagraphs().sizeProperty().values() ).subscribe(in -> in.exec((i, n) -> box.pseudoClassStateChanged(LAST_PAR, i == n-1))); // set up caret Function<CaretNode, Subscription> subscribeToCaret = caret -> { EventStream<Integer> caretIndexStream = EventStreams.nonNullValuesOf(caret.paragraphIndexProperty()); // a new event stream needs to be created for each caret added, so that it will immediately // fire the box's current index value as an event, thereby running the code in the subscribe block // Reusing boxIndexValues will not fire its most recent event, leading to a caret not being added // Thus, we'll call the new event stream "fresh" box index values EventStream<Integer> freshBoxIndexValues = box.indexProperty().values().filter(i -> i != -1); return EventStreams.combine(caretIndexStream, freshBoxIndexValues) .subscribe(t -> { int caretParagraphIndex = t.get1(); int boxIndex = t.get2(); if (caretParagraphIndex == boxIndex) { box.caretsProperty().add(caret); } else { box.caretsProperty().remove(caret); } }); }; Subscription caretSubscription = caretSet.addSubscriber(subscribeToCaret); // TODO: how should 'hasCaret' be handled now? Subscription hasCaretPseudoClass = EventStreams .combine(boxIndexValues, Val.wrap(currentParagraphProperty()).values()) // box index (t1) == caret paragraph index (t2) .map(t -> t.get1().equals(t.get2())) .subscribe(value -> box.pseudoClassStateChanged(HAS_CARET, value)); Function<Selection<PS, SEG, S>, Subscription> subscribeToSelection = selection -> { EventStream<Integer> startParagraphValues = EventStreams.nonNullValuesOf(selection.startParagraphIndexProperty()); EventStream<Integer> endParagraphValues = EventStreams.nonNullValuesOf(selection.endParagraphIndexProperty()); // see comment in caret section about why a new box index EventStream is needed EventStream<Integer> freshBoxIndexValues = box.indexProperty().values().filter(i -> i != -1); return EventStreams.combine(startParagraphValues, endParagraphValues, freshBoxIndexValues) .subscribe(t -> { int startPar = t.get1(); int endPar = t.get2(); int boxIndex = t.get3(); if (startPar <= boxIndex && boxIndex <= endPar) { // So that we don't add multiple paths for the same selection, // which leads to not removing the additional paths when selection is removed, // this is a `Map#putIfAbsent(Key, Value)` implementation that creates the path lazily SelectionPath p = box.selectionsProperty().get(selection); if (p == null) { // create & configure path Val<IndexRange> range = Val.create( () -> box.getIndex() != -1 ? getParagraphSelection(selection, box.getIndex()) : EMPTY_RANGE, selection.rangeProperty() ); SelectionPath path = new SelectionPath(range); path.getStyleClass().add( selection.getSelectionName() ); selection.configureSelectionPath(path); box.selectionsProperty().put(selection, path); } } else { box.selectionsProperty().remove(selection); } }); }; Subscription selectionSubscription = selectionSet.addSubscriber(subscribeToSelection); return new Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>() { @Override public ParagraphBox<PS, SEG, S> getNode() { return box; } @Override public void updateIndex(int index) { box.setIndex(index); } @Override public void dispose() { box.highlightTextFillProperty().unbind(); box.wrapTextProperty().unbind(); box.graphicFactoryProperty().unbind(); box.graphicOffset.unbind(); box.dispose(); firstParPseudoClass.unsubscribe(); lastParPseudoClass.unsubscribe(); caretSubscription.unsubscribe(); hasCaretPseudoClass.unsubscribe(); selectionSubscription.unsubscribe(); } }; } /** Assumes this method is called within a {@link #suspendVisibleParsWhile(Runnable)} block */ private void followCaret() { int parIdx = getCurrentParagraph(); Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = virtualFlow.getCell(parIdx); Bounds caretBounds = caretSelectionBind.getUnderlyingCaret().getLayoutBounds(); double graphicWidth = cell.getNode().getGraphicPrefWidth(); Bounds region = extendLeft(caretBounds, graphicWidth); double scrollX = virtualFlow.getEstimatedScrollX(); // Ordinarily when a caret ends a selection in the target paragraph and scrolling left is required to follow // the caret then the selection won't be visible. So here we check for this scenario and adjust if needed. if ( ! isWrapText() && scrollX > 0.0 && getParagraphSelection( parIdx ).getLength() > 0 ) { double visibleLeftX = cell.getNode().getWidth() * scrollX / 100 - getWidth() + graphicWidth; CaretNode selectionStart = new CaretNode( "", this, getSelection().getStart() ); cell.getNode().caretsProperty().add( selectionStart ); Bounds startBounds = cell.getNode().getCaretBounds( selectionStart ); cell.getNode().caretsProperty().remove( selectionStart ); if ( startBounds.getMinX() - graphicWidth < visibleLeftX ) { region = extendLeft( startBounds, graphicWidth ); } } // Addresses https://github.com/FXMisc/RichTextFX/issues/937#issuecomment-674319602 if ( parIdx == getParagraphs().size()-1 && cell.getNode().getLineCount() == 1 ) { region = new BoundingBox // Correcting the region's height ( region.getMinX(), region.getMinY(), region.getWidth(), cell.getNode().getLayoutBounds().getHeight() ); } virtualFlow.show(parIdx, region); } private ParagraphBox<PS, SEG, S> getCell(int index) { return virtualFlow.getCell(index).getNode(); } private EventStream<MouseOverTextEvent> mouseOverTextEvents(ObservableSet<ParagraphBox<PS, SEG, S>> cells, Duration delay) { return merge(cells, c -> c.stationaryIndices(delay).map(e -> e.unify( l -> l.map((pos, charIdx) -> MouseOverTextEvent.beginAt(c.localToScreen(pos), getParagraphOffset(c.getIndex()) + charIdx)), r -> MouseOverTextEvent.end()))); } private int getParagraphOffset(int parIdx) { return position(parIdx, 0).toOffset(); } private Bounds getParagraphBoundsOnScreen(Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell) { Bounds nodeLocal = cell.getNode().getBoundsInLocal(); Bounds nodeScreen = cell.getNode().localToScreen(nodeLocal); Bounds areaLocal = getBoundsInLocal(); Bounds areaScreen = localToScreen(areaLocal); // use area's minX if scrolled right and paragraph's left is not visible double minX = nodeScreen.getMinX() < areaScreen.getMinX() ? areaScreen.getMinX() : nodeScreen.getMinX(); // use area's minY if scrolled down vertically and paragraph's top is not visible double minY = nodeScreen.getMinY() < areaScreen.getMinY() ? areaScreen.getMinY() : nodeScreen.getMinY(); // use area's width whether paragraph spans outside of it or not // so that short or long paragraph takes up the entire space double width = areaScreen.getWidth(); // use area's maxY if scrolled up vertically and paragraph's bottom is not visible double maxY = nodeScreen.getMaxY() < areaScreen.getMaxY() ? nodeScreen.getMaxY() : areaScreen.getMaxY(); return new BoundingBox(minX, minY, width, maxY - minY); } private Optional<Bounds> getRangeBoundsOnScreen(int paragraphIndex, int from, int to) { return virtualFlow.getCellIfVisible(paragraphIndex) .map(c -> c.getNode().getRangeBoundsOnScreen(from, to)); } private void manageSubscription(Subscription subscription) { subscriptions = subscriptions.and(subscription); } private static Bounds extendLeft(Bounds b, double w) { if(w == 0) { return b; } else { return new BoundingBox( b.getMinX() - w, b.getMinY(), b.getWidth() + w, b.getHeight()); } } private void suspendVisibleParsWhile(Runnable runnable) { Suspendable.combine(beingUpdated, visibleParagraphs).suspendWhile(runnable); } /* ********************************************************************** * * * * CSS * * * * ********************************************************************** */ private static final CssMetaData<GenericStyledArea<?, ?, ?>, Paint> HIGHLIGHT_TEXT_FILL = new CustomCssMetaData<>( "-fx-highlight-text-fill", StyleConverter.getPaintConverter(), Color.WHITE, s -> s.highlightTextFill ); private static final List<CssMetaData<? extends Styleable, ?>> CSS_META_DATA_LIST; static { List<CssMetaData<? extends Styleable, ?>> styleables = new ArrayList<>(Region.getClassCssMetaData()); styleables.add(HIGHLIGHT_TEXT_FILL); CSS_META_DATA_LIST = Collections.unmodifiableList(styleables); } @Override public List<CssMetaData<? extends Styleable, ?>> getCssMetaData() { return CSS_META_DATA_LIST; } public static List<CssMetaData<? extends Styleable, ?>> getClassCssMetaData() { return CSS_META_DATA_LIST; } }
Updated visibleParToAllParIndex (#1002)
richtextfx/src/main/java/org/fxmisc/richtext/GenericStyledArea.java
Updated visibleParToAllParIndex (#1002)
<ide><path>ichtextfx/src/main/java/org/fxmisc/richtext/GenericStyledArea.java <ide> getVisibleParagraphs().size() - 1, visibleParIndex) <ide> ); <ide> } <del> return virtualFlow.visibleCells().get( visibleParIndex ).getNode().getIndex(); <add> <add> Cell<Paragraph<PS,SEG,S>, ParagraphBox<PS,SEG,S>> visibleCell = null; <add> <add> if ( visibleParIndex > 0 ) visibleCell = virtualFlow.visibleCells().get( visibleParIndex ); <add> else visibleCell = virtualFlow.getCellIfVisible( virtualFlow.getFirstVisibleIndex() ) <add> .orElseGet( () -> virtualFlow.visibleCells().get( visibleParIndex ) ); <add> <add> return visibleCell.getNode().getIndex(); <ide> } <ide> <ide> @Override
Java
apache-2.0
5b863882f2efe2658d8486ca901c895afaa760ed
0
bertilmuth/requirementsascode
package org.requirementsascode; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; import org.requirementsascode.exception.MissingUseCaseStepPart; import org.requirementsascode.exception.MoreThanOneStepCanReact; import org.requirementsascode.exception.UnhandledException; import org.requirementsascode.predicate.After; /** * A use case model runner is a highly configurable use case controller that receives events from * the frontend and conditionally calls methods on the backend. * * <p>In requirementsascode, a use case model runner is the only way the frontend communicates with * the backend. It is configured by the use case model it owns. Each real user needs an instance of * a runner, as the runner determines the journey of the user through the use cases. */ public class UseCaseModelRunner implements Serializable{ private static final long serialVersionUID = 1787451244764017381L; private Optional<Actor> user; private List<Actor> userAndSystem; private UseCaseModel useCaseModel; private Step latestStep; private boolean isRunning; private SystemReactionTrigger systemReactionTrigger; private Consumer<SystemReactionTrigger> systemReaction; private Predicate<Step> stepWithoutAlternativePredicate; private LinkedList<UseCase> includedUseCases; private LinkedList<Step> includeSteps; private UseCase includedUseCase; private Optional<Step> optionalIncludeStep; /** * Constructor for creating a runner with standard system reaction, that is: the system reaction, * as defined in the use case step, simply accepts an event. */ public UseCaseModelRunner() { this.user = Optional.empty(); this.systemReactionTrigger = new SystemReactionTrigger(); adaptSystemReaction(systemReactionTrigger -> systemReactionTrigger.trigger()); restart(); } /** * Adapt the system reaction to perform tasks before and/or after triggering the system reaction. * This is useful for cross-cutting concerns, e.g. measuring performance. * * @param adaptedSystemReaction the system reaction to replace the standard system reaction. */ public void adaptSystemReaction(Consumer<SystemReactionTrigger> adaptedSystemReaction) { this.systemReaction = adaptedSystemReaction; } /** * Restarts the runner, resetting it to its original defaults ("no flow has * been run, no step has been run, no use case included"). */ public void restart() { setLatestStep(null); includedUseCases = new LinkedList<>(); includeSteps = new LinkedList<>(); includedUseCase = null; optionalIncludeStep = Optional.empty(); } /** * Configures the runner to use the specified use case model. After you called this method, the * runner will accept events via {@link #reactTo(Object)}. * * <p>As a side effect, this method immediately triggers "autonomous system reactions". * * @param useCaseModel the model that defines the runner's behavior */ public void run(UseCaseModel useCaseModel) { this.useCaseModel = useCaseModel; this.userAndSystem = userAndSystem(user.orElse(useCaseModel.getUserActor())); this.isRunning = true; triggerAutonomousSystemReaction(); } private void triggerAutonomousSystemReaction() { reactTo(this); } private List<Actor> userAndSystem(Actor userActor) { return Arrays.asList(userActor, userActor.getUseCaseModel().getSystemActor()); } /** * After you called this method, the runner will only react to steps that have explicitly set the * specified actor as one of its actors, or that are declared as "autonomous system reactions". * * <p>As a side effect, calling this method triggers immediately triggers "autonomous system * reactions". * * @param actor the actor to run as * @return this runner, for method chaining with {@link #run(UseCaseModel)} */ public UseCaseModelRunner as(Actor actor) { Objects.requireNonNull(actor); this.user = Optional.of(actor); this.userAndSystem = userAndSystem(user.get()); return this; } /** * Returns whether the runner is currently running. * * @see #run(UseCaseModel) * @return true if the runner is running, false otherwise. */ public boolean isRunning() { return isRunning; } /** * Stops the runner. It will not be reacting to events, until {@link #run(UseCaseModel)} is called * again. */ public void stop() { isRunning = false; } /** * Call this method from the frontend to provide several event objects to the runner. For each * event object, {@link #reactTo(Object)} is called. * * @param events the events to react to */ public void reactTo(Object... events) { Objects.requireNonNull(events); for (Object event : events) { reactTo(event); } } /** * Call this method from the frontend to provide an event object to the runner. * * <p>If it is running, the runner will then check which steps can react to the event. If a single * step can react, the runner will trigger the system reaction for that step. If no step can * react, the runner will NOT trigger any system reaction. If more than one step can react, the * runner will throw an exception. * * <p>After that, the runner will trigger "autonomous system reactions". * * <p>See {@link #getStepsThatCanReactTo(Class)} for a description of what "can react" means. * * @param <T> the type of the event object * @param event the event object provided by the frontend * @return the use case step whose system reaction was triggered, or else an empty optional if * none was triggered. * @throws MoreThanOneStepCanReact if more than one step can react * @throws UnhandledException if no step can react, and the event is an (in)direct subclass of * Throwable. */ public <T> Optional<Step> reactTo(T event) { Objects.requireNonNull(event); Optional<Step> latestStepRun = Optional.empty(); if (isRunning) { Class<? extends Object> currentEventClass = event.getClass(); Set<Step> stepsThatCanReact = getStepsThatCanReactTo(currentEventClass); latestStepRun = triggerSystemReactionForSteps(event, stepsThatCanReact); } return latestStepRun; } private <T> Optional<Step> triggerSystemReactionForSteps(T event, Collection<Step> steps) { Step useCaseStep = null; if (steps.size() == 1) { useCaseStep = steps.iterator().next(); triggerSystemReactionForStep(event, useCaseStep); } else if (steps.size() > 1) { throw new MoreThanOneStepCanReact(steps); } else if (event instanceof Throwable) { throw new UnhandledException((Throwable) event); } return useCaseStep != null ? Optional.of(useCaseStep) : Optional.empty(); } private <T> Step triggerSystemReactionForStep(T event, Step step) { if (step.getSystemReaction() == null) { throw new MissingUseCaseStepPart(step, "system"); } setLatestStep(step); setStepWithoutAlternativePredicate(null); systemReactionTrigger.setupWith(event, step); try { systemReaction.accept(systemReactionTrigger); } catch (Exception e) { handleException(e); } continueAfterIncludeStepWhenEndOfIncludedFlowIsReached(); triggerAutonomousSystemReaction(); return step; } private void continueAfterIncludeStepWhenEndOfIncludedFlowIsReached() { if (includedUseCase != null && optionalIncludeStep.isPresent() && isAtEndOfIncludedFlow()) { setLatestStep(optionalIncludeStep.get()); includedUseCase = getUseCaseIncludedBefore(); optionalIncludeStep = getIncludeStepBefore(); } } private UseCase getUseCaseIncludedBefore(){ includedUseCases.pop(); UseCase includedUseCase = includedUseCases.peek(); return includedUseCase; } private Optional<Step> getIncludeStepBefore(){ includeSteps.pop(); Step includeStep = includeSteps.peek(); return includeStep != null? Optional.of(includeStep) : Optional.empty(); } /** * Returns whether at least one step can react to an event of the specified class. * * @see #getStepsThatCanReactTo(Class) * @param eventClass the specified class * @return true if the runner is running and at least one step can react, false otherwise */ public boolean canReactTo(Class<? extends Object> eventClass) { boolean canReact = getStepsThatCanReactTo(eventClass).size() > 0; return canReact; } /** * Returns the use case steps in the use case model that can react to the specified event class. * * <p>A step "can react" if all of the following conditions are met: a) the runner is running b) * one of the step's actors matches the actor the runner is run as c) the step's event class is * the same or a superclass of the specified event class d) the step has a predicate that is true * * @param eventClass the class of events * @return the steps that can react to the class of events */ public Set<Step> getStepsThatCanReactTo(Class<? extends Object> eventClass) { Objects.requireNonNull(eventClass); Set<Step> stepsThatCanReact; if (isRunning) { Stream<Step> stepStream = useCaseModel.getModifiableSteps().stream(); stepsThatCanReact = stepsInStreamThatCanReactTo(eventClass, stepStream); } else { stepsThatCanReact = new HashSet<>(); } return stepsThatCanReact; } /** * Gets the steps that can react from the specified stream, rather than from the whole use case * model. * * @see #getStepsThatCanReactTo(Class) * @param eventClass eventClass the class of events * @param stepStream the stream of steps * @return the subset of steps that can react to the class of events */ Set<Step> stepsInStreamThatCanReactTo( Class<? extends Object> eventClass, Stream<Step> stepStream) { Set<Step> steps; steps = stepStream .filter(step -> stepActorIsRunActor(step)) .filter(step -> stepEventClassIsSameOrSuperclassAsEventClass(step, eventClass)) .filter(step -> hasTruePredicate(step)) .filter(step -> isStepInIncludedUseCaseIfPresent(step)) .filter(getStepWithoutAlternativePredicate().orElse(s -> true)) .collect(Collectors.toSet()); return steps; } private boolean stepActorIsRunActor(Step step) { Actor[] stepActors = step.getActors(); if (stepActors == null) { throw (new MissingUseCaseStepPart(step, "actor")); } boolean stepActorIsRunActor = Stream.of(stepActors).anyMatch(stepActor -> userAndSystem.contains(stepActor)); return stepActorIsRunActor; } private boolean stepEventClassIsSameOrSuperclassAsEventClass( Step useCaseStep, Class<?> currentEventClass) { Class<?> stepEventClass = useCaseStep.getUserEventClass(); return stepEventClass.isAssignableFrom(currentEventClass); } private boolean hasTruePredicate(Step step) { Predicate<UseCaseModelRunner> predicate = step.getPredicate(); boolean result = predicate.test(this); return result; } private boolean isStepInIncludedUseCaseIfPresent(Step step) { boolean result = true; if(includedUseCase != null) { result = includedUseCase.equals(step.getUseCase()); } return result; } /** * Overwrite this method to control what happens exactly when an exception is thrown by a system * reaction. The behavior implemented in runner: the exception is provided as an event object to * the runner, by calling {@link #reactTo(Object)}. You may replace this with a more sophisticated * behavior, that for example involves some kind of logging. * * @param e the exception that has been thrown by the system reaction */ protected void handleException(Exception e) { reactTo(e); } /** * Returns the latest step that has been run by this runner. * * @return the latest step run */ public Optional<Step> getLatestStep() { return Optional.ofNullable(latestStep); } /** * Sets the latest step run by the runner. * * <p>Use this method if you want to restore some previous state, normally you should influence * the behavior of the runner by calling {@link #reactTo(Object)}. * * @param latestStep the latest step run */ public void setLatestStep(Step latestStep) { this.latestStep = latestStep; } /** * Returns the flow the latest step that has been run is contained in. * * @return the latest flow run */ public Optional<Flow> getLatestFlow() { return getLatestStep().map(step -> step.getFlow()); } public void setStepWithoutAlternativePredicate(Predicate<Step> predicate) { stepWithoutAlternativePredicate = predicate; } private Optional<Predicate<Step>> getStepWithoutAlternativePredicate() { return Optional.ofNullable(stepWithoutAlternativePredicate); } public void includeUseCase(UseCase includedUseCase, Step includeStep) { this.includedUseCase = includedUseCase; includedUseCases.push(includedUseCase); includeSteps.push(includeStep); optionalIncludeStep = Optional.of(includeStep); for(Flow includedFlow : includedUseCase.getFlows()){ includeFlowAfterStep(includedFlow, includeStep); } } private void includeFlowAfterStep(Flow includedFlow, Step includeStep) { Optional<Step> optionalFirstStepOfFlow = includedFlow.getFirstStep(); optionalFirstStepOfFlow.ifPresent( firstStepOfFlow -> { Predicate<UseCaseModelRunner> oldFlowPosition = firstStepOfFlow.getFlowPosition().orElse(r -> false); Predicate<UseCaseModelRunner> includeFlowPosition = new After(includeStep).or(oldFlowPosition); firstStepOfFlow.setFlowPosition(includeFlowPosition); }); } private boolean isAtEndOfIncludedFlow() { Optional<Step> lastStepOfRunningFlow = getLatestStep().map(ls -> getLastStepOf(ls.getFlow())); boolean result = getLatestStep() .map( ls -> ls.getUseCase().equals(includedUseCase) && ls.equals(lastStepOfRunningFlow.get())) .orElse(false); return result; } private Step getLastStepOf(Flow flow) { List<Step> stepsOfFlow = flow.getSteps(); int lastStepIndex = stepsOfFlow.size() - 1; Step lastStepOfFlow = stepsOfFlow.get(lastStepIndex); return lastStepOfFlow; } }
requirementsascodecore/src/main/java/org/requirementsascode/UseCaseModelRunner.java
package org.requirementsascode; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; import org.requirementsascode.exception.MissingUseCaseStepPart; import org.requirementsascode.exception.MoreThanOneStepCanReact; import org.requirementsascode.exception.UnhandledException; import org.requirementsascode.predicate.After; /** * A use case model runner is a highly configurable use case controller that receives events from * the frontend and conditionally calls methods on the backend. * * <p>In requirementsascode, a use case model runner is the only way the frontend communicates with * the backend. It is configured by the use case model it owns. Each real user needs an instance of * a runner, as the runner determines the journey of the user through the use cases. */ public class UseCaseModelRunner implements Serializable{ private Optional<Actor> user; private List<Actor> userAndSystem; private UseCaseModel useCaseModel; private Step latestStep; private boolean isRunning; private SystemReactionTrigger systemReactionTrigger; private Consumer<SystemReactionTrigger> systemReaction; private Predicate<Step> stepWithoutAlternativePredicate; private LinkedList<UseCase> includedUseCases; private LinkedList<Step> includeSteps; private Optional<UseCase> optionalIncludedUseCase; private Optional<Step> optionalIncludeStep; private static final long serialVersionUID = 1787451244764017381L; /** * Constructor for creating a runner with standard system reaction, that is: the system reaction, * as defined in the use case step, simply accepts an event. */ public UseCaseModelRunner() { this.user = Optional.empty(); this.systemReactionTrigger = new SystemReactionTrigger(); adaptSystemReaction(systemReactionTrigger -> systemReactionTrigger.trigger()); restart(); } /** * Adapt the system reaction to perform tasks before and/or after triggering the system reaction. * This is useful for cross-cutting concerns, e.g. measuring performance. * * @param adaptedSystemReaction the system reaction to replace the standard system reaction. */ public void adaptSystemReaction(Consumer<SystemReactionTrigger> adaptedSystemReaction) { this.systemReaction = adaptedSystemReaction; } /** * Restarts the runner, resetting it to its original defaults ("no flow has * been run, no step has been run, no use case included"). */ public void restart() { setLatestStep(null); includedUseCases = new LinkedList<>(); includeSteps = new LinkedList<>(); optionalIncludedUseCase = Optional.empty(); optionalIncludeStep = Optional.empty(); } /** * Configures the runner to use the specified use case model. After you called this method, the * runner will accept events via {@link #reactTo(Object)}. * * <p>As a side effect, this method immediately triggers "autonomous system reactions". * * @param useCaseModel the model that defines the runner's behavior */ public void run(UseCaseModel useCaseModel) { this.useCaseModel = useCaseModel; this.userAndSystem = userAndSystem(user.orElse(useCaseModel.getUserActor())); this.isRunning = true; triggerAutonomousSystemReaction(); } private void triggerAutonomousSystemReaction() { reactTo(this); } private List<Actor> userAndSystem(Actor userActor) { return Arrays.asList(userActor, userActor.getUseCaseModel().getSystemActor()); } /** * After you called this method, the runner will only react to steps that have explicitly set the * specified actor as one of its actors, or that are declared as "autonomous system reactions". * * <p>As a side effect, calling this method triggers immediately triggers "autonomous system * reactions". * * @param actor the actor to run as * @return this runner, for method chaining with {@link #run(UseCaseModel)} */ public UseCaseModelRunner as(Actor actor) { Objects.requireNonNull(actor); this.user = Optional.of(actor); this.userAndSystem = userAndSystem(user.get()); return this; } /** * Returns whether the runner is currently running. * * @see #run(UseCaseModel) * @return true if the runner is running, false otherwise. */ public boolean isRunning() { return isRunning; } /** * Stops the runner. It will not be reacting to events, until {@link #run(UseCaseModel)} is called * again. */ public void stop() { isRunning = false; } /** * Call this method from the frontend to provide several event objects to the runner. For each * event object, {@link #reactTo(Object)} is called. * * @param events the events to react to */ public void reactTo(Object... events) { Objects.requireNonNull(events); for (Object event : events) { reactTo(event); } } /** * Call this method from the frontend to provide an event object to the runner. * * <p>If it is running, the runner will then check which steps can react to the event. If a single * step can react, the runner will trigger the system reaction for that step. If no step can * react, the runner will NOT trigger any system reaction. If more than one step can react, the * runner will throw an exception. * * <p>After that, the runner will trigger "autonomous system reactions". * * <p>See {@link #getStepsThatCanReactTo(Class)} for a description of what "can react" means. * * @param <T> the type of the event object * @param event the event object provided by the frontend * @return the use case step whose system reaction was triggered, or else an empty optional if * none was triggered. * @throws MoreThanOneStepCanReact if more than one step can react * @throws UnhandledException if no step can react, and the event is an (in)direct subclass of * Throwable. */ public <T> Optional<Step> reactTo(T event) { Objects.requireNonNull(event); Optional<Step> latestStepRun = Optional.empty(); if (isRunning) { Class<? extends Object> currentEventClass = event.getClass(); Set<Step> stepsThatCanReact = getStepsThatCanReactTo(currentEventClass); latestStepRun = triggerSystemReactionForSteps(event, stepsThatCanReact); } return latestStepRun; } private <T> Optional<Step> triggerSystemReactionForSteps(T event, Collection<Step> steps) { Step useCaseStep = null; if (steps.size() == 1) { useCaseStep = steps.iterator().next(); triggerSystemReactionForStep(event, useCaseStep); } else if (steps.size() > 1) { throw new MoreThanOneStepCanReact(steps); } else if (event instanceof Throwable) { throw new UnhandledException((Throwable) event); } return useCaseStep != null ? Optional.of(useCaseStep) : Optional.empty(); } private <T> Step triggerSystemReactionForStep(T event, Step step) { if (step.getSystemReaction() == null) { throw new MissingUseCaseStepPart(step, "system"); } setLatestStep(step); setStepWithoutAlternativePredicate(null); systemReactionTrigger.setupWith(event, step); try { systemReaction.accept(systemReactionTrigger); } catch (Exception e) { handleException(e); } continueAfterIncludeStepWhenEndOfIncludedFlowIsReached(); triggerAutonomousSystemReaction(); return step; } private void continueAfterIncludeStepWhenEndOfIncludedFlowIsReached() { if (optionalIncludedUseCase.isPresent() && optionalIncludeStep.isPresent() && isAtEndOfIncludedFlow()) { setLatestStep(optionalIncludeStep.get()); optionalIncludedUseCase = getUseCaseIncludedBefore(); optionalIncludeStep = getIncludeStepBefore(); } } private Optional<UseCase> getUseCaseIncludedBefore(){ includedUseCases.pop(); UseCase includedUseCase = includedUseCases.peek(); return includedUseCase != null? Optional.of(includedUseCase) : Optional.empty(); } private Optional<Step> getIncludeStepBefore(){ includeSteps.pop(); Step includeStep = includeSteps.peek(); return includeStep != null? Optional.of(includeStep) : Optional.empty(); } /** * Returns whether at least one step can react to an event of the specified class. * * @see #getStepsThatCanReactTo(Class) * @param eventClass the specified class * @return true if the runner is running and at least one step can react, false otherwise */ public boolean canReactTo(Class<? extends Object> eventClass) { boolean canReact = getStepsThatCanReactTo(eventClass).size() > 0; return canReact; } /** * Returns the use case steps in the use case model that can react to the specified event class. * * <p>A step "can react" if all of the following conditions are met: a) the runner is running b) * one of the step's actors matches the actor the runner is run as c) the step's event class is * the same or a superclass of the specified event class d) the step has a predicate that is true * * @param eventClass the class of events * @return the steps that can react to the class of events */ public Set<Step> getStepsThatCanReactTo(Class<? extends Object> eventClass) { Objects.requireNonNull(eventClass); Set<Step> stepsThatCanReact; if (isRunning) { Stream<Step> stepStream = useCaseModel.getModifiableSteps().stream(); stepsThatCanReact = stepsInStreamThatCanReactTo(eventClass, stepStream); } else { stepsThatCanReact = new HashSet<>(); } return stepsThatCanReact; } /** * Gets the steps that can react from the specified stream, rather than from the whole use case * model. * * @see #getStepsThatCanReactTo(Class) * @param eventClass eventClass the class of events * @param stepStream the stream of steps * @return the subset of steps that can react to the class of events */ Set<Step> stepsInStreamThatCanReactTo( Class<? extends Object> eventClass, Stream<Step> stepStream) { Set<Step> steps; steps = stepStream .filter(step -> stepActorIsRunActor(step)) .filter(step -> stepEventClassIsSameOrSuperclassAsEventClass(step, eventClass)) .filter(step -> hasTruePredicate(step)) .filter(step -> isStepInIncludedUseCaseIfPresent(step)) .filter(getStepWithoutAlternativePredicate().orElse(s -> true)) .collect(Collectors.toSet()); return steps; } private boolean stepActorIsRunActor(Step step) { Actor[] stepActors = step.getActors(); if (stepActors == null) { throw (new MissingUseCaseStepPart(step, "actor")); } boolean stepActorIsRunActor = Stream.of(stepActors).anyMatch(stepActor -> userAndSystem.contains(stepActor)); return stepActorIsRunActor; } private boolean stepEventClassIsSameOrSuperclassAsEventClass( Step useCaseStep, Class<?> currentEventClass) { Class<?> stepEventClass = useCaseStep.getUserEventClass(); return stepEventClass.isAssignableFrom(currentEventClass); } private boolean hasTruePredicate(Step step) { Predicate<UseCaseModelRunner> predicate = step.getPredicate(); boolean result = predicate.test(this); return result; } private boolean isStepInIncludedUseCaseIfPresent(Step step) { boolean result = optionalIncludedUseCase.map(uc -> uc.equals(step.getUseCase())).orElse(true); return result; } /** * Overwrite this method to control what happens exactly when an exception is thrown by a system * reaction. The behavior implemented in runner: the exception is provided as an event object to * the runner, by calling {@link #reactTo(Object)}. You may replace this with a more sophisticated * behavior, that for example involves some kind of logging. * * @param e the exception that has been thrown by the system reaction */ protected void handleException(Exception e) { reactTo(e); } /** * Returns the latest step that has been run by this runner. * * @return the latest step run */ public Optional<Step> getLatestStep() { return Optional.ofNullable(latestStep); } /** * Sets the latest step run by the runner. * * <p>Use this method if you want to restore some previous state, normally you should influence * the behavior of the runner by calling {@link #reactTo(Object)}. * * @param latestStep the latest step run */ public void setLatestStep(Step latestStep) { this.latestStep = latestStep; } /** * Returns the flow the latest step that has been run is contained in. * * @return the latest flow run */ public Optional<Flow> getLatestFlow() { return getLatestStep().map(step -> step.getFlow()); } public void setStepWithoutAlternativePredicate(Predicate<Step> predicate) { stepWithoutAlternativePredicate = predicate; } private Optional<Predicate<Step>> getStepWithoutAlternativePredicate() { return Optional.ofNullable(stepWithoutAlternativePredicate); } public void includeUseCase(UseCase includedUseCase, Step includeStep) { includedUseCases.push(includedUseCase); includeSteps.push(includeStep); optionalIncludedUseCase = Optional.of(includedUseCase); optionalIncludeStep = Optional.of(includeStep); for(Flow includedFlow : includedUseCase.getFlows()){ includeFlowAfterStep(includedFlow, includeStep); } } private void includeFlowAfterStep(Flow includedFlow, Step includeStep) { Optional<Step> optionalFirstStepOfFlow = includedFlow.getFirstStep(); optionalFirstStepOfFlow.ifPresent( firstStepOfFlow -> { Predicate<UseCaseModelRunner> oldFlowPosition = firstStepOfFlow.getFlowPosition().orElse(r -> false); Predicate<UseCaseModelRunner> includeFlowPosition = new After(includeStep).or(oldFlowPosition); firstStepOfFlow.setFlowPosition(includeFlowPosition); }); } private boolean isAtEndOfIncludedFlow() { Optional<Step> lastStepOfRunningFlow = getLatestStep().map(ls -> getLastStepOf(ls.getFlow())); boolean result = getLatestStep() .map( ls -> ls.getUseCase().equals(optionalIncludedUseCase.get()) && ls.equals(lastStepOfRunningFlow.get())) .orElse(false); return result; } private Step getLastStepOf(Flow flow) { List<Step> stepsOfFlow = flow.getSteps(); int lastStepIndex = stepsOfFlow.size() - 1; Step lastStepOfFlow = stepsOfFlow.get(lastStepIndex); return lastStepOfFlow; } }
make includedUseCase in UseCaseModelRunner non-optional
requirementsascodecore/src/main/java/org/requirementsascode/UseCaseModelRunner.java
make includedUseCase in UseCaseModelRunner non-optional
<ide><path>equirementsascodecore/src/main/java/org/requirementsascode/UseCaseModelRunner.java <ide> * a runner, as the runner determines the journey of the user through the use cases. <ide> */ <ide> public class UseCaseModelRunner implements Serializable{ <add> private static final long serialVersionUID = 1787451244764017381L; <add> <ide> private Optional<Actor> user; <ide> private List<Actor> userAndSystem; <ide> <ide> private Predicate<Step> stepWithoutAlternativePredicate; <ide> private LinkedList<UseCase> includedUseCases; <ide> private LinkedList<Step> includeSteps; <del> private Optional<UseCase> optionalIncludedUseCase; <add> private UseCase includedUseCase; <ide> private Optional<Step> optionalIncludeStep; <del> <del> private static final long serialVersionUID = 1787451244764017381L; <ide> <ide> /** <ide> * Constructor for creating a runner with standard system reaction, that is: the system reaction, <ide> setLatestStep(null); <ide> includedUseCases = new LinkedList<>(); <ide> includeSteps = new LinkedList<>(); <del> optionalIncludedUseCase = Optional.empty(); <add> includedUseCase = null; <ide> optionalIncludeStep = Optional.empty(); <ide> } <ide> <ide> } <ide> <ide> private void continueAfterIncludeStepWhenEndOfIncludedFlowIsReached() { <del> if (optionalIncludedUseCase.isPresent() <add> if (includedUseCase != null <ide> && optionalIncludeStep.isPresent() <ide> && isAtEndOfIncludedFlow()) { <ide> setLatestStep(optionalIncludeStep.get()); <del> optionalIncludedUseCase = getUseCaseIncludedBefore(); <add> includedUseCase = getUseCaseIncludedBefore(); <ide> optionalIncludeStep = getIncludeStepBefore(); <ide> } <ide> } <ide> <del> private Optional<UseCase> getUseCaseIncludedBefore(){ <add> private UseCase getUseCaseIncludedBefore(){ <ide> includedUseCases.pop(); <ide> UseCase includedUseCase = includedUseCases.peek(); <del> return includedUseCase != null? Optional.of(includedUseCase) : Optional.empty(); <add> return includedUseCase; <ide> } <ide> <ide> private Optional<Step> getIncludeStepBefore(){ <ide> } <ide> <ide> private boolean isStepInIncludedUseCaseIfPresent(Step step) { <del> boolean result = optionalIncludedUseCase.map(uc -> uc.equals(step.getUseCase())).orElse(true); <add> boolean result = true; <add> if(includedUseCase != null) { <add> result = includedUseCase.equals(step.getUseCase()); <add> } <ide> return result; <ide> } <ide> <ide> } <ide> <ide> public void includeUseCase(UseCase includedUseCase, Step includeStep) { <add> this.includedUseCase = includedUseCase; <ide> includedUseCases.push(includedUseCase); <ide> includeSteps.push(includeStep); <del> optionalIncludedUseCase = Optional.of(includedUseCase); <ide> optionalIncludeStep = Optional.of(includeStep); <ide> for(Flow includedFlow : includedUseCase.getFlows()){ <ide> includeFlowAfterStep(includedFlow, includeStep); <ide> } <ide> } <del> <add> <ide> private void includeFlowAfterStep(Flow includedFlow, Step includeStep) { <ide> Optional<Step> optionalFirstStepOfFlow = includedFlow.getFirstStep(); <ide> optionalFirstStepOfFlow.ifPresent( <ide> getLatestStep() <ide> .map( <ide> ls -> <del> ls.getUseCase().equals(optionalIncludedUseCase.get()) <add> ls.getUseCase().equals(includedUseCase) <ide> && ls.equals(lastStepOfRunningFlow.get())) <ide> .orElse(false); <ide> return result;
Java
bsd-3-clause
562d56c3a196cad6004fc0dae53aa302e48edc6f
0
tomfisher/tripleplay,tomfisher/tripleplay,tomfisher/tripleplay,joansmith/tripleplay,joansmith/tripleplay,joansmith/tripleplay,tomfisher/tripleplay,joansmith/tripleplay,joansmith/tripleplay,tomfisher/tripleplay
// // Triple Play - utilities for use in PlayN-based games // Copyright (c) 2011-2013, Three Rings Design, Inc. - All rights reserved. // http://github.com/threerings/tripleplay/blob/master/LICENSE package tripleplay.syncdb; /** * Provides a mechanism for resolving conflict between two conflicting values in a sync db. */ public interface Resolver<T> { /** Uses the server value, ignoring the client value. */ Resolver<Object> SERVER = new Resolver<Object>() { public <V> V resolve (V client, V server) { return server; } }; /** Uses the smallest of the client and server integral numbers. */ Resolver<Number> INTMIN = new Resolver<Number>() { public <V extends Number> V resolve (V client, V server) { return (client.longValue() > server.longValue()) ? server : client; } }; /** Uses the largest of the client and server integral numbers. */ Resolver<Number> INTMAX = new Resolver<Number>() { public <V extends Number> V resolve (V client, V server) { return (client.longValue() > server.longValue()) ? client : server; } }; /** Uses the smallest of the client and server floating point numbers. */ Resolver<Number> FLOATMIN = new Resolver<Number>() { public <V extends Number> V resolve (V client, V server) { return (client.doubleValue() > server.doubleValue()) ? server : client; } }; /** Uses the largest of the client and server floating point numbers. */ Resolver<Number> FLOATMAX = new Resolver<Number>() { public <V extends Number> V resolve (V client, V server) { return (client.doubleValue() > server.doubleValue()) ? client : server; } }; /** Uses whichever of the client or server is true. */ Resolver<Boolean> TRUE = new Resolver<Boolean>() { @SuppressWarnings("unchecked") public Boolean resolve (Boolean client, Boolean server) { return client ? client : server; } }; /** Uses whichever of the client or server is false. */ Resolver<Boolean> FALSE = new Resolver<Boolean>() { @SuppressWarnings("unchecked") public Boolean resolve (Boolean client, Boolean server) { return client ? server : client; } }; /** Resolves a conflict between a client and server value. * @return the value to be used on the client. */ <V extends T> V resolve (V client, V server); }
core/src/main/java/tripleplay/syncdb/Resolver.java
// // Triple Play - utilities for use in PlayN-based games // Copyright (c) 2011-2013, Three Rings Design, Inc. - All rights reserved. // http://github.com/threerings/tripleplay/blob/master/LICENSE package tripleplay.syncdb; /** * Provides a mechanism for resolving conflict between two conflicting values in a sync db. */ public interface Resolver<T> { /** Uses the server value, ignoring the client value. */ Resolver<Object> SERVER = new Resolver<Object>() { public <V> V resolve (V client, V server) { return server; } }; /** Uses the smallest of the client and server integral numbers. */ Resolver<Number> INTMIN = new Resolver<Number>() { public <V extends Number> V resolve (V client, V server) { return (client.longValue() > server.longValue()) ? server : client; } }; /** Uses the largest of the client and server integral numbers. */ Resolver<Number> INTMAX = new Resolver<Number>() { public <V extends Number> V resolve (V client, V server) { return (client.longValue() > server.longValue()) ? client : server; } }; /** Uses the smallest of the client and server floating point numbers. */ Resolver<Number> FLOATMIN = new Resolver<Number>() { public <V extends Number> V resolve (V client, V server) { return (client.doubleValue() > server.doubleValue()) ? server : client; } }; /** Uses the largest of the client and server floating point numbers. */ Resolver<Number> FLOATMAX = new Resolver<Number>() { public <V extends Number> V resolve (V client, V server) { return (client.doubleValue() > server.doubleValue()) ? client : server; } }; /** Uses whichever of the client or server is true. */ Resolver<Boolean> TRUE = new Resolver<Boolean>() { public <V extends Boolean> V resolve (V client, V server) { return client ? client : server; } }; /** Uses whichever of the client or server is false. */ Resolver<Boolean> FALSE = new Resolver<Boolean>() { public <V extends Boolean> V resolve (V client, V server) { return client ? server : client; } }; /** Resolves a conflict between a client and server value. * @return the value to be used on the client. */ <V extends T> V resolve (V client, V server); }
Compiler-appeasing shenanigans. Boolean is final, so it carps that V can't extend it, but resolve's signature wants that format. This way, however, supports suppression of the warning.
core/src/main/java/tripleplay/syncdb/Resolver.java
Compiler-appeasing shenanigans.
<ide><path>ore/src/main/java/tripleplay/syncdb/Resolver.java <ide> <ide> /** Uses whichever of the client or server is true. */ <ide> Resolver<Boolean> TRUE = new Resolver<Boolean>() { <del> public <V extends Boolean> V resolve (V client, V server) { <add> @SuppressWarnings("unchecked") <add> public Boolean resolve (Boolean client, Boolean server) { <ide> return client ? client : server; <ide> } <ide> }; <ide> <ide> /** Uses whichever of the client or server is false. */ <ide> Resolver<Boolean> FALSE = new Resolver<Boolean>() { <del> public <V extends Boolean> V resolve (V client, V server) { <add> @SuppressWarnings("unchecked") <add> public Boolean resolve (Boolean client, Boolean server) { <ide> return client ? server : client; <ide> } <ide> };
JavaScript
mit
7d0edcafe418622d026c80078c7dfa0f9e316fcb
0
RalphSleigh/bookings,RalphSleigh/bookings,RalphSleigh/bookings
import React from 'react' import csv from 'csv-file-creator' import ReactTable from 'react-table' import Moment from 'moment' import update from 'immutability-helper'; import eol from 'eol' import map from 'lodash/map' //import bookings from '../bookings' //import { manageEventCheck } from '../permission.js' import { Row, Col, Button, Card, CardBody, CardTitle, CardSubtitle, } from 'reactstrap'; import W from '../../../shared/woodcraft.js' import ageFactory from "../../age"; export default class Participants extends React.Component { constructor(props) { super(props); this.state = {expanded: null}; this.ageWidgets = ageFactory(this.props.Event.toJS()); this.exportCSV = this.exportCSV.bind(this); this.updateExpanded = this.updateExpanded.bind(this); } shouldComponentUpdate(nextProps, nextState) { //rerendering the tables suck, lets not do it. //if (this.state !== nextState) return true; //return !this.props.Bookings.equals(nextProps.Bookings); return true; } componentWillReceiveProps() { this.setState(update(this.state, {expanded: {$set: null}})); } exportCSV() { const exportedData = this.props.participants.map(p => { const b = this.props.bookings.find(b => b.id === p.bookingId); return [p.id, p.name, p.displayAge, Moment(p.age).format("DD/MM/YYYY"), p.diet, p.dietExtra, p.medical, p.days, b.userName, b.userEmail, b.userContact, b.emergencyName, b.emergencyPhone, eol.crlf(b.note || ''), p.externalExtra.adultFirstAid, p.createdAt, p.updatedAt] }); const fileName = this.props.Event.get('name') + "-Participants-" + Moment().format('YYYY-MM-DD') + ".csv"; csv(fileName, [['id', 'Name', 'Age Group', 'DOB', 'Diet', 'Requirements & Allergies', 'Medical', 'Attendance', 'Booking Name', 'Booking e-mail', 'Booking Phone', 'Emergency name', 'Emergency Contact', 'Note', 'First Aid', 'Created At', 'Updated At'], ...exportedData]); } updateExpanded(id) { return e => { if (id === this.state.expanded) this.setState(update(this.state, {expanded: {$set: null}})); else this.setState(update(this.state, {expanded: {$set: id}})); } } subRow = (row) => { const event = row.original.E.toJS(); const village = event.villages.find(v => row.original.b.villageId === v.id); const organisation = event.organisations.find(o => row.original.b.organisationId === o.id); const attendance = event.partialDates === "presets" ? event.partialDatesData.find(d => d.mask === row.original.p.days) : null; return (<Card> <CardBody> <CardTitle> {row.original.name} </CardTitle> <Row> <Col sm={4}> {this.ageWidgets.participantCardField(row.original)} {row.original.b.district ? <p><b>Group/District:</b> {row.original.b.district}</p> : null} <p><b>Booking Contact:</b> {row.original.b.userName}</p> <p><b>Booking Contact Phone:</b> {row.original.b.userContact}</p> {village ? <p><b>Village:</b> {village.name}</p> : null} {organisation ? <p><b>Organisation:</b> {organisation.name}</p> : null} {attendance ? <p><b>Attendance:</b> {attendance.name}</p> : null} {!event.bigCampMode ? <p><b>Emergency Contact:</b> {row.original.b.emergencyName}</p> : null} {!event.bigCampMode ? <p><b>Emergency Phone:</b> {row.original.b.emergencyPhone}</p> : null} </Col> <Col sm={4}> <p><b>Diet:</b> {row.original.diet} </p> <p><b>Diet Info:</b></p><p>{row.original.p.dietExtra}</p> <p><b>Anything Else:</b></p><p>{row.original.b.note}</p> </Col> <Col sm={4}> <p><b>Medical:</b></p><p>{row.original.p.medical}</p> </Col> </Row> </CardBody> </Card>); }; render() { const event = this.props.Event.toJS(); const bookings = this.props.filteredBookings; const participants = this.props.filteredParticipants; const groups = W.reduce((a, w) => { const people = participants.filter((p) => p.ageGroup === '' ? false : p.ageGroup === w.singular); if (people.length === 0) return a; return a + ` ${w.name}: ${people.length}`; }, ''); //const prows = participants.sort(nameSort).map(p => <tr key={p.id}><td>{p.name}</td><td>{p.age}</td><td>{p.diet}</td><td>{bookings.find(b => b.id === p.bookingId).userName}</td></tr>) const data = participants.map(p => { const b = bookings.find(b => b.id === p.bookingId); return { name: p.name, dob: p.age, age: p.displayAge, diet: p.diet, createdAt: p.prettyCreatedAt, district: b.district, p: p, b: b, E: this.props.Event }; }); const columns = [{ id: "name", accessor: row => row, Header: "Name", sortable: true, sortMethod: nameSort, Cell: row => row.value.name }]; if (event.bigCampMode) columns.push({accessor: "district", Header: "District", sortable: true}); columns.push({ id: 'age', accessor: row => row, Header: "Age", sortable: true, sortMethod: dobSort, Cell: row => row.original.age }, {accessor: "diet", Header: "Diet", sortable: true, minWidth: 70}, {id: 'createdAt', accessor: row => row, Cell: row => row.original.createdAt, sortMethod: createdSort, Header: "Created At", sortable: true, minWidth: 50 }); if (event.customQuestions.adultFirstAid) columns.push({ id: 'firstaid', accessor: row => row, Cell: row => row.original.p.externalExtra.adultFirstAid === 'yes' ? '✅' : '', Header: "⚕️", sortMethod: firstAidSort, width: 40, sortable: true }); const expanded = {[this.state.expanded]: true}; return (<React.Fragment> <Row> <Col> <Button className="float-right" onClick={this.exportCSV}>Export CSV</Button> <h4>Total Participants: {participants.length}</h4> <p>{groups}</p> </Col> </Row> <Row> <Col> <ReactTable expanded={expanded} getTrProps={(state, rowInfo, column) => { if (rowInfo) return {onClick: this.updateExpanded(rowInfo.viewIndex)}; return {} }} onSortedChange={this.updateExpanded(null)} onPageChange={this.updateExpanded(null)} SubComponent={this.subRow} data={data} columns={columns} showPageSizeOption={false} showPagination={true} defaultPageSize={50}/> </Col> </Row> </React.Fragment>); } } const dobSort = (a, b) => { return a.dob < b.dob ? 1 : -1; }; const createdSort = (a, b) => { return a.p.createdAt > b.p.createdAt ? 1 : -1; }; const firstAidSort = (a, b) => { return !!a.p.externalExtra.adultFirstAid - !!b.p.externalExtra.adultFirstAid; } const nameSort = (a, b) => { var splitA = a.name.split(" "); var splitB = b.name.split(" "); var lastA = splitA[splitA.length - 1]; var lastB = splitB[splitB.length - 1]; if (lastA < lastB) return -1; if (lastA > lastB) return 1; return 0; };
front/manage/components/participants.js
import React from 'react' import csv from 'csv-file-creator' import ReactTable from 'react-table' import Moment from 'moment' import update from 'immutability-helper'; import eol from 'eol' import map from 'lodash/map' //import bookings from '../bookings' //import { manageEventCheck } from '../permission.js' import { Row, Col, Button, Card, CardBody, CardTitle, CardSubtitle, } from 'reactstrap'; import W from '../../../shared/woodcraft.js' import ageFactory from "../../age"; export default class Participants extends React.Component { constructor(props) { super(props); this.state = {expanded: null}; this.ageWidgets = ageFactory(this.props.Event.toJS()); this.exportCSV = this.exportCSV.bind(this); this.updateExpanded = this.updateExpanded.bind(this); } shouldComponentUpdate(nextProps, nextState) { //rerendering the tables suck, lets not do it. //if (this.state !== nextState) return true; //return !this.props.Bookings.equals(nextProps.Bookings); return true; } componentWillReceiveProps() { this.setState(update(this.state, {expanded: {$set: null}})); } exportCSV() { const exportedData = this.props.participants.map(p => { const b = this.props.bookings.find(b => b.id === p.bookingId); return [p.id, p.name, p.displayAge, Moment(p.age).format("DD/MM/YYYY"), p.diet, p.dietExtra, p.medical, b.userName, b.userEmail, b.userContact, b.emergencyName, b.emergencyPhone, eol.crlf(b.note || ''), p.externalExtra.adultFirstAid, p.createdAt, p.updatedAt] }); const fileName = this.props.Event.get('name') + "-Participants-" + Moment().format('YYYY-MM-DD') + ".csv"; csv(fileName, [['id', 'Name', 'Age Group', 'DOB', 'Diet', 'Requirements & Allergies', 'Medical', 'Booking Name', 'Booking e-mail', 'Booking Phone', 'Emergency name', 'Emergency Contact', 'Note', 'First Aid', 'Created At', 'Updated At'], ...exportedData]); } updateExpanded(id) { return e => { if (id === this.state.expanded) this.setState(update(this.state, {expanded: {$set: null}})); else this.setState(update(this.state, {expanded: {$set: id}})); } } subRow = (row) => { const event = row.original.E.toJS(); const village = event.villages.find(v => row.original.b.villageId === v.id); const organisation = event.organisations.find(o => row.original.b.organisationId === o.id); const attendance = event.partialDates === "presets" ? event.partialDatesData.find(d => d.mask === row.original.p.days) : null; return (<Card> <CardBody> <CardTitle> {row.original.name} </CardTitle> <Row> <Col sm={4}> {this.ageWidgets.participantCardField(row.original)} {row.original.b.district ? <p><b>Group/District:</b> {row.original.b.district}</p> : null} <p><b>Booking Contact:</b> {row.original.b.userName}</p> <p><b>Booking Contact Phone:</b> {row.original.b.userContact}</p> {village ? <p><b>Village:</b> {village.name}</p> : null} {organisation ? <p><b>Organisation:</b> {organisation.name}</p> : null} {attendance ? <p><b>Attendance:</b> {attendance.name}</p> : null} {!event.bigCampMode ? <p><b>Emergency Contact:</b> {row.original.b.emergencyName}</p> : null} {!event.bigCampMode ? <p><b>Emergency Phone:</b> {row.original.b.emergencyPhone}</p> : null} </Col> <Col sm={4}> <p><b>Diet:</b> {row.original.diet} </p> <p><b>Diet Info:</b></p><p>{row.original.p.dietExtra}</p> <p><b>Anything Else:</b></p><p>{row.original.b.note}</p> </Col> <Col sm={4}> <p><b>Medical:</b></p><p>{row.original.p.medical}</p> </Col> </Row> </CardBody> </Card>); }; render() { const event = this.props.Event.toJS(); const bookings = this.props.filteredBookings; const participants = this.props.filteredParticipants; const groups = W.reduce((a, w) => { const people = participants.filter((p) => p.ageGroup === '' ? false : p.ageGroup === w.singular); if (people.length === 0) return a; return a + ` ${w.name}: ${people.length}`; }, ''); //const prows = participants.sort(nameSort).map(p => <tr key={p.id}><td>{p.name}</td><td>{p.age}</td><td>{p.diet}</td><td>{bookings.find(b => b.id === p.bookingId).userName}</td></tr>) const data = participants.map(p => { const b = bookings.find(b => b.id === p.bookingId); return { name: p.name, dob: p.age, age: p.displayAge, diet: p.diet, createdAt: p.prettyCreatedAt, district: b.district, p: p, b: b, E: this.props.Event }; }); const columns = [{ id: "name", accessor: row => row, Header: "Name", sortable: true, sortMethod: nameSort, Cell: row => row.value.name }]; if (event.bigCampMode) columns.push({accessor: "district", Header: "District", sortable: true}); columns.push({ id: 'age', accessor: row => row, Header: "Age", sortable: true, sortMethod: dobSort, Cell: row => row.original.age }, {accessor: "diet", Header: "Diet", sortable: true, minWidth: 70}, {id: 'createdAt', accessor: row => row, Cell: row => row.original.createdAt, sortMethod: createdSort, Header: "Created At", sortable: true, minWidth: 50 }); if (event.customQuestions.adultFirstAid) columns.push({ id: 'firstaid', accessor: row => row, Cell: row => row.original.p.externalExtra.adultFirstAid === 'yes' ? '✅' : '', Header: "⚕️", sortMethod: firstAidSort, width: 40, sortable: true }); const expanded = {[this.state.expanded]: true}; return (<React.Fragment> <Row> <Col> <Button className="float-right" onClick={this.exportCSV}>Export CSV</Button> <h4>Total Participants: {participants.length}</h4> <p>{groups}</p> </Col> </Row> <Row> <Col> <ReactTable expanded={expanded} getTrProps={(state, rowInfo, column) => { if (rowInfo) return {onClick: this.updateExpanded(rowInfo.viewIndex)}; return {} }} onSortedChange={this.updateExpanded(null)} onPageChange={this.updateExpanded(null)} SubComponent={this.subRow} data={data} columns={columns} showPageSizeOption={false} showPagination={true} defaultPageSize={50}/> </Col> </Row> </React.Fragment>); } } const dobSort = (a, b) => { return a.dob < b.dob ? 1 : -1; }; const createdSort = (a, b) => { return a.p.createdAt > b.p.createdAt ? 1 : -1; }; const firstAidSort = (a, b) => { return !!a.p.externalExtra.adultFirstAid - !!b.p.externalExtra.adultFirstAid; } const nameSort = (a, b) => { var splitA = a.name.split(" "); var splitB = b.name.split(" "); var lastA = splitA[splitA.length - 1]; var lastB = splitB[splitB.length - 1]; if (lastA < lastB) return -1; if (lastA > lastB) return 1; return 0; };
Add days to participants
front/manage/components/participants.js
Add days to participants
<ide><path>ront/manage/components/participants.js <ide> p.diet, <ide> p.dietExtra, <ide> p.medical, <add> p.days, <ide> b.userName, <ide> b.userEmail, <ide> b.userContact, <ide> <ide> }); <ide> const fileName = this.props.Event.get('name') + "-Participants-" + Moment().format('YYYY-MM-DD') + ".csv"; <del> csv(fileName, [['id', 'Name', 'Age Group', 'DOB', 'Diet', 'Requirements & Allergies', 'Medical', 'Booking Name', 'Booking e-mail', 'Booking Phone', 'Emergency name', 'Emergency Contact', 'Note', 'First Aid', 'Created At', 'Updated At'], ...exportedData]); <add> csv(fileName, [['id', 'Name', 'Age Group', 'DOB', 'Diet', 'Requirements & Allergies', 'Medical', 'Attendance', 'Booking Name', 'Booking e-mail', 'Booking Phone', 'Emergency name', 'Emergency Contact', 'Note', 'First Aid', 'Created At', 'Updated At'], ...exportedData]); <ide> } <ide> <ide> updateExpanded(id) {
Java
mit
5735fa6ec36fb0e68a0bd41c47b0d940d28b9e5a
0
project-recoin/crisis.net
package crisis.net; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import javax.naming.StringRefAddr; import org.apache.commons.lang.StringEscapeUtils; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class ToCsv { static final String delimate = ","; static String disFile; static String jsonDir; public static void main(String[] args) { if (args.length == 2) { disFile = args[0]; jsonDir = args[1]; } else { System.out.println("two args disFile jsonDir"); System.exit(-1); } try { FileWriter writer = new FileWriter(disFile); writer.append("id,publishedAt,content,locationName,geo_long,geo_lat,tags"); writer.append("\n"); // read the json file File folder = new File(jsonDir); File[] listOfFiles = folder.listFiles(); for (int f = 0; f < listOfFiles.length; f++) { if (listOfFiles[f].isFile() && listOfFiles[f].getAbsoluteFile().toString().contains("json")) { System.out.println("Processing file " + listOfFiles[f]); FileReader reader = new FileReader(listOfFiles[f]); JSONParser jsonParser = new JSONParser(); JSONObject jsonObject = (JSONObject) jsonParser.parse(reader); JSONArray data = (JSONArray) jsonObject.get("data"); // take the elements of the json array for (int i = 0; i < data.size(); i++) { JSONObject doc = (JSONObject) data.get(i); if (doc != null) { String id = (String) doc.get("id"); if (id != null) { writer.append(StringEscapeUtils.escapeCsv(id) + delimate); } else { writer.append(delimate); } String publishedAt = (String) doc.get("publishedAt"); if (publishedAt != null) { writer.append(StringEscapeUtils.escapeCsv(publishedAt) + delimate); } else { writer.append(delimate); } String content = (String) doc.get("content"); if (content != null) { String subString = content; if (subString.length() > 20000) { subString = content.substring(0, 20000); } writer.append(StringEscapeUtils.escapeCsv(subString.replaceAll("\n", "")) + delimate); } else { writer.append(delimate); } JSONObject geo = (JSONObject) doc.get("geo"); if (geo != null) { JSONObject addressComponents = (JSONObject) geo.get("addressComponents"); if (addressComponents != null) { String formattedAddress = (String) addressComponents.get("formattedAddress"); String adminArea1 = (String) addressComponents.get("adminArea1"); if (formattedAddress != null) { writer.append(StringEscapeUtils.escapeCsv(formattedAddress) + delimate); } else if (adminArea1 != null) { writer.append(StringEscapeUtils.escapeCsv(adminArea1) + delimate); } else { writer.append(delimate); } } else { writer.append(delimate); } JSONArray coords = (JSONArray) geo.get("coords"); if (coords != null) { if (coords.get(0) != null) { writer.append(StringEscapeUtils.escapeCsv(coords.get(0).toString()) + delimate); } else { writer.append(delimate); } if (coords.get(1) != null) { writer.append(StringEscapeUtils.escapeCsv(coords.get(1).toString()) + delimate); } else { writer.append(delimate); } } else { writer.append(delimate + delimate); } } else { writer.append(delimate + delimate + delimate); } JSONArray tags = (JSONArray) doc.get("tags"); if (tags != null) { StringBuilder string1 = new StringBuilder(); for (int j = 0; j < tags.size(); j++) { JSONObject tag = (JSONObject) tags.get(j); if (tag != null) { String name = (String) tag.get("name"); string1.append(name + ","); } else { writer.append(delimate); } } writer.append(StringEscapeUtils.escapeCsv(string1.toString()) + delimate); } else { writer.append(delimate); } writer.append("\n"); } } } } writer.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } catch (ParseException ex) { ex.printStackTrace(); } catch (NullPointerException ex) { ex.printStackTrace(); } } }
src/main/java/crisis/net/ToCsv.java
package crisis.net; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import javax.naming.StringRefAddr; import org.apache.commons.lang.StringEscapeUtils; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class ToCsv { static final String delimate = ","; static final String disFile = "crisis.csv"; static final String jsonDir = "/Users/user/crisisNet"; public static void main(String[] args) { try { FileWriter writer = new FileWriter(disFile); writer.append("id,publishedAt,content,locationName,geo_long,geo_lat,tags"); writer.append("\n"); // read the json file File folder = new File(jsonDir); File[] listOfFiles = folder.listFiles(); for (int f = 0; f < listOfFiles.length; f++) { if (listOfFiles[f].isFile() && listOfFiles[f].getAbsoluteFile().toString().contains("json")) { System.out.println("Processing file " + listOfFiles[f]); FileReader reader = new FileReader(listOfFiles[f]); JSONParser jsonParser = new JSONParser(); JSONObject jsonObject = (JSONObject) jsonParser.parse(reader); JSONArray data = (JSONArray) jsonObject.get("data"); // take the elements of the json array for (int i = 0; i < data.size(); i++) { JSONObject doc = (JSONObject) data.get(i); if (doc != null) { String id = (String) doc.get("id"); if (id != null) { writer.append(StringEscapeUtils.escapeCsv(id) + delimate); } else { writer.append(delimate); } String publishedAt = (String) doc.get("publishedAt"); if (publishedAt != null) { writer.append(StringEscapeUtils.escapeCsv(publishedAt) + delimate); } else { writer.append(delimate); } String content = (String) doc.get("content"); if (content != null) { String subString = content; if (subString.length() > 20000) { subString = content.substring(0, 20000); } writer.append(StringEscapeUtils.escapeCsv(subString.replaceAll("\n", "")) + delimate); } else { writer.append(delimate); } JSONObject geo = (JSONObject) doc.get("geo"); if (geo != null) { JSONObject addressComponents = (JSONObject) geo.get("addressComponents"); if (addressComponents != null) { String formattedAddress = (String) addressComponents.get("formattedAddress"); String adminArea1 = (String) addressComponents.get("adminArea1"); if (formattedAddress != null) { writer.append(StringEscapeUtils.escapeCsv(formattedAddress) + delimate); } else if (adminArea1 != null) { writer.append(StringEscapeUtils.escapeCsv(adminArea1) + delimate); } else { writer.append(delimate); } } else { writer.append(delimate); } JSONArray coords = (JSONArray) geo.get("coords"); if (coords != null) { if (coords.get(0) != null) { writer.append(StringEscapeUtils.escapeCsv(coords.get(0).toString()) + delimate); } else { writer.append(delimate); } if (coords.get(1) != null) { writer.append(StringEscapeUtils.escapeCsv(coords.get(1).toString()) + delimate); } else { writer.append(delimate); } } else { writer.append(delimate + delimate); } } else { writer.append(delimate + delimate + delimate); } JSONArray tags = (JSONArray) doc.get("tags"); if (tags != null) { StringBuilder string1 = new StringBuilder(); for (int j = 0; j < tags.size(); j++) { JSONObject tag = (JSONObject) tags.get(j); if (tag != null) { String name = (String) tag.get("name"); string1.append(name + ","); } else { writer.append(delimate); } } writer.append(StringEscapeUtils.escapeCsv(string1.toString()) + delimate); } else { writer.append(delimate); } writer.append("\n"); } } } } writer.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } catch (ParseException ex) { ex.printStackTrace(); } catch (NullPointerException ex) { ex.printStackTrace(); } } }
csv has args
src/main/java/crisis/net/ToCsv.java
csv has args
<ide><path>rc/main/java/crisis/net/ToCsv.java <ide> public class ToCsv { <ide> <ide> static final String delimate = ","; <del> static final String disFile = "crisis.csv"; <del> static final String jsonDir = "/Users/user/crisisNet"; <add> static String disFile; <add> static String jsonDir; <ide> <ide> public static void main(String[] args) { <ide> <add> if (args.length == 2) { <add> disFile = args[0]; <add> jsonDir = args[1]; <add> } else { <add> System.out.println("two args disFile jsonDir"); <add> System.exit(-1); <add> } <ide> try { <ide> <ide> FileWriter writer = new FileWriter(disFile); <ide> if (content != null) { <ide> String subString = content; <ide> if (subString.length() > 20000) { <del> subString = content.substring(0, 20000); <add> subString = content.substring(0, 20000); <ide> } <ide> writer.append(StringEscapeUtils.escapeCsv(subString.replaceAll("\n", "")) + delimate); <ide> } else {
Java
apache-2.0
1d135b7ab84ab2e03481b47b7d09f40e35810170
0
NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra
/* ### * IP: GHIDRA * * 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 ghidra.framework.main.datatable; import java.awt.Component; import java.util.Collections; import java.util.List; import docking.ActionContext; import docking.ComponentProvider; import ghidra.framework.model.*; /** * A context that understands files that live in a {@link Project}. Most of the clients of * this context will use its notion of selected {@link DomainFile}s and folders. */ public class ProjectDataActionContext extends ActionContext implements DomainFileContext { private List<DomainFolder> selectedFolders; private List<DomainFile> selectedFiles; private Component comp; private boolean isActiveProject; private ProjectData projectData; private boolean isTransient; public ProjectDataActionContext(ComponentProvider provider, ProjectData projectData, Object contextObject, List<DomainFolder> selectedFolders, List<DomainFile> selectedFiles, Component comp, boolean isActiveProject) { super(provider, contextObject, comp); this.projectData = projectData; this.selectedFolders = selectedFolders; this.selectedFiles = selectedFiles; this.comp = comp; this.isActiveProject = isActiveProject; } @Override public List<DomainFile> getSelectedFiles() { if (selectedFiles == null) { return Collections.emptyList(); } return selectedFiles; } public List<DomainFolder> getSelectedFolders() { if (selectedFolders == null) { return Collections.emptyList(); } return selectedFolders; } public boolean hasExactlyOneFileOrFolder() { return (getFolderCount() + getFileCount()) == 1; } public int getFolderCount() { if (selectedFolders == null) { return 0; } return selectedFolders.size(); } @Override public int getFileCount() { if (selectedFiles == null) { return 0; } return selectedFiles.size(); } public ProjectData getProjectData() { return projectData; } public Component getComponent() { return comp; } @Override public boolean isInActiveProject() { return isActiveProject; } public boolean isReadOnlyProject() { if (projectData == null) { return false; } return !projectData.getRootFolder().isInWritableProject(); } public boolean hasOneOrMoreFilesAndFolders() { return getFolderCount() + getFileCount() > 0; } public boolean containsRootFolder() { if (getFolderCount() == 0) { return false; } List<DomainFolder> folders = getSelectedFolders(); for (DomainFolder domainFolder : folders) { if (domainFolder.getParent() == null) { return true; } } return false; } /** * Transient data is that which will appear in a temporary project dialog * @param isTransient true if transient */ public void setTransient(boolean isTransient) { this.isTransient = isTransient; } /** * Transient data is that which will appear in a temporary project dialog * @return true if transient */ public boolean isTransient() { return isTransient; } }
Ghidra/Framework/Project/src/main/java/ghidra/framework/main/datatable/ProjectDataActionContext.java
/* ### * IP: GHIDRA * * 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 ghidra.framework.main.datatable; import java.awt.Component; import java.util.Collections; import java.util.List; import docking.ActionContext; import docking.ComponentProvider; import ghidra.framework.model.*; public class ProjectDataActionContext extends ActionContext implements DomainFileContext { private List<DomainFolder> selectedFolders; private List<DomainFile> selectedFiles; private Component comp; private boolean isActiveProject; private ProjectData projectData; private boolean isTransient; public ProjectDataActionContext(ComponentProvider provider, ProjectData projectData, Object contextObject, List<DomainFolder> selectedFolders, List<DomainFile> selectedFiles, Component comp, boolean isActiveProject) { super(provider, contextObject, comp); this.projectData = projectData; this.selectedFolders = selectedFolders; this.selectedFiles = selectedFiles; this.comp = comp; this.isActiveProject = isActiveProject; } @Override public List<DomainFile> getSelectedFiles() { if (selectedFiles == null) { return Collections.emptyList(); } return selectedFiles; } public List<DomainFolder> getSelectedFolders() { if (selectedFolders == null) { return Collections.emptyList(); } return selectedFolders; } public boolean hasExactlyOneFileOrFolder() { return (getFolderCount() + getFileCount()) == 1; } public int getFolderCount() { if (selectedFolders == null) { return 0; } return selectedFolders.size(); } @Override public int getFileCount() { if (selectedFiles == null) { return 0; } return selectedFiles.size(); } public ProjectData getProjectData() { return projectData; } public Component getComponent() { return comp; } @Override public boolean isInActiveProject() { return isActiveProject; } public boolean isReadOnlyProject() { if (projectData == null) { return false; } return !projectData.getRootFolder().isInWritableProject(); } public boolean hasOneOrMoreFilesAndFolders() { return getFolderCount() + getFileCount() > 0; } public boolean containsRootFolder() { if (getFolderCount() == 0) { return false; } List<DomainFolder> folders = getSelectedFolders(); for (DomainFolder domainFolder : folders) { if (domainFolder.getParent() == null) { return true; } } return false; } /** * Transient data is that which will appear in a temporary project dialog * @param isTransient true if transient */ public void setTransient(boolean isTransient) { this.isTransient = isTransient; } /** * Transient data is that which will appear in a temporary project dialog * @return true if transient */ public boolean isTransient() { return isTransient; } }
GT-3302 - Front-end UI freeze - review fixes
Ghidra/Framework/Project/src/main/java/ghidra/framework/main/datatable/ProjectDataActionContext.java
GT-3302 - Front-end UI freeze - review fixes
<ide><path>hidra/Framework/Project/src/main/java/ghidra/framework/main/datatable/ProjectDataActionContext.java <ide> import docking.ComponentProvider; <ide> import ghidra.framework.model.*; <ide> <add>/** <add> * A context that understands files that live in a {@link Project}. Most of the clients of <add> * this context will use its notion of selected {@link DomainFile}s and folders. <add> */ <ide> public class ProjectDataActionContext extends ActionContext implements DomainFileContext { <ide> <ide> private List<DomainFolder> selectedFolders;
JavaScript
mit
355ac6c2525635931385ab5f88b3fb69a01b0f4d
0
danheadforcode/fg-gatsby
import React from 'react' import { Link } from 'react-router' import { prefixLink } from 'gatsby-helpers' import Helmet from 'react-helmet' import { config } from 'config' export default class Index extends React.Component { render() { return ( <div> <h1> Hi Daniel </h1> <p>Welcome to your new Gatsby site.</p> <p>Now go build something great.</p> <Link to={prefixLink('/page-2/')}>Go to page 2</Link> </div> ) } }
pages/index.js
import React from 'react' import { Link } from 'react-router' import { prefixLink } from 'gatsby-helpers' import Helmet from 'react-helmet' import { config } from 'config' export default class Index extends React.Component { render() { return ( <div> <h1> Hi Dan </h1> <p>Welcome to your new Gatsby site.</p> <p>Now go build something great.</p> <Link to={prefixLink('/page-2/')}>Go to page 2</Link> </div> ) } }
changed greeting
pages/index.js
changed greeting
<ide><path>ages/index.js <ide> return ( <ide> <div> <ide> <h1> <del> Hi Dan <add> Hi Daniel <ide> </h1> <ide> <p>Welcome to your new Gatsby site.</p> <ide> <p>Now go build something great.</p>
Java
lgpl-2.1
f6a9c1a469208e8aad7c8a9793c93f0c06f469cd
0
xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * 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 com.xpn.xwiki.plugin; import java.util.ArrayList; import java.util.List; import java.util.Vector; import org.apache.commons.lang.StringUtils; import org.apache.ecs.filter.CharacterFilter; import org.xwiki.bridge.event.DocumentCreatedEvent; import org.xwiki.bridge.event.DocumentUpdatedEvent; import org.xwiki.model.reference.DocumentReference; import org.xwiki.observation.EventListener; import org.xwiki.observation.ObservationManager; import org.xwiki.observation.event.Event; import com.xpn.xwiki.XWiki; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.objects.StringProperty; import com.xpn.xwiki.render.WikiSubstitution; import com.xpn.xwiki.util.Util; import com.xpn.xwiki.web.Utils; public class PatternPlugin extends XWikiDefaultPlugin implements EventListener { Vector<String> patterns = new Vector<String>(); Vector<String> results = new Vector<String>(); Vector<String> descriptions = new Vector<String>(); WikiSubstitution patternListSubstitution; private static final List<Event> EVENTS = new ArrayList<Event>() { { add(new DocumentCreatedEvent(new DocumentReference("xwiki", "Plugins", "PatternPlugin"))); add(new DocumentUpdatedEvent(new DocumentReference("xwiki", "Plugins", "PatternPlugin"))); } }; public PatternPlugin(String name, String className, XWikiContext context) { super(name, className, context); init(context); // register for any modifications of the Plugins.PatternPlugin document.. Utils.getComponent(ObservationManager.class).addListener(this); } public List<Event> getEvents() { return EVENTS; } @Override public void init(XWikiContext context) { XWiki xwiki = context.getWiki(); try { this.patterns.clear(); this.results.clear(); this.descriptions.clear(); XWikiDocument pattern_doc = xwiki.getDocument("Plugins", "PatternPlugin", context); Vector<BaseObject> patternlist = pattern_doc.getObjects("Plugins.PatternPlugin"); if (patternlist != null) { for (BaseObject obj : patternlist) { if (obj == null) { continue; } this.patterns.add(((StringProperty) obj.get("pattern")).getValue().toString()); this.results.add(((StringProperty) obj.get("result")).getValue().toString()); this.descriptions.add(((StringProperty) obj.get("description")).getValue().toString()); } } } catch (Exception e) { e.printStackTrace(); } this.patternListSubstitution = new WikiSubstitution(context.getUtil(), "%PATTERNS%"); // Add a notification rule if the preference property plugin is modified } public void addPattern(String pattern, String result, String description) { this.patterns.add(pattern); this.results.add(result); this.descriptions.add(description); } public String getPatternList() { CharacterFilter filter = new CharacterFilter(); StringBuffer list = new StringBuffer(); list.append("{pre}\n"); list.append("<table border=1>"); list.append("<tr><td><strong>Pattern</strong></td>"); list.append("<td><strong>Result</strong></td><td><strong>Description</strong></td></tr>"); for (int i = 0; i < this.patterns.size(); i++) { list.append("<tr><td>"); list.append(filter.process(this.patterns.get(i))); list.append("</td><td>"); list.append(filter.process(this.results.get(i))); list.append("</td><td>"); list.append(this.descriptions.get(i)); list.append("</td></tr>"); } list.append("</table>"); list.append("\n{/pre}"); return list.toString(); } @Override public String commonTagsHandler(String line, XWikiContext context) { String subst = getPatternList(); subst = StringUtils.replace(subst, "$", "\\$"); this.patternListSubstitution.setSubstitution(subst); line = this.patternListSubstitution.substitute(line); return line; } @Override public String startRenderingHandler(String line, XWikiContext context) { return line; } @Override public String outsidePREHandler(String line, XWikiContext context) { Util util = context.getUtil(); for (int i = 0; i < this.patterns.size(); i++) { String pattern = this.patterns.get(i); String result = this.results.get(i); try { if (pattern.startsWith("s/")) { line = util.substitute(pattern, line); } else { line = StringUtils.replace(line, " " + pattern, " " + result); } } catch (Exception e) { // Log a error but do not fail.. } } return line; } @Override public String insidePREHandler(String line, XWikiContext context) { return line; } @Override public String endRenderingHandler(String line, XWikiContext context) { return line; } /** * {@inheritDoc} * * @see org.xwiki.observation.EventListener#onEvent(org.xwiki.observation.event.Event, java.lang.Object, * java.lang.Object) */ public void onEvent(Event event, Object source, Object data) { // If the PatternPlugin document has been modified we need to reload the patterns init((XWikiContext) data); } }
xwiki-core/src/main/java/com/xpn/xwiki/plugin/PatternPlugin.java
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * 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 com.xpn.xwiki.plugin; import java.util.ArrayList; import java.util.List; import java.util.Vector; import org.apache.commons.lang.StringUtils; import org.apache.ecs.filter.CharacterFilter; import org.xwiki.bridge.event.DocumentCreatedEvent; import org.xwiki.bridge.event.DocumentUpdatedEvent; import org.xwiki.model.reference.DocumentReference; import org.xwiki.observation.EventListener; import org.xwiki.observation.ObservationManager; import org.xwiki.observation.event.Event; import com.xpn.xwiki.XWiki; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.objects.StringProperty; import com.xpn.xwiki.render.WikiSubstitution; import com.xpn.xwiki.util.Util; import com.xpn.xwiki.web.Utils; public class PatternPlugin extends XWikiDefaultPlugin implements EventListener { Vector<String> patterns = new Vector<String>(); Vector<String> results = new Vector<String>(); Vector<String> descriptions = new Vector<String>(); WikiSubstitution patternListSubstitution; private static final List<Event> EVENTS = new ArrayList<Event>() { { add(new DocumentCreatedEvent(new DocumentReference("xwiki", "Plugins", "PatternPlugin"))); add(new DocumentUpdatedEvent(new DocumentReference("xwiki", "Plugins", "PatternPlugin"))); } }; public PatternPlugin(String name, String className, XWikiContext context) { super(name, className, context); init(context); // register for any modifications of the Plugins.PatternPlugin document.. Utils.getComponent(ObservationManager.class).addListener(this); } public List<Event> getEvents() { return EVENTS; } public void init(XWikiContext context) { XWiki xwiki = context.getWiki(); try { patterns.clear(); results.clear(); descriptions.clear(); XWikiDocument pattern_doc = xwiki.getDocument("Plugins", "PatternPlugin", context); Vector<BaseObject> patternlist = pattern_doc.getObjects("Plugins.PatternPlugin"); if (patternlist != null) { for (BaseObject obj : patternlist) { if (obj == null) { continue; } patterns.add(((StringProperty) obj.get("pattern")).getValue().toString()); results.add(((StringProperty) obj.get("result")).getValue().toString()); descriptions.add(((StringProperty) obj.get("description")).getValue().toString()); } } } catch (Exception e) { e.printStackTrace(); } patternListSubstitution = new WikiSubstitution(context.getUtil(), "%PATTERNS%"); // Add a notification rule if the preference property plugin is modified } public void addPattern(String pattern, String result, String description) { patterns.add(pattern); results.add(result); descriptions.add(description); } public String getPatternList() { CharacterFilter filter = new CharacterFilter(); StringBuffer list = new StringBuffer(); list.append("{pre}\n"); list.append("<table border=1>"); list.append("<tr><td><strong>Pattern</strong></td>"); list.append("<td><strong>Result</strong></td><td><strong>Description</strong></td></tr>"); for (int i = 0; i < patterns.size(); i++) { list.append("<tr><td>"); list.append(filter.process(patterns.get(i))); list.append("</td><td>"); list.append(filter.process(results.get(i))); list.append("</td><td>"); list.append(descriptions.get(i)); list.append("</td></tr>"); } list.append("</table>"); list.append("\n{/pre}"); return list.toString(); } public String commonTagsHandler(String line, XWikiContext context) { String subst = getPatternList(); subst = StringUtils.replace(subst, "$", "\\$"); patternListSubstitution.setSubstitution(subst); line = patternListSubstitution.substitute(line); return line; } public String startRenderingHandler(String line, XWikiContext context) { return line; } public String outsidePREHandler(String line, XWikiContext context) { Util util = context.getUtil(); for (int i = 0; i < patterns.size(); i++) { String pattern = patterns.get(i); String result = results.get(i); try { if (pattern.startsWith("s/")) line = util.substitute(pattern, line); else line = StringUtils.replace(line, " " + pattern, " " + result); } catch (Exception e) { // Log a error but do not fail.. } } return line; } public String insidePREHandler(String line, XWikiContext context) { return line; } public String endRenderingHandler(String line, XWikiContext context) { return line; } /** * {@inheritDoc} * * @see org.xwiki.observation.EventListener#onEvent(org.xwiki.observation.event.Event, java.lang.Object, * java.lang.Object) */ public void onEvent(Event event, Object source, Object data) { // If the PatternPlugin document has been modified we need to reload the patterns init((XWikiContext) data); } }
[cleanup] Applied codestyle git-svn-id: d23d7a6431d93e1bdd218a46658458610974b053@34417 f329d543-caf0-0310-9063-dda96c69346f
xwiki-core/src/main/java/com/xpn/xwiki/plugin/PatternPlugin.java
[cleanup] Applied codestyle
<ide><path>wiki-core/src/main/java/com/xpn/xwiki/plugin/PatternPlugin.java <ide> * 02110-1301 USA, or see the FSF site: http://www.fsf.org. <ide> * <ide> */ <del> <ide> package com.xpn.xwiki.plugin; <ide> <ide> import java.util.ArrayList; <ide> return EVENTS; <ide> } <ide> <add> @Override <ide> public void init(XWikiContext context) <ide> { <ide> XWiki xwiki = context.getWiki(); <ide> try { <del> patterns.clear(); <del> results.clear(); <del> descriptions.clear(); <add> this.patterns.clear(); <add> this.results.clear(); <add> this.descriptions.clear(); <ide> XWikiDocument pattern_doc = xwiki.getDocument("Plugins", "PatternPlugin", context); <ide> Vector<BaseObject> patternlist = pattern_doc.getObjects("Plugins.PatternPlugin"); <ide> if (patternlist != null) { <ide> if (obj == null) { <ide> continue; <ide> } <del> patterns.add(((StringProperty) obj.get("pattern")).getValue().toString()); <del> results.add(((StringProperty) obj.get("result")).getValue().toString()); <del> descriptions.add(((StringProperty) obj.get("description")).getValue().toString()); <add> this.patterns.add(((StringProperty) obj.get("pattern")).getValue().toString()); <add> this.results.add(((StringProperty) obj.get("result")).getValue().toString()); <add> this.descriptions.add(((StringProperty) obj.get("description")).getValue().toString()); <ide> } <ide> } <ide> } catch (Exception e) { <ide> e.printStackTrace(); <ide> } <ide> <del> patternListSubstitution = new WikiSubstitution(context.getUtil(), "%PATTERNS%"); <add> this.patternListSubstitution = new WikiSubstitution(context.getUtil(), "%PATTERNS%"); <ide> // Add a notification rule if the preference property plugin is modified <ide> } <ide> <ide> public void addPattern(String pattern, String result, String description) <ide> { <del> patterns.add(pattern); <del> results.add(result); <del> descriptions.add(description); <add> this.patterns.add(pattern); <add> this.results.add(result); <add> this.descriptions.add(description); <ide> } <ide> <ide> public String getPatternList() <ide> list.append("<table border=1>"); <ide> list.append("<tr><td><strong>Pattern</strong></td>"); <ide> list.append("<td><strong>Result</strong></td><td><strong>Description</strong></td></tr>"); <del> for (int i = 0; i < patterns.size(); i++) { <add> for (int i = 0; i < this.patterns.size(); i++) { <ide> list.append("<tr><td>"); <del> list.append(filter.process(patterns.get(i))); <add> list.append(filter.process(this.patterns.get(i))); <ide> list.append("</td><td>"); <del> list.append(filter.process(results.get(i))); <add> list.append(filter.process(this.results.get(i))); <ide> list.append("</td><td>"); <del> list.append(descriptions.get(i)); <add> list.append(this.descriptions.get(i)); <ide> list.append("</td></tr>"); <ide> } <ide> list.append("</table>"); <ide> return list.toString(); <ide> } <ide> <add> @Override <ide> public String commonTagsHandler(String line, XWikiContext context) <ide> { <ide> String subst = getPatternList(); <ide> subst = StringUtils.replace(subst, "$", "\\$"); <del> patternListSubstitution.setSubstitution(subst); <del> line = patternListSubstitution.substitute(line); <add> this.patternListSubstitution.setSubstitution(subst); <add> line = this.patternListSubstitution.substitute(line); <ide> return line; <ide> } <ide> <add> @Override <ide> public String startRenderingHandler(String line, XWikiContext context) <ide> { <ide> return line; <ide> } <ide> <add> @Override <ide> public String outsidePREHandler(String line, XWikiContext context) <ide> { <ide> Util util = context.getUtil(); <ide> <del> for (int i = 0; i < patterns.size(); i++) { <del> String pattern = patterns.get(i); <del> String result = results.get(i); <add> for (int i = 0; i < this.patterns.size(); i++) { <add> String pattern = this.patterns.get(i); <add> String result = this.results.get(i); <ide> try { <del> if (pattern.startsWith("s/")) <add> if (pattern.startsWith("s/")) { <ide> line = util.substitute(pattern, line); <del> else <add> } else { <ide> line = StringUtils.replace(line, " " + pattern, " " + result); <add> } <ide> } catch (Exception e) { <ide> // Log a error but do not fail.. <ide> } <ide> return line; <ide> } <ide> <add> @Override <ide> public String insidePREHandler(String line, XWikiContext context) <ide> { <ide> return line; <ide> } <ide> <add> @Override <ide> public String endRenderingHandler(String line, XWikiContext context) <ide> { <ide> return line;
Java
apache-2.0
df9eef889376ab4b67ac7917fef4e6d420f16531
0
ftomassetti/intellij-community,ibinti/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,joewalnes/idea-community,Lekanich/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,da1z/intellij-community,consulo/consulo,xfournet/intellij-community,kdwink/intellij-community,ryano144/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,clumsy/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,kool79/intellij-community,apixandru/intellij-community,asedunov/intellij-community,hurricup/intellij-community,semonte/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,vladmm/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,holmes/intellij-community,robovm/robovm-studio,supersven/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,jagguli/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,semonte/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,kdwink/intellij-community,joewalnes/idea-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,kool79/intellij-community,fitermay/intellij-community,samthor/intellij-community,izonder/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,kool79/intellij-community,asedunov/intellij-community,blademainer/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,joewalnes/idea-community,FHannes/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,da1z/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,signed/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,ryano144/intellij-community,allotria/intellij-community,kool79/intellij-community,da1z/intellij-community,blademainer/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,signed/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,caot/intellij-community,Distrotech/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,retomerz/intellij-community,slisson/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,joewalnes/idea-community,samthor/intellij-community,kdwink/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,supersven/intellij-community,jagguli/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,allotria/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,caot/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,consulo/consulo,salguarnieri/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,joewalnes/idea-community,Distrotech/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,FHannes/intellij-community,clumsy/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,slisson/intellij-community,joewalnes/idea-community,lucafavatella/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,consulo/consulo,mglukhikh/intellij-community,fnouama/intellij-community,samthor/intellij-community,retomerz/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,caot/intellij-community,adedayo/intellij-community,signed/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,joewalnes/idea-community,apixandru/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,robovm/robovm-studio,slisson/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,robovm/robovm-studio,FHannes/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,retomerz/intellij-community,da1z/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,da1z/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,kool79/intellij-community,kdwink/intellij-community,signed/intellij-community,petteyg/intellij-community,FHannes/intellij-community,slisson/intellij-community,fnouama/intellij-community,semonte/intellij-community,hurricup/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,signed/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,blademainer/intellij-community,izonder/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,ernestp/consulo,joewalnes/idea-community,orekyuu/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,consulo/consulo,vvv1559/intellij-community,xfournet/intellij-community,apixandru/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,izonder/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,signed/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,diorcety/intellij-community,semonte/intellij-community,hurricup/intellij-community,izonder/intellij-community,supersven/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,joewalnes/idea-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,supersven/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,fnouama/intellij-community,holmes/intellij-community,tmpgit/intellij-community,signed/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,kool79/intellij-community,hurricup/intellij-community,supersven/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,izonder/intellij-community,da1z/intellij-community,ernestp/consulo,supersven/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,izonder/intellij-community,diorcety/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,signed/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,FHannes/intellij-community,amith01994/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,MER-GROUP/intellij-community,clumsy/intellij-community,consulo/consulo,jagguli/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,izonder/intellij-community,allotria/intellij-community,apixandru/intellij-community,supersven/intellij-community,blademainer/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,petteyg/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,allotria/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,fnouama/intellij-community,consulo/consulo,ivan-fedorov/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,ernestp/consulo,xfournet/intellij-community,fnouama/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,samthor/intellij-community,ahb0327/intellij-community,da1z/intellij-community,supersven/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,holmes/intellij-community,allotria/intellij-community,semonte/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,ibinti/intellij-community,robovm/robovm-studio,ernestp/consulo,da1z/intellij-community,petteyg/intellij-community,hurricup/intellij-community,robovm/robovm-studio,asedunov/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,kool79/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,izonder/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,caot/intellij-community,apixandru/intellij-community,slisson/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,fitermay/intellij-community,retomerz/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,caot/intellij-community,ahb0327/intellij-community,da1z/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,caot/intellij-community,fitermay/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,caot/intellij-community,fitermay/intellij-community,clumsy/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,fnouama/intellij-community,allotria/intellij-community,slisson/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,da1z/intellij-community,vladmm/intellij-community,vladmm/intellij-community,ol-loginov/intellij-community,caot/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,slisson/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,fnouama/intellij-community,adedayo/intellij-community,apixandru/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,fitermay/intellij-community,ernestp/consulo,holmes/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,kool79/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,blademainer/intellij-community,dslomov/intellij-community,kool79/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,diorcety/intellij-community,ernestp/consulo,xfournet/intellij-community,vvv1559/intellij-community,da1z/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,hurricup/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,izonder/intellij-community,holmes/intellij-community,Lekanich/intellij-community,caot/intellij-community,asedunov/intellij-community,ibinti/intellij-community,vladmm/intellij-community,slisson/intellij-community,kdwink/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,allotria/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,semonte/intellij-community,nicolargo/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.openapi.wm.impl.status; import com.intellij.concurrency.JobScheduler; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.wm.CustomStatusBarWidget; import com.intellij.openapi.wm.StatusBar; import com.intellij.openapi.wm.StatusBarWidget; import com.intellij.ui.UIBundle; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; public class MemoryUsagePanel extends JButton implements CustomStatusBarWidget { @NonNls private static final String SAMPLE_STRING = "0000M of 0000M"; private static final int MEGABYTE = 1024 * 1024; private static final Color ourColorFree = new Color(240, 240, 240); private static final Color ourColorUsed = new Color(112, 135, 214); private static final Color ourColorUsed2 = new Color(166, 181, 230); private static final int HEIGHT = 16; private long myLastTotal = -1; private long myLastUsed = -1; private ScheduledFuture<?> myFuture; private BufferedImage myBufferedImage; private boolean myWasPressed; public MemoryUsagePanel() { setOpaque(false); addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.gc(); updateState(); } }); setBorder(StatusBarWidget.WidgetBorder.INSTANCE); updateUI(); } public void dispose() { myFuture.cancel(true); myFuture = null; } public void install(@NotNull StatusBar statusBar) { } @Nullable public WidgetPresentation getPresentation(@NotNull PlatformType type) { return null; } @NotNull public String ID() { return "Memory"; } public void setShowing(final boolean showing) { if (showing && !isVisible()) { setVisible(true); revalidate(); } else if (!showing && isVisible()) { setVisible(showing); revalidate(); } } @Override public void updateUI() { super.updateUI(); setFont(SystemInfo.isMac ? UIUtil.getLabelFont().deriveFont(11.0f) : UIUtil.getLabelFont()); } public JComponent getComponent() { return this; } @Override public void paintComponent(final Graphics g) { final Dimension size = getSize(); final boolean pressed = getModel().isPressed(); final boolean forced = myWasPressed && !pressed || !myWasPressed && pressed; myWasPressed = pressed; if (myBufferedImage == null || forced) { myBufferedImage = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB); final Graphics bg = myBufferedImage.getGraphics().create(); final Runtime runtime = Runtime.getRuntime(); final long maxMemory = runtime.maxMemory(); final long freeMemory = maxMemory - runtime.totalMemory() + runtime.freeMemory(); final Insets insets = SystemInfo.isMac ? getInsets() : new Insets(0, 0, 0, 0); final int totalBarLength = size.width - insets.left - insets.right - (SystemInfo.isMac ? 0 : 0); final int usedBarLength = totalBarLength - (int)(totalBarLength * freeMemory / maxMemory); final int allocatedBarWidth = totalBarLength - (int)(totalBarLength * (freeMemory - runtime.freeMemory()) / maxMemory); final int barHeight = SystemInfo.isMac ? HEIGHT : size.height - insets.top - insets.bottom; final Graphics2D g2 = (Graphics2D)bg; final int yOffset = (size.height - barHeight) / 2; final int xOffset = insets.left + (SystemInfo.isMac ? 0 : 0); g2.setPaint(new GradientPaint(0, 0, new Color(190, 190, 190), 0, size.height - 1, new Color(230, 230, 230))); g2.fillRect(xOffset, yOffset, totalBarLength, barHeight); g2.setPaint(new GradientPaint(0, 0, new Color(200, 200, 200, 100), 0, size.height - 1, new Color(150, 150, 150, 130))); g2.fillRect(xOffset + 1, yOffset, allocatedBarWidth, barHeight); g2.setColor(new Color(175, 175, 175)); g2.drawLine(xOffset + allocatedBarWidth, yOffset + 1, xOffset + allocatedBarWidth, yOffset + barHeight - 1); if (pressed) { g2.setPaint(new GradientPaint(1, 1, new Color(101, 111, 135), 0, size.height - 2, new Color(175, 185, 202))); g2.fillRect(xOffset + 1, yOffset, usedBarLength, barHeight); } else { g2.setPaint(new GradientPaint(1, 1, new Color(175, 185, 202), 0, size.height - 2, new Color(126, 138, 168))); g2.fillRect(xOffset + 1, yOffset, usedBarLength, barHeight); if (SystemInfo.isMac) { g2.setColor(new Color(194, 197, 203)); g2.drawLine(xOffset + 1, yOffset+1, allocatedBarWidth, yOffset+1); } } if (SystemInfo.isMac) { g2.setColor(new Color(110, 110, 110)); g2.drawRect(xOffset, yOffset, totalBarLength, barHeight - 1); } g2.setFont(getFont()); final long used = (maxMemory - freeMemory) / MEGABYTE; final long total = maxMemory / MEGABYTE; final String info = UIBundle.message("memory.usage.panel.message.text", Long.toString(used), Long.toString(total)); final FontMetrics fontMetrics = g.getFontMetrics(); final int infoWidth = fontMetrics.charsWidth(info.toCharArray(), 0, info.length()); final int infoHeight = fontMetrics.getHeight() - fontMetrics.getDescent(); UIUtil.applyRenderingHints(g2); g2.setColor(Color.black); g2.drawString(info, xOffset + (totalBarLength - infoWidth) / 2, yOffset + (barHeight + infoHeight) / 2 - 1); bg.dispose(); } g.drawImage(myBufferedImage, 0, 0, null); } public final int getPreferredWidth() { final Insets insets = getInsets(); return getFontMetrics(SystemInfo.isMac ? UIUtil.getLabelFont().deriveFont(11.0f) : UIUtil.getLabelFont()).stringWidth(SAMPLE_STRING) + insets.left + insets.right + (SystemInfo.isMac ? 2 : 0); } @Override public Dimension getPreferredSize() { return new Dimension(getPreferredWidth(), Integer.MAX_VALUE); } @Override public Dimension getMaximumSize() { return getPreferredSize(); } /** * Invoked when enclosed frame is being shown. */ public void addNotify() { myFuture = JobScheduler.getScheduler().scheduleAtFixedRate(new Runnable() { public void run() { SwingUtilities.invokeLater(new Runnable() { public void run() { if (!isDisplayable()) return; // This runnable may be posted in event queue while calling removeNotify. updateState(); } }); } }, 1, 5, TimeUnit.SECONDS); super.addNotify(); } private void updateState() { if (!isShowing()) { return; } final Runtime runtime = Runtime.getRuntime(); final long total = runtime.totalMemory() / MEGABYTE; final long used = total - runtime.freeMemory() / MEGABYTE; if (total != myLastTotal || used != myLastUsed) { myLastTotal = total; myLastUsed = used; SwingUtilities.invokeLater(new Runnable() { public void run() { myBufferedImage = null; repaint(); } }); setToolTipText(UIBundle.message("memory.usage.panel.statistics.message", total, used)); } } }
platform/platform-impl/src/com/intellij/openapi/wm/impl/status/MemoryUsagePanel.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.openapi.wm.impl.status; import com.intellij.concurrency.JobScheduler; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.wm.CustomStatusBarWidget; import com.intellij.openapi.wm.StatusBar; import com.intellij.openapi.wm.StatusBarWidget; import com.intellij.ui.UIBundle; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; public class MemoryUsagePanel extends JButton implements CustomStatusBarWidget { @NonNls private static final String SAMPLE_STRING = "0000M of 0000M"; private static final int MEGABYTE = 1024 * 1024; private static final Color ourColorFree = new Color(240, 240, 240); private static final Color ourColorUsed = new Color(112, 135, 214); private static final Color ourColorUsed2 = new Color(166, 181, 230); private static final int HEIGHT = 16; private long myLastTotal = -1; private long myLastUsed = -1; private ScheduledFuture<?> myFuture; private BufferedImage myBufferedImage; private boolean myWasPressed; public MemoryUsagePanel() { setOpaque(false); addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.gc(); updateState(); } }); setBorder(StatusBarWidget.WidgetBorder.INSTANCE); updateUI(); } public void dispose() { myFuture.cancel(true); myFuture = null; } public void install(@NotNull StatusBar statusBar) { } @Nullable public WidgetPresentation getPresentation(@NotNull PlatformType type) { return null; } @NotNull public String ID() { return "Memory"; } public void setShowing(final boolean showing) { if (showing && !isVisible()) { setVisible(true); revalidate(); } else if (!showing && isVisible()) { setVisible(showing); revalidate(); } } @Override public void updateUI() { super.updateUI(); setFont(SystemInfo.isMac ? UIUtil.getLabelFont().deriveFont(11.0f) : UIUtil.getLabelFont()); } public JComponent getComponent() { return this; } @Override public void paintComponent(final Graphics g) { final Dimension size = getSize(); final boolean pressed = getModel().isPressed(); final boolean forced = myWasPressed && !pressed || !myWasPressed && pressed; myWasPressed = pressed; if (myBufferedImage == null || forced) { myBufferedImage = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB); final Graphics bg = myBufferedImage.getGraphics().create(); final Runtime runtime = Runtime.getRuntime(); final long maxMemory = runtime.maxMemory(); final long freeMemory = maxMemory - runtime.totalMemory() + runtime.freeMemory(); final Insets insets = SystemInfo.isMac ? getInsets() : new Insets(0, 0, 0, 0); final int totalBarLength = size.width - insets.left - insets.right - (SystemInfo.isMac ? 0 : 0); final int usedBarLength = totalBarLength - (int)(totalBarLength * freeMemory / maxMemory); final int allocatedBarWidth = totalBarLength - (int)(totalBarLength * (freeMemory - runtime.freeMemory()) / maxMemory); final int barHeight = SystemInfo.isMac ? HEIGHT : size.height - insets.top - insets.bottom; final Graphics2D g2 = (Graphics2D)bg; final int yOffset = (size.height - barHeight) / 2; final int xOffset = insets.left + (SystemInfo.isMac ? 0 : 0); g2.setPaint(new GradientPaint(0, 0, new Color(190, 190, 190), 0, size.height - 1, new Color(230, 230, 230))); g2.fillRect(xOffset, yOffset, totalBarLength, barHeight); g2.setPaint(new GradientPaint(0, 0, new Color(200, 200, 200, 100), 0, size.height - 1, new Color(150, 150, 150, 130))); g2.fillRect(xOffset + 1, yOffset, allocatedBarWidth, barHeight); g2.setColor(new Color(175, 175, 175)); g2.drawLine(xOffset + allocatedBarWidth, yOffset + 1, xOffset + allocatedBarWidth, yOffset + barHeight - 1); if (pressed) { g2.setPaint(new GradientPaint(1, 1, new Color(101, 111, 135), 0, size.height - 2, new Color(175, 185, 202))); g2.fillRect(xOffset + 1, yOffset, usedBarLength, barHeight); } else { g2.setPaint(new GradientPaint(1, 1, new Color(175, 185, 202), 0, size.height - 2, new Color(126, 138, 168))); g2.fillRect(xOffset + 1, yOffset, usedBarLength, barHeight); if (SystemInfo.isMac) { g2.setColor(new Color(194, 197, 203)); g2.drawLine(xOffset + 1, yOffset+1, allocatedBarWidth, yOffset+1); } } if (SystemInfo.isMac) { g2.setColor(new Color(110, 110, 110)); g2.drawRect(xOffset, yOffset, totalBarLength, barHeight - 1); } g2.setFont(getFont()); final long used = (maxMemory - freeMemory) / MEGABYTE; final long total = maxMemory / MEGABYTE; final String info = UIBundle.message("memory.usage.panel.message.text", Long.toString(used), Long.toString(total)); final FontMetrics fontMetrics = g.getFontMetrics(); final int infoWidth = fontMetrics.charsWidth(info.toCharArray(), 0, info.length()); final int infoHeight = fontMetrics.getHeight() - fontMetrics.getDescent(); UIUtil.applyRenderingHints(g); g2.setColor(Color.black); g2.drawString(info, xOffset + (totalBarLength - infoWidth) / 2, yOffset + (barHeight + infoHeight) / 2 - 1); bg.dispose(); } g.drawImage(myBufferedImage, 0, 0, null); } public final int getPreferredWidth() { final Insets insets = getInsets(); return getFontMetrics(SystemInfo.isMac ? UIUtil.getLabelFont().deriveFont(11.0f) : UIUtil.getLabelFont()).stringWidth(SAMPLE_STRING) + insets.left + insets.right + (SystemInfo.isMac ? 2 : 0); } @Override public Dimension getPreferredSize() { return new Dimension(getPreferredWidth(), Integer.MAX_VALUE); } @Override public Dimension getMaximumSize() { return getPreferredSize(); } /** * Invoked when enclosed frame is being shown. */ public void addNotify() { myFuture = JobScheduler.getScheduler().scheduleAtFixedRate(new Runnable() { public void run() { SwingUtilities.invokeLater(new Runnable() { public void run() { if (!isDisplayable()) return; // This runnable may be posted in event queue while calling removeNotify. updateState(); } }); } }, 1, 5, TimeUnit.SECONDS); super.addNotify(); } private void updateState() { if (!isShowing()) { return; } final Runtime runtime = Runtime.getRuntime(); final long total = runtime.totalMemory() / MEGABYTE; final long used = total - runtime.freeMemory() / MEGABYTE; if (total != myLastTotal || used != myLastUsed) { myLastTotal = total; myLastUsed = used; SwingUtilities.invokeLater(new Runnable() { public void run() { myBufferedImage = null; repaint(); } }); setToolTipText(UIBundle.message("memory.usage.panel.statistics.message", total, used)); } } }
memory usage panel antialiasing fix
platform/platform-impl/src/com/intellij/openapi/wm/impl/status/MemoryUsagePanel.java
memory usage panel antialiasing fix
<ide><path>latform/platform-impl/src/com/intellij/openapi/wm/impl/status/MemoryUsagePanel.java <ide> final FontMetrics fontMetrics = g.getFontMetrics(); <ide> final int infoWidth = fontMetrics.charsWidth(info.toCharArray(), 0, info.length()); <ide> final int infoHeight = fontMetrics.getHeight() - fontMetrics.getDescent(); <del> UIUtil.applyRenderingHints(g); <add> UIUtil.applyRenderingHints(g2); <ide> <ide> g2.setColor(Color.black); <ide> g2.drawString(info, xOffset + (totalBarLength - infoWidth) / 2, yOffset + (barHeight + infoHeight) / 2 - 1);
Java
apache-2.0
960066cd9023da6f781027f275d97975cbdf5873
0
signed/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,diorcety/intellij-community,caot/intellij-community,ryano144/intellij-community,clumsy/intellij-community,consulo/consulo,pwoodworth/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,retomerz/intellij-community,fitermay/intellij-community,kdwink/intellij-community,signed/intellij-community,da1z/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,diorcety/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,ernestp/consulo,suncycheng/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,FHannes/intellij-community,samthor/intellij-community,adedayo/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,amith01994/intellij-community,allotria/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,izonder/intellij-community,kool79/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,joewalnes/idea-community,ol-loginov/intellij-community,semonte/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,allotria/intellij-community,robovm/robovm-studio,semonte/intellij-community,caot/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,caot/intellij-community,petteyg/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,fnouama/intellij-community,signed/intellij-community,petteyg/intellij-community,supersven/intellij-community,da1z/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,consulo/consulo,amith01994/intellij-community,dslomov/intellij-community,slisson/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,xfournet/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,semonte/intellij-community,youdonghai/intellij-community,caot/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,hurricup/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,izonder/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,joewalnes/idea-community,Lekanich/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,vladmm/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,samthor/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,joewalnes/idea-community,izonder/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,asedunov/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,jagguli/intellij-community,samthor/intellij-community,holmes/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,consulo/consulo,orekyuu/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,robovm/robovm-studio,ryano144/intellij-community,ibinti/intellij-community,caot/intellij-community,dslomov/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,semonte/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,signed/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,blademainer/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,fnouama/intellij-community,izonder/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,FHannes/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,jagguli/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,slisson/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,consulo/consulo,apixandru/intellij-community,hurricup/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,supersven/intellij-community,FHannes/intellij-community,petteyg/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,da1z/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,caot/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,izonder/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,blademainer/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,clumsy/intellij-community,hurricup/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,caot/intellij-community,adedayo/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,fitermay/intellij-community,retomerz/intellij-community,holmes/intellij-community,blademainer/intellij-community,joewalnes/idea-community,alphafoobar/intellij-community,FHannes/intellij-community,apixandru/intellij-community,semonte/intellij-community,fitermay/intellij-community,clumsy/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,xfournet/intellij-community,fitermay/intellij-community,fnouama/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,izonder/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,semonte/intellij-community,MichaelNedzelsky/intellij-community,joewalnes/idea-community,ryano144/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,clumsy/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,jagguli/intellij-community,samthor/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,clumsy/intellij-community,kool79/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,da1z/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,signed/intellij-community,diorcety/intellij-community,semonte/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,signed/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,slisson/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,fitermay/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,kool79/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,ernestp/consulo,petteyg/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,kdwink/intellij-community,blademainer/intellij-community,dslomov/intellij-community,ernestp/consulo,SerCeMan/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,signed/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,da1z/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,dslomov/intellij-community,amith01994/intellij-community,adedayo/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,supersven/intellij-community,adedayo/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,apixandru/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,supersven/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,supersven/intellij-community,ibinti/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,signed/intellij-community,adedayo/intellij-community,supersven/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,signed/intellij-community,retomerz/intellij-community,adedayo/intellij-community,hurricup/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,samthor/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,apixandru/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,da1z/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,samthor/intellij-community,samthor/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,signed/intellij-community,consulo/consulo,apixandru/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,FHannes/intellij-community,samthor/intellij-community,wreckJ/intellij-community,slisson/intellij-community,robovm/robovm-studio,apixandru/intellij-community,hurricup/intellij-community,retomerz/intellij-community,kool79/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,kool79/intellij-community,amith01994/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,ibinti/intellij-community,da1z/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,hurricup/intellij-community,asedunov/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,FHannes/intellij-community,ryano144/intellij-community,holmes/intellij-community,clumsy/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,allotria/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,joewalnes/idea-community,ol-loginov/intellij-community,signed/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,joewalnes/idea-community,retomerz/intellij-community,caot/intellij-community,orekyuu/intellij-community,semonte/intellij-community,FHannes/intellij-community,joewalnes/idea-community,ibinti/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,da1z/intellij-community,semonte/intellij-community,semonte/intellij-community,izonder/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,caot/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,tmpgit/intellij-community,consulo/consulo,retomerz/intellij-community,ernestp/consulo,joewalnes/idea-community,salguarnieri/intellij-community,da1z/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,signed/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,ernestp/consulo,lucafavatella/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,kool79/intellij-community,allotria/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,ernestp/consulo,ftomassetti/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,hurricup/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.openapi.vfs.impl; import com.intellij.openapi.Disposable; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.UserDataHolderBase; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.pointers.VirtualFilePointer; import com.intellij.openapi.vfs.pointers.VirtualFilePointerListener; import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager; import com.intellij.util.PathUtil; import org.jetbrains.annotations.NotNull; import java.io.PrintStream; import java.io.PrintWriter; public class VirtualFilePointerImpl extends UserDataHolderBase implements VirtualFilePointer, Disposable { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vfs.impl.VirtualFilePointerImpl"); private Pair<VirtualFile, String> myFileAndUrl; // must not be both null private final VirtualFileManager myVirtualFileManager; private final VirtualFilePointerListener myListener; private boolean disposed = false; int useCount; private long myLastUpdated = -1; private static final Key<Throwable> CREATE_TRACE = Key.create("CREATION_TRACE"); private static final Key<Throwable> KILL_TRACE = Key.create("KILL_TRACE"); private static final boolean TRACE_CREATION = /*true || */LOG.isDebugEnabled(); VirtualFilePointerImpl(VirtualFile file, @NotNull String url, @NotNull VirtualFileManager virtualFileManager, VirtualFilePointerListener listener, @NotNull Disposable parentDisposable) { myFileAndUrl = Pair.create(file, url); myVirtualFileManager = virtualFileManager; myListener = listener; useCount = 0; if (TRACE_CREATION) { putUserData(CREATE_TRACE, new Throwable("parent = '"+parentDisposable+"' ("+parentDisposable.getClass()+")")); } } @NotNull public String getFileName() { Pair<VirtualFile, String> result = update(); if (result == null) { checkDisposed(); return ""; } VirtualFile file = result.first; if (file != null) { return file.getName(); } String url = result.second; int index = url.lastIndexOf('/'); return index >= 0 ? url.substring(index + 1) : url; } public VirtualFile getFile() { Pair<VirtualFile, String> result = update(); if (result == null) { checkDisposed(); return null; } return result.first; } @NotNull public String getUrl() { //checkDisposed(); no check here since Disposer might want to compute hashcode during dispose() update(); return getUrlNoUpdate(); } private String getUrlNoUpdate() { Pair<VirtualFile, String> fileAndUrl = myFileAndUrl; VirtualFile file = fileAndUrl.first; String url = fileAndUrl.second; return url == null ? file.getUrl() : url; } @NotNull public String getPresentableUrl() { checkDisposed(); return PathUtil.toPresentableUrl(getUrl()); } private void checkDisposed() { if (disposed) throw new MyException("Already disposed: "+toString(), getUserData(CREATE_TRACE), getUserData(KILL_TRACE)); } public void throwNotDisposedError(String msg) throws RuntimeException { Throwable trace = getUserData(CREATE_TRACE); throw new RuntimeException(msg+"\n" + "url=" + this + "\nCreation trace " + (trace==null?"null":"some")+ "\n", trace); } public int incrementUsageCount() { return ++useCount; } private static class MyException extends RuntimeException { private final Throwable e1; private final Throwable e2; private MyException(String message, Throwable e1, Throwable e2) { super(message); this.e1 = e1; this.e2 = e2; } @Override public void printStackTrace(PrintStream s) { printStackTrace(new PrintWriter(s)); } @Override public void printStackTrace(PrintWriter s) { super.printStackTrace(s); if (e1 != null) { s.println("--------------Creation trace: "); e1.printStackTrace(s); } if (e2 != null) { s.println("--------------Kill trace: "); e2.printStackTrace(s); } } } public boolean isValid() { Pair<VirtualFile, String> result = update(); return result != null && result.first != null; } Pair<VirtualFile, String> update() { if (disposed) return null; long lastUpdated = myLastUpdated; Pair<VirtualFile, String> fileAndUrl = myFileAndUrl; VirtualFile file = fileAndUrl.first; String url = fileAndUrl.second; long fsModCount = myVirtualFileManager.getModificationCount(); if (lastUpdated == fsModCount) return fileAndUrl; if (file != null && !file.isValid()) { url = file.getUrl(); file = null; } if (file == null) { LOG.assertTrue(url != null, "Both file & url are null"); file = myVirtualFileManager.findFileByUrl(url); if (file != null) { url = null; } } if (file != null && !file.exists()) { url = file.getUrl(); file = null; } Pair<VirtualFile, String> result = Pair.create(file, url); myFileAndUrl = result; myLastUpdated = fsModCount; return result; } @Override public String toString() { return getUrlNoUpdate(); } public void dispose() { if (disposed) { throw new MyException("Punching the dead horse.\nurl="+toString(), getUserData(CREATE_TRACE), getUserData(KILL_TRACE)); } if (--useCount == 0) { if (TRACE_CREATION) { putUserData(KILL_TRACE, new Throwable()); } String url = getUrlNoUpdate(); disposed = true; ((VirtualFilePointerManagerImpl)VirtualFilePointerManager.getInstance()).clearPointerCaches(url, myListener); } } public boolean isDisposed() { return disposed; } }
platform/platform-impl/src/com/intellij/openapi/vfs/impl/VirtualFilePointerImpl.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.openapi.vfs.impl; import com.intellij.openapi.Disposable; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.UserDataHolderBase; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.pointers.VirtualFilePointer; import com.intellij.openapi.vfs.pointers.VirtualFilePointerListener; import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager; import com.intellij.util.PathUtil; import org.jetbrains.annotations.NotNull; import java.io.PrintStream; import java.io.PrintWriter; public class VirtualFilePointerImpl extends UserDataHolderBase implements VirtualFilePointer, Disposable { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vfs.impl.VirtualFilePointerImpl"); private String myUrl; // is null when myFile is not null private VirtualFile myFile; private final VirtualFileManager myVirtualFileManager; private final VirtualFilePointerListener myListener; private boolean disposed = false; int useCount; private long myLastUpdated = -1; private static final Key<Throwable> CREATE_TRACE = Key.create("CREATION_TRACE"); private static final Key<Throwable> KILL_TRACE = Key.create("KILL_TRACE"); private static final boolean TRACE_CREATION = /*true || */LOG.isDebugEnabled(); VirtualFilePointerImpl(VirtualFile file, @NotNull String url, @NotNull VirtualFileManager virtualFileManager, VirtualFilePointerListener listener, @NotNull Disposable parentDisposable) { myFile = file; myUrl = url; myVirtualFileManager = virtualFileManager; myListener = listener; useCount = 0; if (TRACE_CREATION) { putUserData(CREATE_TRACE, new Throwable("parent = '"+parentDisposable+"' ("+parentDisposable.getClass()+")")); } } @NotNull public String getFileName() { Pair<VirtualFile, String> result = update(); VirtualFile file = result.first; if (file != null) { return file.getName(); } String url = result.second; int index = url.lastIndexOf('/'); return index >= 0 ? url.substring(index + 1) : url; } public VirtualFile getFile() { checkDisposed(); Pair<VirtualFile, String> result = update(); return result.first; } @NotNull public String getUrl() { //checkDisposed(); no check here since Disposer might want to compute hashcode during dispose() Pair<VirtualFile, String> result = update(); return getUrlNoUpdate(result.first, result.second); } private static String getUrlNoUpdate(VirtualFile file, String url) { return url == null ? file.getUrl() : url; } @NotNull public String getPresentableUrl() { checkDisposed(); return PathUtil.toPresentableUrl(getUrl()); } private void checkDisposed() { if (disposed) throw new MyException("Already disposed: "+toString(), getUserData(CREATE_TRACE), getUserData(KILL_TRACE)); } public void throwNotDisposedError(String msg) throws RuntimeException { Throwable trace = getUserData(CREATE_TRACE); throw new RuntimeException(msg+"\n" + "url=" + this + "\nCreation trace " + (trace==null?"null":"some")+ "\n", trace); } public int incrementUsageCount() { return ++useCount; } private static class MyException extends RuntimeException { private final Throwable e1; private final Throwable e2; private MyException(String message, Throwable e1, Throwable e2) { super(message); this.e1 = e1; this.e2 = e2; } @Override public void printStackTrace(PrintStream s) { printStackTrace(new PrintWriter(s)); } @Override public void printStackTrace(PrintWriter s) { super.printStackTrace(s); if (e1 != null) { s.println("--------------Creation trace: "); e1.printStackTrace(s); } if (e2 != null) { s.println("--------------Kill trace: "); e2.printStackTrace(s); } } } public boolean isValid() { Pair<VirtualFile, String> result = update(); return !disposed && result.first != null; } Pair<VirtualFile, String> update() { if (disposed) return null; long lastUpdated = myLastUpdated; String url = myUrl; VirtualFile file = myFile; long fsModCount = myVirtualFileManager.getModificationCount(); if (lastUpdated == fsModCount) return Pair.create(file, url); if (file != null && !file.isValid()) { url = file.getUrl(); file = null; } if (file == null) { LOG.assertTrue(url != null, "Both file & url are null"); file = myVirtualFileManager.findFileByUrl(url); if (file != null) { url = null; } } if (file != null && !file.exists()) { url = file.getUrl(); file = null; } myFile = file; myUrl = url; myLastUpdated = fsModCount; return Pair.create(file, url); } @Override public String toString() { return getUrlNoUpdate(myFile, myUrl); } public void dispose() { if (disposed) { throw new MyException("Punching the dead horse.\nurl="+toString(), getUserData(CREATE_TRACE), getUserData(KILL_TRACE)); } if (--useCount == 0) { if (TRACE_CREATION) { putUserData(KILL_TRACE, new Throwable()); } String url = getUrlNoUpdate(myFile, myUrl); disposed = true; ((VirtualFilePointerManagerImpl)VirtualFilePointerManager.getInstance()).clearPointerCaches(url, myListener); } } public boolean isDisposed() { return disposed; } }
race condition fix
platform/platform-impl/src/com/intellij/openapi/vfs/impl/VirtualFilePointerImpl.java
race condition fix
<ide><path>latform/platform-impl/src/com/intellij/openapi/vfs/impl/VirtualFilePointerImpl.java <ide> <ide> public class VirtualFilePointerImpl extends UserDataHolderBase implements VirtualFilePointer, Disposable { <ide> private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vfs.impl.VirtualFilePointerImpl"); <del> private String myUrl; // is null when myFile is not null <del> private VirtualFile myFile; <add> private Pair<VirtualFile, String> myFileAndUrl; // must not be both null <ide> private final VirtualFileManager myVirtualFileManager; <ide> private final VirtualFilePointerListener myListener; <ide> private boolean disposed = false; <ide> private static final boolean TRACE_CREATION = /*true || */LOG.isDebugEnabled(); <ide> <ide> VirtualFilePointerImpl(VirtualFile file, @NotNull String url, @NotNull VirtualFileManager virtualFileManager, VirtualFilePointerListener listener, @NotNull Disposable parentDisposable) { <del> myFile = file; <del> myUrl = url; <add> myFileAndUrl = Pair.create(file, url); <ide> myVirtualFileManager = virtualFileManager; <ide> myListener = listener; <ide> useCount = 0; <ide> @NotNull <ide> public String getFileName() { <ide> Pair<VirtualFile, String> result = update(); <add> if (result == null) { <add> checkDisposed(); <add> return ""; <add> } <ide> VirtualFile file = result.first; <ide> if (file != null) { <ide> return file.getName(); <ide> } <ide> <ide> public VirtualFile getFile() { <del> checkDisposed(); <del> <ide> Pair<VirtualFile, String> result = update(); <add> if (result == null) { <add> checkDisposed(); <add> return null; <add> } <ide> return result.first; <ide> } <ide> <ide> public String getUrl() { <ide> //checkDisposed(); no check here since Disposer might want to compute hashcode during dispose() <ide> <del> Pair<VirtualFile, String> result = update(); <del> return getUrlNoUpdate(result.first, result.second); <del> } <del> <del> private static String getUrlNoUpdate(VirtualFile file, String url) { <add> update(); <add> return getUrlNoUpdate(); <add> } <add> <add> private String getUrlNoUpdate() { <add> Pair<VirtualFile, String> fileAndUrl = myFileAndUrl; <add> VirtualFile file = fileAndUrl.first; <add> String url = fileAndUrl.second; <ide> return url == null ? file.getUrl() : url; <ide> } <ide> <ide> <ide> public boolean isValid() { <ide> Pair<VirtualFile, String> result = update(); <del> return !disposed && result.first != null; <add> return result != null && result.first != null; <ide> } <ide> <ide> Pair<VirtualFile, String> update() { <ide> if (disposed) return null; <ide> long lastUpdated = myLastUpdated; <del> String url = myUrl; <del> VirtualFile file = myFile; <add> Pair<VirtualFile, String> fileAndUrl = myFileAndUrl; <add> VirtualFile file = fileAndUrl.first; <add> String url = fileAndUrl.second; <ide> long fsModCount = myVirtualFileManager.getModificationCount(); <del> if (lastUpdated == fsModCount) return Pair.create(file, url); <add> if (lastUpdated == fsModCount) return fileAndUrl; <ide> <ide> if (file != null && !file.isValid()) { <ide> url = file.getUrl(); <ide> url = file.getUrl(); <ide> file = null; <ide> } <del> myFile = file; <del> myUrl = url; <add> Pair<VirtualFile, String> result = Pair.create(file, url); <add> myFileAndUrl = result; <ide> myLastUpdated = fsModCount; <del> return Pair.create(file, url); <add> return result; <ide> } <ide> <ide> @Override <ide> public String toString() { <del> return getUrlNoUpdate(myFile, myUrl); <add> return getUrlNoUpdate(); <ide> } <ide> <ide> public void dispose() { <ide> if (TRACE_CREATION) { <ide> putUserData(KILL_TRACE, new Throwable()); <ide> } <del> String url = getUrlNoUpdate(myFile, myUrl); <add> String url = getUrlNoUpdate(); <ide> disposed = true; <ide> ((VirtualFilePointerManagerImpl)VirtualFilePointerManager.getInstance()).clearPointerCaches(url, myListener); <ide> }
Java
apache-2.0
7f1cce685ac00999946f85867b2705aad847e16d
0
apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc
/* * Copyright 2016-2018 shardingsphere.io. * <p> * 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. * </p> */ package io.shardingsphere.shardingjdbc.jdbc.adapter; import com.google.common.base.Preconditions; import io.shardingsphere.core.bootstrap.ShardingBootstrap; import io.shardingsphere.core.constant.DatabaseType; import io.shardingsphere.shardingjdbc.jdbc.unsupported.AbstractUnsupportedOperationDataSource; import lombok.Getter; import lombok.Setter; import javax.sql.DataSource; import java.io.PrintWriter; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.SQLException; import java.util.Collection; import java.util.Map; import java.util.logging.Logger; /** * Adapter for {@code Datasource}. * * @author zhangliang * @author panjuan * @author zhaojun */ @Getter @Setter public abstract class AbstractDataSourceAdapter extends AbstractUnsupportedOperationDataSource implements AutoCloseable { static { ShardingBootstrap.init(); } private final Map<String, DataSource> dataSourceMap; private final DatabaseType databaseType; private PrintWriter logWriter = new PrintWriter(System.out); public AbstractDataSourceAdapter(final Map<String, DataSource> dataSourceMap) throws SQLException { this.dataSourceMap = dataSourceMap; databaseType = getDatabaseType(dataSourceMap.values()); } protected final DatabaseType getDatabaseType(final Collection<DataSource> dataSources) throws SQLException { DatabaseType result = null; for (DataSource each : dataSources) { DatabaseType databaseType = getDatabaseType(each); Preconditions.checkState(null == result || result.equals(databaseType), String.format("Database type inconsistent with '%s' and '%s'", result, databaseType)); result = databaseType; } return result; } private DatabaseType getDatabaseType(final DataSource dataSource) throws SQLException { if (dataSource instanceof AbstractDataSourceAdapter) { return ((AbstractDataSourceAdapter) dataSource).databaseType; } try (Connection connection = dataSource.getConnection()) { return DatabaseType.valueFrom(connection.getMetaData().getDatabaseProductName()); } } @Override public void close() { for (DataSource each : getDataSourceMap().values()) { try { Method closeMethod = each.getClass().getDeclaredMethod("close"); closeMethod.invoke(each); } catch (final ReflectiveOperationException ignored) { } } } @Override public final Logger getParentLogger() { return Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); } @Override public final Connection getConnection(final String username, final String password) throws SQLException { return getConnection(); } }
sharding-jdbc/sharding-jdbc-core/src/main/java/io/shardingsphere/shardingjdbc/jdbc/adapter/AbstractDataSourceAdapter.java
/* * Copyright 2016-2018 shardingsphere.io. * <p> * 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. * </p> */ package io.shardingsphere.shardingjdbc.jdbc.adapter; import com.google.common.base.Preconditions; import io.shardingsphere.core.bootstrap.ShardingBootstrap; import io.shardingsphere.core.constant.DatabaseType; import io.shardingsphere.shardingjdbc.jdbc.unsupported.AbstractUnsupportedOperationDataSource; import lombok.Getter; import lombok.Setter; import javax.sql.DataSource; import java.io.PrintWriter; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.SQLException; import java.util.Collection; import java.util.Map; import java.util.logging.Logger; /** * Adapter for {@code Datasource}. * * @author zhangliang * @author panjuan */ @Getter @Setter public abstract class AbstractDataSourceAdapter extends AbstractUnsupportedOperationDataSource implements AutoCloseable { static { ShardingBootstrap.init(); } @Getter private final Map<String, DataSource> dataSourceMap; private final DatabaseType databaseType; private PrintWriter logWriter = new PrintWriter(System.out); public AbstractDataSourceAdapter(final Map<String, DataSource> dataSourceMap) throws SQLException { this.dataSourceMap = dataSourceMap; databaseType = getDatabaseType(dataSourceMap.values()); } protected final DatabaseType getDatabaseType(final Collection<DataSource> dataSources) throws SQLException { DatabaseType result = null; for (DataSource each : dataSources) { DatabaseType databaseType = getDatabaseType(each); Preconditions.checkState(null == result || result.equals(databaseType), String.format("Database type inconsistent with '%s' and '%s'", result, databaseType)); result = databaseType; } return result; } private DatabaseType getDatabaseType(final DataSource dataSource) throws SQLException { if (dataSource instanceof AbstractDataSourceAdapter) { return ((AbstractDataSourceAdapter) dataSource).databaseType; } try (Connection connection = dataSource.getConnection()) { return DatabaseType.valueFrom(connection.getMetaData().getDatabaseProductName()); } } @Override public void close() { for (DataSource each : getDataSourceMap().values()) { try { Method closeMethod = each.getClass().getDeclaredMethod("close"); closeMethod.invoke(each); } catch (final ReflectiveOperationException ignored) { } } } @Override public final Logger getParentLogger() { return Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); } @Override public final Connection getConnection(final String username, final String password) throws SQLException { return getConnection(); } }
#1363 Remove @Getter modifier on the datasourceMap.
sharding-jdbc/sharding-jdbc-core/src/main/java/io/shardingsphere/shardingjdbc/jdbc/adapter/AbstractDataSourceAdapter.java
#1363 Remove @Getter modifier on the datasourceMap.
<ide><path>harding-jdbc/sharding-jdbc-core/src/main/java/io/shardingsphere/shardingjdbc/jdbc/adapter/AbstractDataSourceAdapter.java <ide> * <ide> * @author zhangliang <ide> * @author panjuan <add> * @author zhaojun <ide> */ <ide> @Getter <ide> @Setter <ide> ShardingBootstrap.init(); <ide> } <ide> <del> @Getter <ide> private final Map<String, DataSource> dataSourceMap; <ide> <ide> private final DatabaseType databaseType;
Java
lgpl-2.1
c1df35b2604fe69857baa987c0cc79f585eb9eed
0
celements/celements-core,celements/celements-core
package com.celements.mailsender; import java.util.List; import java.util.Map; import org.xwiki.component.annotation.Component; import com.celements.web.plugin.cmd.IMailObjectRole; import com.xpn.xwiki.api.Attachment; import com.xpn.xwiki.web.Utils; @Component public class CelMailSenderService implements IMailSenderRole { private IMailObjectRole injectedMailObject; // chars - a-z A-Z 0-9 œ à á â ã ä å æ ç è é ê ë ì í î ï ð ñ ò ó ô õ ö ø ù ú û ü ý þ ÿ public static final String EMAIL_VALIDATION_REGEX = "^[\\w\\-\\u0153\\u00E0-\\u00F6\\u00F8-\\u00FF.+]+[@][\\w\\-\"" + "\u0153\\u00E0-\\u00F6\\u00F8-\\u00FF]+([.]([\\w\\-\\u0153\\u00E0-\\u00F6\\u00F8-\\u00FF]+))+$"; public static final String EMAIL_VALIDATION_REGEX_CLASS_DEFINITIONS = "/" + EMAIL_VALIDATION_REGEX + "/"; @Override public int sendMail(String from, String replyTo, String to, String cc, String bcc, String subject, String htmlContent, String textContent, List<Attachment> attachments, Map<String, String> others) { return sendMail(from, replyTo, to, cc, bcc, subject, htmlContent, textContent, attachments, others, false); } @Override public int sendMail(String from, String replyTo, String to, String cc, String bcc, String subject, String htmlContent, String textContent, List<Attachment> attachments, Map<String, String> others, boolean isLatin1) { IMailObjectRole sender = getNewMailObject(); sender.setFrom(from); sender.setReplyTo(replyTo); sender.setTo(to); sender.setCc(cc); sender.setBcc(bcc); sender.setSubject(subject); sender.setHtmlContent(htmlContent, isLatin1); sender.setTextContent(textContent); sender.setAttachments(attachments); sender.setOthers(others); return sender.sendMail(); } @Override public boolean isValidEmail(String email) { return email.matches(getEmailValidationRegex()); } /** * use for tests only!!! */ void internal_injectedMailObject(IMailObjectRole mockMailObject) { this.injectedMailObject = mockMailObject; } IMailObjectRole getNewMailObject() { if (injectedMailObject != null) { return injectedMailObject; } return Utils.getComponent(IMailObjectRole.class); } @Override public String getEmailValidationRegex() { return EMAIL_VALIDATION_REGEX; } @Override public String getEmailValidationRegexForClassDefinitions() { return EMAIL_VALIDATION_REGEX_CLASS_DEFINITIONS; } }
src/main/java/com/celements/mailsender/CelMailSenderService.java
package com.celements.mailsender; import java.util.List; import java.util.Map; import org.xwiki.component.annotation.Component; import com.celements.web.plugin.cmd.IMailObjectRole; import com.xpn.xwiki.api.Attachment; import com.xpn.xwiki.web.Utils; @Component public class CelMailSenderService implements IMailSenderRole { private IMailObjectRole injectedMailObject; @Override public int sendMail(String from, String replyTo, String to, String cc, String bcc, String subject, String htmlContent, String textContent, List<Attachment> attachments, Map<String, String> others) { return sendMail(from, replyTo, to, cc, bcc, subject, htmlContent, textContent, attachments, others, false); } @Override public int sendMail(String from, String replyTo, String to, String cc, String bcc, String subject, String htmlContent, String textContent, List<Attachment> attachments, Map<String, String> others, boolean isLatin1) { IMailObjectRole sender = getNewMailObject(); sender.setFrom(from); sender.setReplyTo(replyTo); sender.setTo(to); sender.setCc(cc); sender.setBcc(bcc); sender.setSubject(subject); sender.setHtmlContent(htmlContent, isLatin1); sender.setTextContent(textContent); sender.setAttachments(attachments); sender.setOthers(others); return sender.sendMail(); } @Override public boolean isValidEmail(String email) { return email.matches(getEmailValidationRegex()); } /** * use for tests only!!! */ void internal_injectedMailObject(IMailObjectRole mockMailObject) { this.injectedMailObject = mockMailObject; } IMailObjectRole getNewMailObject() { if (injectedMailObject != null) { return injectedMailObject; } return Utils.getComponent(IMailObjectRole.class); } @Override public String getEmailValidationRegex() { // chars - a-z A-Z 0-9 œ à á â ã ä å æ ç è é ê ë ì í î ï ð ñ ò ó ô õ ö ø ù ú û ü ý þ ÿ String wordChars = "\\w\\-\\u0153\\u00E0-\\u00F6\\u00F8-\\u00FF"; return "^[" + wordChars + ".+]+[@][" + wordChars + "]+([.]([" + wordChars + "]+))+$"; } @Override public String getEmailValidationRegexForClassDefinitions() { return "/" + getEmailValidationRegex() + "/"; } }
Email Validation not available in Class Definitions (#108) * The Regexp moved to a constant (on the component) The methods getEmailValidationRegexForClassDefinitions and getEmailValidationRegex return the appropriate constants. * EMAIL_VALIDATION_REGEX used to build EMAIL_VALIDATION_REGEX_CLASS_DEFINITIONS * Comment left as it was * Comment moved
src/main/java/com/celements/mailsender/CelMailSenderService.java
Email Validation not available in Class Definitions (#108)
<ide><path>rc/main/java/com/celements/mailsender/CelMailSenderService.java <ide> public class CelMailSenderService implements IMailSenderRole { <ide> <ide> private IMailObjectRole injectedMailObject; <add> <add> // chars - a-z A-Z 0-9 œ à á â ã ä å æ ç è é ê ë ì í î ï ð ñ ò ó ô õ ö ø ù ú û ü ý þ ÿ <add> public static final String EMAIL_VALIDATION_REGEX = "^[\\w\\-\\u0153\\u00E0-\\u00F6\\u00F8-\\u00FF.+]+[@][\\w\\-\"" <add> + "\u0153\\u00E0-\\u00F6\\u00F8-\\u00FF]+([.]([\\w\\-\\u0153\\u00E0-\\u00F6\\u00F8-\\u00FF]+))+$"; <add> <add> public static final String EMAIL_VALIDATION_REGEX_CLASS_DEFINITIONS = "/" + EMAIL_VALIDATION_REGEX <add> + "/"; <ide> <ide> @Override <ide> public int sendMail(String from, String replyTo, String to, String cc, String bcc, String subject, <ide> <ide> @Override <ide> public String getEmailValidationRegex() { <del> // chars - a-z A-Z 0-9 œ à á â ã ä å æ ç è é ê ë ì í î ï ð ñ ò ó ô õ ö ø ù ú û ü ý þ ÿ <del> String wordChars = "\\w\\-\\u0153\\u00E0-\\u00F6\\u00F8-\\u00FF"; <del> return "^[" + wordChars + ".+]+[@][" + wordChars + "]+([.]([" + wordChars + "]+))+$"; <add> return EMAIL_VALIDATION_REGEX; <ide> } <ide> <ide> @Override <ide> public String getEmailValidationRegexForClassDefinitions() { <del> return "/" + getEmailValidationRegex() + "/"; <add> return EMAIL_VALIDATION_REGEX_CLASS_DEFINITIONS; <ide> } <del> <ide> }
Java
bsd-2-clause
bc2ed2dc244fd31a53bda8e9e73d64b75f27b730
0
clementval/claw-compiler,clementval/claw-compiler
/* * This file is released under terms of BSD license * See LICENSE file for more information */ package cx2x.translator.transformation.claw; import cx2x.translator.common.NestedDoStatement; import cx2x.translator.language.ClawDimension; import cx2x.translator.language.ClawLanguage; import cx2x.translator.language.helper.accelerator.AcceleratorHelper; import cx2x.translator.language.helper.target.Target; import cx2x.xcodeml.exception.IllegalTransformationException; import cx2x.xcodeml.helper.XelementHelper; import cx2x.xcodeml.transformation.Transformation; import cx2x.xcodeml.transformation.Transformer; import cx2x.xcodeml.xelement.*; import java.util.*; /** * The parallelize transformation transforms the code contained in a * subtourine/function by adding necessary dimensions and parallelism to the * defined data. * * @author clementval */ public class Parallelize extends Transformation { private final ClawLanguage _claw; private Map<String, ClawDimension> _dimensions; private int _overDimensions; private XfunctionDefinition _fctDef; /** * Constructs a new Parallelize transfomration triggered from a specific * pragma. * @param directive The directive that triggered the define transformation. */ public Parallelize(ClawLanguage directive) { super(directive); _overDimensions = 0; _claw = directive; // Keep information about the claw directive here _dimensions = new HashMap<>(); } @Override public boolean analyze(XcodeProgram xcodeml, Transformer transformer) { // Check for the parent fct/subroutine definition _fctDef = XelementHelper.findParentFctDef(_claw.getPragma()); if(_fctDef == null){ xcodeml.addError("Parent function/subroutine cannot be found. " + "Parallelize directive must be defined in a function/subroutine.", _claw.getPragma().getLineNo()); return false; } // Check if any dimension has been defined. if(!_claw.hasDimensionClause()){ xcodeml.addError("No dimension defined for parallelization.", _claw.getPragma().getLineNo()); return false; } for(ClawDimension d : _claw.getDimesionValues()){ if(_dimensions.containsKey(d.getIdentifier())){ xcodeml.addError( String.format("Dimension with identifier %s already specified.", d.getIdentifier()), _claw.getPragma().getLineNo() ); } _dimensions.put(d.getIdentifier(), d); } // Check data information for(String d : _claw.getDataClauseValues()){ if(!_fctDef.getSymbolTable().contains(d)){ xcodeml.addError( String.format("Data %s is not defined in the current block.", d), _claw.getPragma().getLineNo() ); return false; } if(!_fctDef.getDeclarationTable().contains(d)){ xcodeml.addError( String.format("Data %s is not declared in the current block.", d), _claw.getPragma().getLineNo() ); return false; } } // Check the dimension information if(!_claw.getOverClauseValues().contains(":")){ xcodeml.addError("The column dimension has not been specified in the " + "over clause. Use : to specify it.", _claw.getPragma().getLineNo()); return false; } // Check if over dimensions are defined dimensions for(String o : _claw.getOverClauseValues()){ if(!o.equals(ClawDimension.BASE_DIM)){ ++_overDimensions; if(!_dimensions.containsKey(o)){ xcodeml.addError( String.format( "Dimension %s is not defined. Cannot be used in over " + "clause", o), _claw.getPragma().getLineNo() ); return false; } } } return true; } @Override public void transform(XcodeProgram xcodeml, Transformer transformer, Transformation other) throws Exception { // Insert the declarations of variables to iterate over the new dimensions insertVariableToIterateOverDimension(xcodeml); // Promot all array fields with new dimensions. promoteFields(xcodeml); // Adapt array references. adapteArrayReferences(xcodeml); // Delete the pragma _claw.getPragma().delete(); // Apply specific target transformation if(_claw.getTarget() == Target.GPU){ transformForGPU(xcodeml); } else { transformForCPU(xcodeml); } } /** * Apply GPU based transformation. * @param xcodeml Current XcodeML program unit. * @throws Exception */ private void transformForGPU(XcodeProgram xcodeml) throws Exception { /* Create a nested loop with the new defined dimensions and wrap it around * the whole subroutine's body. This is for the moment a really naive * transformation idead but it is our start point. */ NestedDoStatement loops = new NestedDoStatement(getOrderedDimensionsFromDefinition(), xcodeml); XelementHelper.copyBody(_fctDef.getBody(), loops.getInnerStatement()); _fctDef.getBody().delete(); Xbody newBody = XelementHelper.createEmpty(Xbody.class, xcodeml); newBody.appendToChildren(loops.getOuterStatement(), false); _fctDef.appendToChildren(newBody, false); AcceleratorHelper.generateParallelLoopClause(_claw, xcodeml, loops.getOuterStatement(), loops.getOuterStatement(), loops.getGroupSize()); } /** * Apply CPU based transformations. * @param xcodeml Current XcodeML program unit * @throws Exception */ private void transformForCPU(XcodeProgram xcodeml) throws Exception { /* Create a group of nested loop with the newly defined dimension and wrap * every assignement statement in the column loop or including data with it. * This is for the moment a really naive transformation idea but it is our * start point. */ List<ClawDimension> order = getOrderedDimensionsFromDefinition(); List<XassignStatement> assignStatements = XelementHelper.getAllAssignments(_fctDef.getBody()); for(XassignStatement assign : assignStatements){ if(!assign.getLValueModel().isArrayRef()){ continue; } XarrayRef ref = assign.getLValueModel().getArrayRef(); if(_claw.getDataClauseValues(). contains(ref.getVarRef().getVar().getValue())) { NestedDoStatement loops = new NestedDoStatement(order, xcodeml); XelementHelper.insertAfter(assign, loops.getOuterStatement()); loops.getInnerStatement().getBody().appendToChildren(assign, true); assign.delete(); } } } /** * Promote all fields declared in the data clause with the additional * dimensions. * @param xcodeml Current XcodeML program unit in which the element will be * created. * @throws IllegalTransformationException if elements cannot be created or * elements cannot be found. */ private void promoteFields(XcodeProgram xcodeml) throws IllegalTransformationException { for(String data : _claw.getDataClauseValues()){ Xid id = _fctDef.getSymbolTable().get(data); XvarDecl decl = _fctDef.getDeclarationTable().get(data); XbasicType bType = (XbasicType) xcodeml.getTypeTable().get(id.getType()); if(bType == null){ throw new IllegalTransformationException("Cannot find type for " + data, _claw.getPragma().getLineNo()); } XbasicType newType = bType.cloneObject(); newType.setType(xcodeml.getTypeTable().generateArrayTypeHash()); for(int i = 0; i < _overDimensions; ++i){ XindexRange index = XindexRange.createEmptyAssumedShaped(xcodeml); newType.addDimension(index, 0); } id.setType(newType.getType()); decl.getName().setType(newType.getType()); xcodeml.getTypeTable().add(newType); } } /** * Adapt all the array references of the variable in the data clause in the * current function/subroutine definition. * @param xcodeml Current XcodeML program unit in which the element will be * created. * @throws IllegalTransformationException if elements cannot be created or * elements cannot be found. */ private void adapteArrayReferences(XcodeProgram xcodeml) throws IllegalTransformationException { List<XarrayIndex> beforeCrt = new ArrayList<>(); List<XarrayIndex> afterCrt = new ArrayList<>(); List<XarrayIndex> crt = beforeCrt; for(String dim : _claw.getOverClauseValues()){ if(dim.equals(ClawDimension.BASE_DIM)){ crt = afterCrt; } else { ClawDimension d = _dimensions.get(dim); crt.add(d.generateArrayIndex(xcodeml)); } } Collections.reverse(beforeCrt); // Because of insertion order for(String data : _claw.getDataClauseValues()){ List<XarrayRef> refs = XelementHelper.getAllArrayReferences(_fctDef.getBody(), data); for(XarrayRef ref : refs){ for(XarrayIndex ai : beforeCrt){ XelementHelper.insertAfter(ref.getVarRef(), ai.cloneObject()); } for(XarrayIndex ai : afterCrt){ XelementHelper.insertAfter( ref.getInnerElements().get(ref.getInnerElements().size()-1), ai.cloneObject()); } } } } /** * Insert the declaration of the different variables needed to iterate over * the additional dimensions. * @param xcodeml Current XcodeML program unit in which element are created. * @throws IllegalTransformationException if elements cannot be created or * elements cannot be found. */ private void insertVariableToIterateOverDimension(XcodeProgram xcodeml) throws IllegalTransformationException { // Find function type XfunctionType fctType = (XfunctionType) xcodeml.getTypeTable().get(_fctDef.getName().getType()); // Create type and declaration for iterations over the new dimensions XbasicType intTypeIntentIn = XbasicType.create( xcodeml.getTypeTable().generateIntegerTypeHash(), XelementName.TYPE_F_INT, Xintent.IN, xcodeml); xcodeml.getTypeTable().add(intTypeIntentIn); // For each dimension defined in the directive for(ClawDimension dimension : _claw.getDimesionValues()){ if(dimension.lowerBoundIsVar()){ createIdAndDecl(dimension.getLowerBoundId(), intTypeIntentIn.getType(), XelementName.SCLASS_F_PARAM, xcodeml); Xname paramName = Xname.create(dimension.getLowerBoundId(), intTypeIntentIn.getType(), xcodeml); fctType.getParams().add(paramName); } if(dimension.upperBoundIsVar()){ createIdAndDecl(dimension.getUpperBoundId(), intTypeIntentIn.getType(), XelementName.SCLASS_F_PARAM, xcodeml); Xname paramName = Xname.create(dimension.getUpperBoundId(), intTypeIntentIn.getType(), xcodeml); fctType.getParams().add(paramName); } // Create induction variable declaration createIdAndDecl(dimension.getIdentifier(), XelementName.TYPE_F_INT, XelementName.SCLASS_F_LOCAL, xcodeml); } } /** * Create the id and varDecl elements and add them to the symbol/declaration * table. * @param name Name of the variable. * @param type Type of the variable. * @param sclass Scope class of the variable (from XelementName). * @param xcodeml Current XcodeML program unit in which the elements will be * created. * @throws IllegalTransformationException if the elements cannot be created. */ private void createIdAndDecl(String name, String type, String sclass, XcodeProgram xcodeml) throws IllegalTransformationException { Xid id = Xid.create(type, sclass, name, xcodeml); _fctDef.getSymbolTable().add(id); XvarDecl decl = XvarDecl.create(type, name, xcodeml); _fctDef.getDeclarationTable().add(decl); } /** * Get the list of dimensions in order from the parallelize over definition. * @return Ordered list of dimension object. */ private List<ClawDimension> getOrderedDimensionsFromDefinition(){ List<ClawDimension> dimensions = new ArrayList<>(); for(String o : _claw.getOverClauseValues()) { if (o.equals(ClawDimension.BASE_DIM)) { continue; } dimensions.add(_dimensions.get(o)); } return dimensions; } @Override public boolean canBeTransformedWith(Transformation other) { return false; // This is an independent transformation } }
omni-cx2x/src/cx2x/translator/transformation/claw/Parallelize.java
/* * This file is released under terms of BSD license * See LICENSE file for more information */ package cx2x.translator.transformation.claw; import cx2x.translator.common.NestedDoStatement; import cx2x.translator.language.ClawDimension; import cx2x.translator.language.ClawLanguage; import cx2x.translator.language.helper.accelerator.AcceleratorHelper; import cx2x.translator.language.helper.target.Target; import cx2x.xcodeml.exception.IllegalTransformationException; import cx2x.xcodeml.helper.XelementHelper; import cx2x.xcodeml.transformation.Transformation; import cx2x.xcodeml.transformation.Transformer; import cx2x.xcodeml.xelement.*; import java.util.*; /** * The parallelize transformation transforms the code contained in a * subtourine/function by adding necessary dimensions and parallelism to the * defined data. * * @author clementval */ public class Parallelize extends Transformation { private final ClawLanguage _claw; private Map<String, ClawDimension> _dimensions; private int _overDimensions; private XfunctionDefinition _fctDef; /** * Constructs a new Parallelize transfomration triggered from a specific * pragma. * @param directive The directive that triggered the define transformation. */ public Parallelize(ClawLanguage directive) { super(directive); _overDimensions = 0; _claw = directive; // Keep information about the claw directive here _dimensions = new HashMap<>(); } @Override public boolean analyze(XcodeProgram xcodeml, Transformer transformer) { // Check for the parent fct/subroutine definition _fctDef = XelementHelper.findParentFctDef(_claw.getPragma()); if(_fctDef == null){ xcodeml.addError("Parent function/subroutine cannot be found. " + "Parallelize directive must be defined in a function/subroutine.", _claw.getPragma().getLineNo()); return false; } // Check if any dimension has been defined. if(!_claw.hasDimensionClause()){ xcodeml.addError("No dimension defined for parallelization.", _claw.getPragma().getLineNo()); return false; } for(ClawDimension d : _claw.getDimesionValues()){ if(_dimensions.containsKey(d.getIdentifier())){ xcodeml.addError( String.format("Dimension with identifier %s already specified.", d.getIdentifier()), _claw.getPragma().getLineNo() ); } _dimensions.put(d.getIdentifier(), d); } // Check data information for(String d : _claw.getDataClauseValues()){ if(!_fctDef.getSymbolTable().contains(d)){ xcodeml.addError( String.format("Data %s is not defined in the current block.", d), _claw.getPragma().getLineNo() ); return false; } if(!_fctDef.getDeclarationTable().contains(d)){ xcodeml.addError( String.format("Data %s is not declared in the current block.", d), _claw.getPragma().getLineNo() ); return false; } } // Check the dimension information if(!_claw.getOverClauseValues().contains(":")){ xcodeml.addError("The column dimension has not been specified in the " + "over clause. Use : to specify it.", _claw.getPragma().getLineNo()); return false; } // Check if over dimensions are defined dimensions for(String o : _claw.getOverClauseValues()){ if(!o.equals(ClawDimension.BASE_DIM)){ ++_overDimensions; if(!_dimensions.containsKey(o)){ xcodeml.addError( String.format( "Dimension %s is not defined. Cannot be used in over " + "clause", o), _claw.getPragma().getLineNo() ); return false; } } } return true; } @Override public void transform(XcodeProgram xcodeml, Transformer transformer, Transformation other) throws Exception { // Apply first all common declaration // Insert the declarations of variables to iterate over the new dimensions insertVariableToIterateOverDimension(xcodeml); // Promot all array fields with new dimensions. promoteFields(xcodeml); // Adapt array references. adapteArrayReferences(xcodeml); // Delete the pragma _claw.getPragma().delete(); // Apply specific target transformation if(_claw.getTarget() == Target.GPU){ transformForGPU(xcodeml); } else { transformForCPU(xcodeml); } } /** * Apply GPU based transformation. * @param xcodeml Current XcodeML program unit. * @throws Exception */ private void transformForGPU(XcodeProgram xcodeml) throws Exception { /* Create a nested loop with the new defined dimensions and wrap it around * the whole subroutine's body. This is for the moment a really naive * transformation idead but it is our start point. */ NestedDoStatement loops = new NestedDoStatement(getOrderedDimensionsFromDefinition(), xcodeml); XelementHelper.copyBody(_fctDef.getBody(), loops.getInnerStatement()); _fctDef.getBody().delete(); Xbody newBody = XelementHelper.createEmpty(Xbody.class, xcodeml); newBody.appendToChildren(loops.getOuterStatement(), false); _fctDef.appendToChildren(newBody, false); AcceleratorHelper.generateParallelLoopClause(_claw, xcodeml, loops.getOuterStatement(), loops.getOuterStatement(), loops.getGroupSize()); } /** * Apply CPU based transformations. * @param xcodeml Current XcodeML program unit * @throws Exception */ private void transformForCPU(XcodeProgram xcodeml) throws Exception { /* Create a group of nested loop with the newly defined dimension and wrap * every assignement statement in the column loop or including data with it. * This is for the moment a really naive transformation idea but it is our * start point. */ List<ClawDimension> order = getOrderedDimensionsFromDefinition(); List<XassignStatement> assignStatements = XelementHelper.getAllAssignments(_fctDef.getBody()); for(XassignStatement assign : assignStatements){ if(!assign.getLValueModel().isArrayRef()){ continue; } XarrayRef ref = assign.getLValueModel().getArrayRef(); if(_claw.getDataClauseValues(). contains(ref.getVarRef().getVar().getValue())) { NestedDoStatement loops = new NestedDoStatement(order, xcodeml); XelementHelper.insertAfter(assign, loops.getOuterStatement()); loops.getInnerStatement().getBody().appendToChildren(assign, true); assign.delete(); } } } /** * Promote all fields declared in the data clause with the additional * dimensions. * @param xcodeml Current XcodeML program unit in which the element will be * created. * @throws IllegalTransformationException if elements cannot be created or * elements cannot be found. */ private void promoteFields(XcodeProgram xcodeml) throws IllegalTransformationException { for(String data : _claw.getDataClauseValues()){ Xid id = _fctDef.getSymbolTable().get(data); XvarDecl decl = _fctDef.getDeclarationTable().get(data); XbasicType bType = (XbasicType) xcodeml.getTypeTable().get(id.getType()); if(bType == null){ throw new IllegalTransformationException("Cannot find type for " + data, _claw.getPragma().getLineNo()); } XbasicType newType = bType.cloneObject(); newType.setType(xcodeml.getTypeTable().generateArrayTypeHash()); for(int i = 0; i < _overDimensions; ++i){ XindexRange index = XindexRange.createEmptyAssumedShaped(xcodeml); newType.addDimension(index, 0); } id.setType(newType.getType()); decl.getName().setType(newType.getType()); xcodeml.getTypeTable().add(newType); } } /** * Adapt all the array references of the variable in the data clause in the * current function/subroutine definition. * @param xcodeml Current XcodeML program unit in which the element will be * created. * @throws IllegalTransformationException if elements cannot be created or * elements cannot be found. */ private void adapteArrayReferences(XcodeProgram xcodeml) throws IllegalTransformationException { List<XarrayIndex> beforeCrt = new ArrayList<>(); List<XarrayIndex> afterCrt = new ArrayList<>(); List<XarrayIndex> crt = beforeCrt; for(String dim : _claw.getOverClauseValues()){ if(dim.equals(ClawDimension.BASE_DIM)){ crt = afterCrt; } else { ClawDimension d = _dimensions.get(dim); crt.add(d.generateArrayIndex(xcodeml)); } } Collections.reverse(beforeCrt); // Because of insertion order for(String data : _claw.getDataClauseValues()){ List<XarrayRef> refs = XelementHelper.getAllArrayReferences(_fctDef.getBody(), data); for(XarrayRef ref : refs){ for(XarrayIndex ai : beforeCrt){ XelementHelper.insertAfter(ref.getVarRef(), ai.cloneObject()); } for(XarrayIndex ai : afterCrt){ XelementHelper.insertAfter( ref.getInnerElements().get(ref.getInnerElements().size()-1), ai.cloneObject()); } } } } /** * Insert the declaration of the different variables needed to iterate over * the additional dimensions. * @param xcodeml Current XcodeML program unit in which element are created. * @throws IllegalTransformationException if elements cannot be created or * elements cannot be found. */ private void insertVariableToIterateOverDimension(XcodeProgram xcodeml) throws IllegalTransformationException { // Find function type XfunctionType fctType = (XfunctionType) xcodeml.getTypeTable().get(_fctDef.getName().getType()); // Create type and declaration for iterations over the new dimensions XbasicType intTypeIntentIn = XbasicType.create( xcodeml.getTypeTable().generateIntegerTypeHash(), XelementName.TYPE_F_INT, Xintent.IN, xcodeml); xcodeml.getTypeTable().add(intTypeIntentIn); // For each dimension defined in the directive for(ClawDimension dimension : _claw.getDimesionValues()){ if(dimension.lowerBoundIsVar()){ createIdAndDecl(dimension.getLowerBoundId(), intTypeIntentIn.getType(), XelementName.SCLASS_F_PARAM, xcodeml); Xname paramName = Xname.create(dimension.getLowerBoundId(), intTypeIntentIn.getType(), xcodeml); fctType.getParams().add(paramName); } if(dimension.upperBoundIsVar()){ createIdAndDecl(dimension.getUpperBoundId(), intTypeIntentIn.getType(), XelementName.SCLASS_F_PARAM, xcodeml); Xname paramName = Xname.create(dimension.getUpperBoundId(), intTypeIntentIn.getType(), xcodeml); fctType.getParams().add(paramName); } // Create induction variable declaration createIdAndDecl(dimension.getIdentifier(), XelementName.TYPE_F_INT, XelementName.SCLASS_F_LOCAL, xcodeml); } } /** * Create the id and varDecl elements and add them to the symbol/declaration * table. * @param name Name of the variable. * @param type Type of the variable. * @param sclass Scope class of the variable (from XelementName). * @param xcodeml Current XcodeML program unit in which the elements will be * created. * @throws IllegalTransformationException if the elements cannot be created. */ private void createIdAndDecl(String name, String type, String sclass, XcodeProgram xcodeml) throws IllegalTransformationException { Xid id = Xid.create(type, sclass, name, xcodeml); _fctDef.getSymbolTable().add(id); XvarDecl decl = XvarDecl.create(type, name, xcodeml); _fctDef.getDeclarationTable().add(decl); } /** * Get the list of dimensions in order from the parallelize over definition. * @return Ordered list of dimension object. */ private List<ClawDimension> getOrderedDimensionsFromDefinition(){ List<ClawDimension> dimensions = new ArrayList<>(); for(String o : _claw.getOverClauseValues()) { if (o.equals(ClawDimension.BASE_DIM)) { continue; } dimensions.add(_dimensions.get(o)); } return dimensions; } @Override public boolean canBeTransformedWith(Transformation other) { return false; // This is an independent transformation } }
Remove useless comment
omni-cx2x/src/cx2x/translator/transformation/claw/Parallelize.java
Remove useless comment
<ide><path>mni-cx2x/src/cx2x/translator/transformation/claw/Parallelize.java <ide> Transformation other) <ide> throws Exception <ide> { <del> <del> // Apply first all common declaration <del> <ide> // Insert the declarations of variables to iterate over the new dimensions <ide> insertVariableToIterateOverDimension(xcodeml); <ide>
Java
mit
fdc2efafc3a5fea08b49d3db2ae88cf985f27b7a
0
Qoracoin/Qora,Bitcoinsulting/Qora,Bitcoinsulting/Qora,Bitcoinsulting/Qora,Qoracoin/Qora,Bitcoinsulting/Qora,Bitcoinsulting/Qora,Qoracoin/Qora
package at; import java.math.BigDecimal; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.Charset; import java.util.Iterator; import java.util.List; import java.util.concurrent.ConcurrentSkipListMap; import org.json.simple.JSONObject; import org.mapdb.Fun.Tuple4; import qora.account.Account; import qora.crypto.Base58; import database.DBSet; public class AT extends AT_Machine_State { private String name; private String description; private String type; private String tags; public AT(byte[] atId, byte[] creator, String name , String description, String type, String tags , byte[] creationBytes, int height) { super(atId, creator, creationBytes, height); this.name = name; this.description = description; this.type = type; this.tags = tags; } public AT ( byte[] atId , byte[] creator , String name , String description, String type, String tags , short version , byte[] stateBytes, int csize , int dsize , int c_user_stack_bytes , int c_call_stack_bytes , long minActivationAmount , int creationBlockHeight, int sleepBetween , byte[] apCode ) { super( atId , creator , version , stateBytes , csize , dsize , c_user_stack_bytes , c_call_stack_bytes , creationBlockHeight , sleepBetween , minActivationAmount ,apCode ); this.name = name; this.description = description; this.type = type; this.tags = tags; } public static AT getAT( String id, DBSet dbSet ) { return getAT( Base58.decode( id ) , dbSet ); } public static AT getAT( byte[] atId, DBSet dbSet) { AT at = dbSet.getATMap().getAT( atId ); return at; } public static AT getAT(byte[] atId) { return getAT( atId, DBSet.getInstance() ); } public static Iterator<String> getOrderedATs( DBSet dbSet, Integer height ) { return dbSet.getATMap().getOrderedATs(height); } //public int getDataLength() { // return name.length() + description.length() + this.getStateSize(); //} public byte[] toBytes(boolean b) { byte[] bname = getName().getBytes( Charset.forName( "UTF-8" ) ); byte[] bdesc = description.getBytes( Charset.forName( "UTF-8" ) ); byte[] btype = type.getBytes( Charset.forName("UTF-8") ); byte[] btags = tags.getBytes( Charset.forName("UTF-8") ); ByteBuffer bf = ByteBuffer.allocate( 4 + bname.length + 4 + bdesc.length + getSize() + 4 + btype.length + 4 + btags.length ); bf.order( ByteOrder.LITTLE_ENDIAN ); bf.putInt( bname.length ); bf.put( bname ); bf.putInt( bdesc.length ); bf.put( bdesc ); bf.putInt( btype.length ); bf.put( btype ); bf.putInt( btags.length ); bf.put( btags ); bf.put( getBytes() ); return bf.array(); } public int getCreationLength() { byte[] bname = getName().getBytes( Charset.forName( "UTF-8" ) ); byte[] bdesc = description.getBytes( Charset.forName( "UTF-8" ) ); byte[] btype = type.getBytes( Charset.forName("UTF-8") ); byte[] btags = tags.getBytes( Charset.forName("UTF-8") ); return 4 + bname.length + 4 + bdesc.length + 4 + btype.length + 4 + btags.length + getSize(); } public static AT parse(byte[] bytes) { ByteBuffer bf = ByteBuffer.allocate( bytes.length ); bf.order( ByteOrder.LITTLE_ENDIAN ); bf.put( bytes ); bf.clear(); int nameSize = bf.getInt(); byte[] bname = new byte[ nameSize ]; bf.get( bname ); String name = new String( bname , Charset.forName( "UTF-8" ) ); int descSize = bf.getInt(); byte[] bdesc = new byte[ descSize ]; bf.get( bdesc ); String description = new String( bdesc , Charset.forName( "UTF-8" ) ); int typeSize = bf.getInt(); byte[] btype = new byte[ typeSize ]; bf.get( btype ); String type = new String( btype , Charset.forName( "UTF-8" ) ); int tagsSize = bf.getInt(); byte[] btags = new byte[ tagsSize ]; bf.get( btags ); String tags = new String( btags , Charset.forName( "UTF-8" ) ); byte[] atId = new byte[ AT_Constants.AT_ID_SIZE ]; bf.get( atId ); byte[] creator = new byte[ AT_Constants.AT_ID_SIZE ]; bf.get( creator ); short version = bf.getShort(); int csize = bf.getInt(); int dsize = bf.getInt(); int c_call_stack_bytes = bf.getInt(); int c_user_stack_bytes = bf.getInt(); long minActivationAmount = bf.getLong(); int creationBlockHeight = bf.getInt(); int sleepBetween = bf.getInt(); byte[] ap_code = new byte[ csize ]; bf.get( ap_code ); byte[] state = new byte[ bf.capacity() - bf.position() ]; bf.get( state ); AT at = new AT( atId , creator , name , description, type, tags , version , state , csize , dsize , c_user_stack_bytes , c_call_stack_bytes , minActivationAmount , creationBlockHeight , sleepBetween , ap_code ); return at; } @SuppressWarnings("unchecked") public JSONObject toJSON() { JSONObject atJSON = new JSONObject(); atJSON.put("accountBalance", new Account(Base58.encode(getId())).getConfirmedBalance().toPlainString() ); atJSON.put("name", this.name); atJSON.put("description", description); atJSON.put("type", type); atJSON.put("tags", tags); atJSON.put("version", getVersion()); atJSON.put("minActivation", BigDecimal.valueOf( minActivationAmount() , 8 ).toPlainString() ); atJSON.put("creationBlock", getCreationBlockHeight()); atJSON.put("state", getStateJSON()); atJSON.put("creator", new Account(Base58.encode(getCreator())).getAddress()); return atJSON; } public String getName() { return name; } public String getDescription() { return this.description; } public String getType() { return type; } public String getTags() { return tags; } }
Qora/src/at/AT.java
package at; import java.math.BigDecimal; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.Charset; import java.util.Iterator; import java.util.List; import java.util.concurrent.ConcurrentSkipListMap; import org.json.simple.JSONObject; import org.mapdb.Fun.Tuple4; import qora.account.Account; import qora.crypto.Base58; import database.DBSet; public class AT extends AT_Machine_State { private String name; private String description; private String type; private String tags; public AT(byte[] atId, byte[] creator, String name , String description, String type, String tags , byte[] creationBytes, int height) { super(atId, creator, creationBytes, height); this.name = name; this.description = description; this.type = type; this.tags = tags; } public AT ( byte[] atId , byte[] creator , String name , String description, String type, String tags , short version , byte[] stateBytes, int csize , int dsize , int c_user_stack_bytes , int c_call_stack_bytes , long minActivationAmount , int creationBlockHeight, int sleepBetween , byte[] apCode ) { super( atId , creator , version , stateBytes , csize , dsize , c_user_stack_bytes , c_call_stack_bytes , creationBlockHeight , sleepBetween , minActivationAmount ,apCode ); this.name = name; this.description = description; this.type = type; this.tags = tags; } public static AT getAT( String id, DBSet dbSet ) { return getAT( Base58.decode( id ) , dbSet ); } public static AT getAT( byte[] atId, DBSet dbSet) { AT at = dbSet.getATMap().getAT( atId ); return at; } public static AT getAT(byte[] atId) { return getAT( atId, DBSet.getInstance() ); } public static Iterator<String> getOrderedATs( DBSet dbSet, Integer height ) { return dbSet.getATMap().getOrderedATs(height); } //public int getDataLength() { // return name.length() + description.length() + this.getStateSize(); //} public byte[] toBytes(boolean b) { byte[] bname = getName().getBytes( Charset.forName( "UTF-8" ) ); byte[] bdesc = description.getBytes( Charset.forName( "UTF-8" ) ); byte[] btype = type.getBytes( Charset.forName("UTF-8") ); byte[] btags = tags.getBytes( Charset.forName("UTF-8") ); ByteBuffer bf = ByteBuffer.allocate( 4 + bname.length + 4 + bdesc.length + getSize() + 4 + btype.length + 4 + btags.length ); bf.order( ByteOrder.LITTLE_ENDIAN ); bf.putInt( bname.length ); bf.put( bname ); bf.putInt( bdesc.length ); bf.put( bdesc ); bf.putInt( btype.length ); bf.put( btype ); bf.putInt( btags.length ); bf.put( btags ); bf.put( getBytes() ); return bf.array(); } public int getCreationLength() { byte[] bname = getName().getBytes( Charset.forName( "UTF-8" ) ); byte[] bdesc = description.getBytes( Charset.forName( "UTF-8" ) ); byte[] btype = type.getBytes( Charset.forName("UTF-8") ); byte[] btags = tags.getBytes( Charset.forName("UTF-8") ); return 4 + bname.length + 4 + bdesc.length + 4 + btype.length + 4 + btags.length + getSize(); } public static AT parse(byte[] bytes) { ByteBuffer bf = ByteBuffer.allocate( bytes.length ); bf.order( ByteOrder.LITTLE_ENDIAN ); bf.put( bytes ); bf.clear(); int nameSize = bf.getInt(); byte[] bname = new byte[ nameSize ]; bf.get( bname ); String name = new String( bname , Charset.forName( "UTF-8" ) ); int descSize = bf.getInt(); byte[] bdesc = new byte[ descSize ]; bf.get( bdesc ); String description = new String( bdesc , Charset.forName( "UTF-8" ) ); int typeSize = bf.getInt(); byte[] btype = new byte[ typeSize ]; bf.get( btype ); String type = new String( btype , Charset.forName( "UTF-8" ) ); int tagsSize = bf.getInt(); byte[] btags = new byte[ tagsSize ]; bf.get( btags ); String tags = new String( btags , Charset.forName( "UTF-8" ) ); byte[] atId = new byte[ AT_Constants.AT_ID_SIZE ]; bf.get( atId ); byte[] creator = new byte[ AT_Constants.AT_ID_SIZE ]; bf.get( creator ); short version = bf.getShort(); int csize = bf.getInt(); int dsize = bf.getInt(); int c_call_stack_bytes = bf.getInt(); int c_user_stack_bytes = bf.getInt(); long minActivationAmount = bf.getLong(); int creationBlockHeight = bf.getInt(); int sleepBetween = bf.getInt(); byte[] ap_code = new byte[ csize ]; bf.get( ap_code ); byte[] state = new byte[ bf.capacity() - bf.position() ]; bf.get( state ); AT at = new AT( atId , creator , name , description, type, tags , version , state , csize , dsize , c_user_stack_bytes , c_call_stack_bytes , minActivationAmount , creationBlockHeight , sleepBetween , ap_code ); return at; } @SuppressWarnings("unchecked") public JSONObject toJSON() { JSONObject atJSON = new JSONObject(); atJSON.put("account", new Account(Base58.encode(getId())).getConfirmedBalance().toPlainString() ); atJSON.put("name", this.name); atJSON.put("description", description); atJSON.put("type", type); atJSON.put("tags", tags); atJSON.put("version", getVersion()); atJSON.put("minActivation", BigDecimal.valueOf( minActivationAmount() , 8 ).toPlainString() ); atJSON.put("creationBlock", getCreationBlockHeight()); atJSON.put("state", getStateJSON()); atJSON.put("creator", new Account(Base58.encode(getCreator())).getAddress()); return atJSON; } public String getName() { return name; } public String getDescription() { return this.description; } public String getType() { return type; } public String getTags() { return tags; } }
change "account" to "accountBalance" in GET at/id/ Agreed with vbcs
Qora/src/at/AT.java
change "account" to "accountBalance" in GET at/id/
<ide><path>ora/src/at/AT.java <ide> public JSONObject toJSON() <ide> { <ide> JSONObject atJSON = new JSONObject(); <del> atJSON.put("account", new Account(Base58.encode(getId())).getConfirmedBalance().toPlainString() ); <add> atJSON.put("accountBalance", new Account(Base58.encode(getId())).getConfirmedBalance().toPlainString() ); <ide> atJSON.put("name", this.name); <ide> atJSON.put("description", description); <ide> atJSON.put("type", type);
Java
mit
19c043d92c6c913f28f8524b14afad1318efd8ee
0
CreaturePhil/Algorithms
public class BubbleSort { /** * Bubble Sort repeatedly steps through the list to be sorted, compares each * pair of adjacent items and swaps them if they are in the wrong order. * The pass through the list is repeated until no swaps are needed, which * indicates that the list is sorted. Bubble Sort is a comparison sort and is * named for the way smaller elements "bubble" to the top of the list. * Bubble Sort has O(n^2) time complexity. */ public int[] bubble_sort(int[] arr) { int temp; for (int i = 0; i < arr.length; i++) { for (int j = i; j < arr.length; j++) { if (arr[i] > arr[j]) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } return arr; } }
sorting/BubbleSort.java
public class BubbleSort { /** * Bubble Sort repeatedly steps through the list to be sorted, compares each * pair of adjacent items and swaps them if they are in the wrong order. * The pass through the list is repeated until no swaps are needed, which * indicates that the list is sorted. Bubble Sort is a comparison sort, is * named for the way smaller elements "bubble" to the top of the list. * Bubble Sort has O(n^2) time complexity. */ public int[] bubble_sort(int[] arr) { int temp; for (int i = 0; i < arr.length; i++) { for (int j = i; j < arr.length; j++) { if (arr[i] > arr[j]) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } return arr; } }
Update BubbleSort.java
sorting/BubbleSort.java
Update BubbleSort.java
<ide><path>orting/BubbleSort.java <ide> * Bubble Sort repeatedly steps through the list to be sorted, compares each <ide> * pair of adjacent items and swaps them if they are in the wrong order. <ide> * The pass through the list is repeated until no swaps are needed, which <del> * indicates that the list is sorted. Bubble Sort is a comparison sort, is <add> * indicates that the list is sorted. Bubble Sort is a comparison sort and is <ide> * named for the way smaller elements "bubble" to the top of the list. <ide> * Bubble Sort has O(n^2) time complexity. <ide> */
Java
apache-2.0
ddda3b4bc05c800ef3e1001ff56c03562becb376
0
idekerlab/KEGGscape,parvathisudha/KEGGscape,idekerlab/KEGGscape,parvathisudha/KEGGscape
package org.cytoscape.data.reader.kgml; import giny.view.NodeView; import java.awt.Color; import java.awt.Font; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.cytoscape.data.reader.kgml.generated.Entry; import org.cytoscape.data.reader.kgml.generated.Graphics; import org.cytoscape.data.reader.kgml.generated.Pathway; import org.cytoscape.data.reader.kgml.generated.Product; import org.cytoscape.data.reader.kgml.generated.Reaction; import org.cytoscape.data.reader.kgml.generated.Relation; import org.cytoscape.data.reader.kgml.generated.Substrate; import org.cytoscape.data.reader.kgml.generated.Subtype; import cytoscape.CyEdge; import cytoscape.CyNetwork; import cytoscape.CyNode; import cytoscape.Cytoscape; import cytoscape.data.CyAttributes; import cytoscape.data.Semantics; import cytoscape.view.CyNetworkView; import cytoscape.visual.ArrowShape; import cytoscape.visual.EdgeAppearanceCalculator; import cytoscape.visual.GlobalAppearanceCalculator; import cytoscape.visual.LineStyle; import cytoscape.visual.NodeAppearanceCalculator; import cytoscape.visual.NodeShape; import cytoscape.visual.VisualPropertyType; import cytoscape.visual.VisualStyle; import cytoscape.visual.calculators.BasicCalculator; import cytoscape.visual.calculators.Calculator; import cytoscape.visual.mappings.DiscreteMapping; import cytoscape.visual.mappings.ObjectMapping; import cytoscape.visual.mappings.PassThroughMapping; public class PathwayMapper { private final Pathway pathway; private final String pathwayName; private int[] nodeIdx; private int[] edgeIdx; private static final String KEGG_NAME = "KEGG.name"; private static final String KEGG_ENTRY_TYPE = "KEGG.entry"; private static final String KEGG_LABEL = "KEGG.label"; private static final String KEGG_RELATION_TYPE = "KEGG.relation"; private static final String KEGG_REACTION_TYPE = "KEGG.reaction"; private static final String KEGG_LINK = "KEGG.link"; public PathwayMapper(final Pathway pathway) { this.pathway = pathway; this.pathwayName = pathway.getName(); } public void doMapping() { mapNode(); final List<CyEdge> relationEdges = mapRelationEdge(); final List<CyEdge> reactionEdges = mapReactionEdge(); edgeIdx = new int[relationEdges.size() + reactionEdges.size()]; int idx = 0; for (CyEdge edge : reactionEdges) { edgeIdx[idx] = edge.getRootGraphIndex(); idx++; } for (CyEdge edge : relationEdges) { edgeIdx[idx] = edge.getRootGraphIndex(); idx++; } } private final Map<String, Entry> entryMap = new HashMap<String, Entry>(); final Map<String, CyNode> nodeMap = new HashMap<String, CyNode>(); // final Map<String, CyNode> cpdMap = new HashMap<String, CyNode>(); final Map<String, CyNode> id2cpdMap = new HashMap<String, CyNode>(); final Map<String, List<Entry>> cpdDataMap = new HashMap<String, List<Entry>>(); final Map<CyNode, Entry> geneDataMap = new HashMap<CyNode, Entry>(); private final Map<CyNode, String> entry2reaction = new HashMap<CyNode, String>(); private void mapNode() { final String pathwayID = pathway.getName(); final List<Entry> components = pathway.getEntry(); final CyAttributes nodeAttr = Cytoscape.getNodeAttributes(); for (final Entry comp : components) { for (Graphics grap : comp.getGraphics()) { if (!grap.getType().equals(KEGGShape.LINE.getTag())) { CyNode node = Cytoscape.getCyNode(pathwayID + "-" + comp.getId(), true); nodeAttr.setAttribute(node.getIdentifier(), KEGG_NAME, comp .getName()); if (comp.getLink() != null) nodeAttr.setAttribute(node.getIdentifier(), KEGG_LINK, comp.getLink()); nodeAttr.setAttribute(node.getIdentifier(), KEGG_ENTRY_TYPE, comp.getType()); final String reaction = comp.getReaction(); // Save reaction if (reaction != null) { entry2reaction.put(node, reaction); nodeAttr.setAttribute(node.getIdentifier(), "KEGG.reaction", reaction); } // final Graphics graphics = comp.getGraphics(); if (grap != null && grap.getName() != null) { nodeAttr.setAttribute(node.getIdentifier(), KEGG_LABEL, grap.getName()); } nodeMap.put(comp.getId(), node); entryMap.put(comp.getId(), comp); if (comp.getType().equals(KEGGEntryType.COMPOUND.getTag())) { id2cpdMap.put(comp.getId(), node); List<Entry> current = cpdDataMap.get(comp.getName()); if (current != null) { current.add(comp); } else { current = new ArrayList<Entry>(); current.add(comp); } cpdDataMap.put(comp.getName(), current); } else if (comp.getType().equals( KEGGEntryType.GENE.getTag()) || comp.getType().equals( KEGGEntryType.ORTHOLOG.getTag())) { geneDataMap.put(node, comp); } } } } nodeIdx = new int[nodeMap.values().size()]; int idx = 0; for (CyNode node : nodeMap.values()) { nodeIdx[idx] = node.getRootGraphIndex(); idx++; } } private List<CyEdge> mapRelationEdge() { final List<Relation> relations = pathway.getRelation(); final List<CyEdge> edges = new ArrayList<CyEdge>(); final CyAttributes edgeAttr = Cytoscape.getEdgeAttributes(); for (Relation rel : relations) { final String type = rel.getType(); if (rel.getType().equals(KEGGRelationType.MAPLINK.getTag())) { final List<Subtype> subs = rel.getSubtype(); if (entryMap.get(rel.getEntry1()).getType().equals( KEGGEntryType.MAP.getTag())) { CyNode maplinkNode = nodeMap.get(rel.getEntry1()); for (Subtype sub : subs) { CyNode cpdNode = nodeMap.get(sub.getValue()); System.out.println(maplinkNode.getIdentifier()); System.out.println(cpdNode.getIdentifier() + "\n\n"); CyEdge edge1 = Cytoscape.getCyEdge(cpdNode, maplinkNode, Semantics.INTERACTION, type, true, true); edges.add(edge1); edgeAttr.setAttribute(edge1.getIdentifier(), KEGG_RELATION_TYPE, type); CyEdge edge2 = Cytoscape.getCyEdge(maplinkNode, cpdNode, Semantics.INTERACTION, type, true, true); edges.add(edge2); // edgeAttr.setAttribute(edge2.getIdentifier(), // KEGG_RELATION_TYPE, type); } } else { CyNode maplinkNode = nodeMap.get(rel.getEntry2()); for (Subtype sub : subs) { CyNode cpdNode = nodeMap.get(sub.getValue()); System.out.println(maplinkNode.getIdentifier()); System.out.println(cpdNode.getIdentifier() + "\n\n"); CyEdge edge1 = Cytoscape.getCyEdge(cpdNode, maplinkNode, Semantics.INTERACTION, type, true, true); edges.add(edge1); edgeAttr.setAttribute(edge1.getIdentifier(), KEGG_RELATION_TYPE, type); CyEdge edge2 = Cytoscape.getCyEdge(maplinkNode, cpdNode, Semantics.INTERACTION, type, true, true); edges.add(edge2); // edgeAttr.setAttribute(edge2.getIdentifier(), // KEGG_RELATION_TYPE, type); } } } } return edges; } private List<CyEdge> mapReactionEdge() { final String pathwayID = pathway.getName(); final List<Reaction> reactions = pathway.getReaction(); final List<CyEdge> edges = new ArrayList<CyEdge>(); CyAttributes edgeAttr = Cytoscape.getEdgeAttributes(); Pattern pattern = Pattern.compile(".*01100"); if (pattern.matcher(pathwayID).matches()) { for (Reaction rea : reactions) { for (Substrate sub : rea.getSubstrate()) { CyNode subNode = nodeMap.get(sub.getId()); for (Product pro : rea.getProduct()) { CyNode proNode = nodeMap.get(pro.getId()); CyEdge edge = Cytoscape.getCyEdge(subNode, proNode, Semantics.INTERACTION, "cc", true); edges.add(edge); edgeAttr.setAttribute(edge.getIdentifier(), KEGG_NAME, rea.getName()); edgeAttr.setAttribute(edge.getIdentifier(), KEGG_REACTION_TYPE, rea.getType()); } } } } else { for (Reaction rea : reactions) { CyNode reaNode = nodeMap.get(rea.getId()); System.out.println(rea.getId()); System.out.println(reaNode.getIdentifier()); if (rea.getType().equals("irreversible")) { for (Substrate sub : rea.getSubstrate()) { CyNode subNode = nodeMap.get(sub.getId()); CyEdge edge = Cytoscape.getCyEdge(subNode, reaNode, Semantics.INTERACTION, "cr", true, true); edges.add(edge); edgeAttr.setAttribute(edge.getIdentifier(), KEGG_NAME, rea.getName()); edgeAttr.setAttribute(edge.getIdentifier(), KEGG_REACTION_TYPE, rea.getType()); } for (Product pro : rea.getProduct()) { CyNode proNode = nodeMap.get(pro.getId()); CyEdge edge = Cytoscape.getCyEdge(reaNode, proNode, Semantics.INTERACTION, "rc", true, true); edges.add(edge); edgeAttr.setAttribute(edge.getIdentifier(), KEGG_NAME, rea.getName()); edgeAttr.setAttribute(edge.getIdentifier(), KEGG_REACTION_TYPE, rea.getType()); } } else { for (Substrate sub : rea.getSubstrate()) { System.out.println(sub.getId()); CyNode subNode = nodeMap.get(sub.getId()); System.out.println(subNode.getIdentifier()); CyEdge subEdge = Cytoscape.getCyEdge(subNode, reaNode, Semantics.INTERACTION, "cr", true, true); edges.add(subEdge); edgeAttr.setAttribute(subEdge.getIdentifier(), KEGG_NAME, rea.getName()); edgeAttr.setAttribute(subEdge.getIdentifier(), KEGG_REACTION_TYPE, rea.getType()); CyEdge proEdge = Cytoscape.getCyEdge(reaNode, subNode, Semantics.INTERACTION, "rc", true, true); edges.add(proEdge); edgeAttr.setAttribute(proEdge.getIdentifier(), KEGG_NAME, rea.getName()); edgeAttr.setAttribute(proEdge.getIdentifier(), KEGG_REACTION_TYPE, rea.getType()); } for (Product pro : rea.getProduct()) { CyNode proNode = nodeMap.get(pro.getId()); CyEdge proEdge = Cytoscape.getCyEdge(reaNode, proNode, Semantics.INTERACTION, "rc", true, true); edges.add(proEdge); edgeAttr.setAttribute(proEdge.getIdentifier(), KEGG_NAME, rea.getName()); edgeAttr.setAttribute(proEdge.getIdentifier(), KEGG_REACTION_TYPE, rea.getType()); CyEdge subEdge = Cytoscape.getCyEdge(proNode, reaNode, Semantics.INTERACTION, "cr", true, true); edges.add(subEdge); edgeAttr.setAttribute(subEdge.getIdentifier(), KEGG_NAME, rea.getName()); edgeAttr.setAttribute(subEdge.getIdentifier(), KEGG_REACTION_TYPE, rea.getType()); } } } } return edges; } protected void updateView(final CyNetwork network) { final String vsName = "KEGG: " + pathway.getTitle() + "(" + pathwayName + ")"; final VisualStyle defStyle = new VisualStyle(vsName); NodeAppearanceCalculator nac = defStyle.getNodeAppearanceCalculator(); EdgeAppearanceCalculator eac = defStyle.getEdgeAppearanceCalculator(); GlobalAppearanceCalculator gac = defStyle .getGlobalAppearanceCalculator(); // Default values final Color nodeColor = Color.WHITE; final Color nodeLineColor = new Color(20, 20, 20); final Color nodeLabelColor = new Color(30, 30, 30); final Color geneNodeColor = new Color(153, 255, 153); final Font nodeLabelFont = new Font("SansSerif", 7, Font.PLAIN); gac.setDefaultBackgroundColor(Color.white); final PassThroughMapping m = new PassThroughMapping("", KEGG_LABEL); final Calculator nodeLabelMappingCalc = new BasicCalculator(vsName + "-" + "NodeLabelMapping", m, VisualPropertyType.NODE_LABEL); nac.setCalculator(nodeLabelMappingCalc); nac.setNodeSizeLocked(false); nac.getDefaultAppearance().set(VisualPropertyType.NODE_FILL_COLOR, nodeColor); nac.getDefaultAppearance().set(VisualPropertyType.NODE_SHAPE, NodeShape.ROUND_RECT); nac.getDefaultAppearance().set(VisualPropertyType.NODE_BORDER_COLOR, nodeLineColor); nac.getDefaultAppearance().set(VisualPropertyType.NODE_LINE_WIDTH, 1); nac.getDefaultAppearance().set(VisualPropertyType.NODE_LABEL_COLOR, nodeLabelColor); nac.getDefaultAppearance().set(VisualPropertyType.NODE_FONT_FACE, nodeLabelFont); nac.getDefaultAppearance().set(VisualPropertyType.NODE_FONT_SIZE, 6); // Default Edge appr eac.getDefaultAppearance().set(VisualPropertyType.EDGE_TGTARROW_SHAPE, ArrowShape.DELTA); final DiscreteMapping edgeLineStyle = new DiscreteMapping( LineStyle.SOLID, KEGG_RELATION_TYPE, ObjectMapping.EDGE_MAPPING); final Calculator edgeLineStyleCalc = new BasicCalculator(vsName + "-" + "EdgeLineStyleMapping", edgeLineStyle, VisualPropertyType.EDGE_LINE_STYLE); edgeLineStyle.putMapValue(KEGGRelationType.MAPLINK.getTag(), LineStyle.LONG_DASH); eac.setCalculator(edgeLineStyleCalc); final DiscreteMapping nodeShape = new DiscreteMapping(NodeShape.RECT, KEGG_ENTRY_TYPE, ObjectMapping.NODE_MAPPING); final Calculator nodeShapeCalc = new BasicCalculator(vsName + "-" + "NodeShapeMapping", nodeShape, VisualPropertyType.NODE_SHAPE); nodeShape.putMapValue(KEGGEntryType.MAP.getTag(), NodeShape.ROUND_RECT); nodeShape.putMapValue(KEGGEntryType.GENE.getTag(), NodeShape.RECT); nodeShape.putMapValue(KEGGEntryType.ORTHOLOG.getTag(), NodeShape.RECT); nodeShape.putMapValue(KEGGEntryType.COMPOUND.getTag(), NodeShape.ELLIPSE); nac.setCalculator(nodeShapeCalc); final DiscreteMapping nodeColorMap = new DiscreteMapping(nodeColor, KEGG_ENTRY_TYPE, ObjectMapping.NODE_MAPPING); final Calculator nodeColorCalc = new BasicCalculator(vsName + "-" + "NodeColorMapping", nodeColorMap, VisualPropertyType.NODE_FILL_COLOR); nodeColorMap.putMapValue(KEGGEntryType.GENE.getTag(), geneNodeColor); nac.setCalculator(nodeColorCalc); final DiscreteMapping nodeBorderColorMap = new DiscreteMapping( nodeColor, KEGG_ENTRY_TYPE, ObjectMapping.NODE_MAPPING); final Calculator nodeBorderColorCalc = new BasicCalculator(vsName + "-" + "NodeBorderColorMapping", nodeBorderColorMap, VisualPropertyType.NODE_BORDER_COLOR); nodeBorderColorMap.putMapValue(KEGGEntryType.MAP.getTag(), Color.BLUE); nac.setCalculator(nodeBorderColorCalc); final DiscreteMapping nodeWidth = new DiscreteMapping(30, "ID", ObjectMapping.NODE_MAPPING); final Calculator nodeWidthCalc = new BasicCalculator(vsName + "-" + "NodeWidthMapping", nodeWidth, VisualPropertyType.NODE_WIDTH); final DiscreteMapping nodeHeight = new DiscreteMapping(30, "ID", ObjectMapping.NODE_MAPPING); final Calculator nodeHeightCalc = new BasicCalculator(vsName + "-" + "NodeHeightMapping", nodeHeight, VisualPropertyType.NODE_HEIGHT); nac.setCalculator(nodeHeightCalc); nac.setCalculator(nodeWidthCalc); final CyNetworkView view = Cytoscape.getNetworkView(network .getIdentifier()); final CyAttributes nodeAttr = Cytoscape.getNodeAttributes(); nodeWidth.setControllingAttributeName("ID", null, false); nodeHeight.setControllingAttributeName("ID", null, false); for (String key : nodeMap.keySet()) { for (Graphics nodeGraphics : entryMap.get(key).getGraphics()) { if (KEGGShape.getShape(nodeGraphics.getType()) != -1) { final String nodeID = nodeMap.get(key).getIdentifier(); final NodeView nv = view.getNodeView(nodeMap.get(key)); nv.setXPosition(Double.parseDouble(nodeGraphics.getX())); nv.setYPosition(Double.parseDouble(nodeGraphics.getY())); final double w = Double .parseDouble(nodeGraphics.getWidth()); nodeAttr.setAttribute(nodeID, "KEGG.nodeWidth", w); nodeWidth.putMapValue(nodeID, w); final double h = Double.parseDouble(nodeGraphics .getHeight()); nodeAttr.setAttribute(nodeID, "KEGG.nodeHeight", h); nodeHeight.putMapValue(nodeID, h); nv.setShape(KEGGShape.getShape(nodeGraphics.getType())); } } } Cytoscape.getVisualMappingManager().getCalculatorCatalog() .addVisualStyle(defStyle); Cytoscape.getVisualMappingManager().setVisualStyle(defStyle); view.setVisualStyle(defStyle.getName()); Cytoscape.getVisualMappingManager().setNetworkView(view); view.redrawGraph(false, true); } public int[] getNodeIdx() { return nodeIdx; } public int[] getEdgeIdx() { return edgeIdx; } }
src/org/cytoscape/data/reader/kgml/PathwayMapper.java
package org.cytoscape.data.reader.kgml; import giny.view.NodeView; import java.awt.Color; import java.awt.Font; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.cytoscape.data.reader.kgml.generated.Entry; import org.cytoscape.data.reader.kgml.generated.Graphics; import org.cytoscape.data.reader.kgml.generated.Pathway; import org.cytoscape.data.reader.kgml.generated.Product; import org.cytoscape.data.reader.kgml.generated.Reaction; import org.cytoscape.data.reader.kgml.generated.Relation; import org.cytoscape.data.reader.kgml.generated.Substrate; import org.cytoscape.data.reader.kgml.generated.Subtype; import cytoscape.CyEdge; import cytoscape.CyNetwork; import cytoscape.CyNode; import cytoscape.Cytoscape; import cytoscape.data.CyAttributes; import cytoscape.data.Semantics; import cytoscape.view.CyNetworkView; import cytoscape.visual.ArrowShape; import cytoscape.visual.EdgeAppearanceCalculator; import cytoscape.visual.GlobalAppearanceCalculator; import cytoscape.visual.LineStyle; import cytoscape.visual.NodeAppearanceCalculator; import cytoscape.visual.NodeShape; import cytoscape.visual.VisualPropertyType; import cytoscape.visual.VisualStyle; import cytoscape.visual.calculators.BasicCalculator; import cytoscape.visual.calculators.Calculator; import cytoscape.visual.mappings.DiscreteMapping; import cytoscape.visual.mappings.ObjectMapping; import cytoscape.visual.mappings.PassThroughMapping; public class PathwayMapper { private final Pathway pathway; private final String pathwayName; private int[] nodeIdx; private int[] edgeIdx; private static final String KEGG_NAME = "KEGG.name"; private static final String KEGG_ENTRY_TYPE = "KEGG.entry"; private static final String KEGG_LABEL = "KEGG.label"; private static final String KEGG_RELATION_TYPE = "KEGG.relation"; private static final String KEGG_REACTION_TYPE = "KEGG.reaction"; private static final String KEGG_LINK = "KEGG.link"; public PathwayMapper(final Pathway pathway) { this.pathway = pathway; this.pathwayName = pathway.getName(); } public void doMapping() { mapNode(); final List<CyEdge> relationEdges = mapRelationEdge(); final List<CyEdge> reactionEdges = mapReactionEdge(); edgeIdx = new int[relationEdges.size() + reactionEdges.size()]; int idx = 0; for (CyEdge edge : reactionEdges) { edgeIdx[idx] = edge.getRootGraphIndex(); idx++; } for (CyEdge edge : relationEdges) { edgeIdx[idx] = edge.getRootGraphIndex(); idx++; } } private final Map<String, Entry> entryMap = new HashMap<String, Entry>(); final Map<String, CyNode> nodeMap = new HashMap<String, CyNode>(); // final Map<String, CyNode> cpdMap = new HashMap<String, CyNode>(); final Map<String, CyNode> id2cpdMap = new HashMap<String, CyNode>(); final Map<String, List<Entry>> cpdDataMap = new HashMap<String, List<Entry>>(); final Map<CyNode, Entry> geneDataMap = new HashMap<CyNode, Entry>(); private final Map<CyNode, String> entry2reaction = new HashMap<CyNode, String>(); private void mapNode() { final String pathwayID = pathway.getName(); final List<Entry> components = pathway.getEntry(); final CyAttributes nodeAttr = Cytoscape.getNodeAttributes(); for (final Entry comp : components) { for (Graphics grap : comp.getGraphics()) { if (!grap.getType().equals(KEGGShape.LINE.getTag())) { CyNode node = Cytoscape.getCyNode(pathwayID + "-" + comp.getId(), true); nodeAttr.setAttribute(node.getIdentifier(), KEGG_NAME, comp .getName()); if (comp.getLink() != null) nodeAttr.setAttribute(node.getIdentifier(), KEGG_LINK, comp.getLink()); nodeAttr.setAttribute(node.getIdentifier(), KEGG_ENTRY_TYPE, comp.getType()); final String reaction = comp.getReaction(); // Save reaction if (reaction != null) { entry2reaction.put(node, reaction); nodeAttr.setAttribute(node.getIdentifier(), "KEGG.reaction", reaction); } // final Graphics graphics = comp.getGraphics(); if (grap != null && grap.getName() != null) { nodeAttr.setAttribute(node.getIdentifier(), KEGG_LABEL, grap.getName()); } nodeMap.put(comp.getId(), node); entryMap.put(comp.getId(), comp); if (comp.getType().equals(KEGGEntryType.COMPOUND.getTag())) { id2cpdMap.put(comp.getId(), node); List<Entry> current = cpdDataMap.get(comp.getName()); if (current != null) { current.add(comp); } else { current = new ArrayList<Entry>(); current.add(comp); } cpdDataMap.put(comp.getName(), current); } else if (comp.getType().equals( KEGGEntryType.GENE.getTag()) || comp.getType().equals( KEGGEntryType.ORTHOLOG.getTag())) { geneDataMap.put(node, comp); } } } } nodeIdx = new int[nodeMap.values().size()]; int idx = 0; for (CyNode node : nodeMap.values()) { nodeIdx[idx] = node.getRootGraphIndex(); idx++; } } private List<CyEdge> mapRelationEdge() { final List<Relation> relations = pathway.getRelation(); final List<CyEdge> edges = new ArrayList<CyEdge>(); final CyAttributes edgeAttr = Cytoscape.getEdgeAttributes(); for (Relation rel : relations) { final String type = rel.getType(); if (rel.getType().equals(KEGGRelationType.MAPLINK.getTag())) { final List<Subtype> subs = rel.getSubtype(); if (entryMap.get(rel.getEntry1()).getType().equals( KEGGEntryType.MAP.getTag())) { CyNode maplinkNode = nodeMap.get(rel.getEntry1()); for (Subtype sub : subs) { CyNode cpdNode = nodeMap.get(sub.getValue()); System.out.println(maplinkNode.getIdentifier()); System.out.println(cpdNode.getIdentifier() + "\n\n"); CyEdge edge1 = Cytoscape.getCyEdge(cpdNode, maplinkNode, Semantics.INTERACTION, type, true, true); edges.add(edge1); edgeAttr.setAttribute(edge1.getIdentifier(), KEGG_RELATION_TYPE, type); CyEdge edge2 = Cytoscape.getCyEdge(maplinkNode, cpdNode, Semantics.INTERACTION, type, true, true); edges.add(edge2); edgeAttr.setAttribute(edge2.getIdentifier(), KEGG_RELATION_TYPE, type); } } else { CyNode maplinkNode = nodeMap.get(rel.getEntry2()); for (Subtype sub : subs) { CyNode cpdNode = nodeMap.get(sub.getValue()); System.out.println(maplinkNode.getIdentifier()); System.out.println(cpdNode.getIdentifier() + "\n\n"); CyEdge edge1 = Cytoscape.getCyEdge(cpdNode, maplinkNode, Semantics.INTERACTION, type, true, true); edges.add(edge1); edgeAttr.setAttribute(edge1.getIdentifier(), KEGG_RELATION_TYPE, type); CyEdge edge2 = Cytoscape.getCyEdge(maplinkNode, cpdNode, Semantics.INTERACTION, type, true, true); edges.add(edge2); edgeAttr.setAttribute(edge2.getIdentifier(), KEGG_RELATION_TYPE, type); } } } } return edges; } private List<CyEdge> mapReactionEdge() { final String pathwayID = pathway.getName(); final List<Reaction> reactions = pathway.getReaction(); final List<CyEdge> edges = new ArrayList<CyEdge>(); CyAttributes edgeAttr = Cytoscape.getEdgeAttributes(); Pattern pattern = Pattern.compile(".*01100"); if (pattern.matcher(pathwayID).matches()) { for (Reaction rea : reactions) { for (Substrate sub : rea.getSubstrate()) { CyNode subNode = nodeMap.get(sub.getId()); for (Product pro : rea.getProduct()) { CyNode proNode = nodeMap.get(pro.getId()); CyEdge edge = Cytoscape.getCyEdge(subNode, proNode, Semantics.INTERACTION, "cc", true); edges.add(edge); edgeAttr.setAttribute(edge.getIdentifier(), KEGG_REACTION_TYPE, rea.getName()); } } } } else { for (Reaction rea : reactions) { CyNode reaNode = nodeMap.get(rea.getId()); System.out.println(rea.getId()); System.out.println(reaNode.getIdentifier()); if (rea.getType().equals("irreversible")) { for (Substrate sub : rea.getSubstrate()) { CyNode subNode = nodeMap.get(sub.getId()); CyEdge edge = Cytoscape.getCyEdge(subNode, reaNode, Semantics.INTERACTION, "cr", true, true); edges.add(edge); edgeAttr.setAttribute(edge.getIdentifier(), KEGG_REACTION_TYPE, "substrate"); } for (Product pro : rea.getProduct()) { CyNode proNode = nodeMap.get(pro.getId()); CyEdge edge = Cytoscape.getCyEdge(reaNode, proNode, Semantics.INTERACTION, "rc", true, true); edges.add(edge); edgeAttr.setAttribute(edge.getIdentifier(), KEGG_REACTION_TYPE, "product"); } } else { for (Substrate sub : rea.getSubstrate()) { System.out.println(sub.getId()); CyNode subNode = nodeMap.get(sub.getId()); System.out.println(subNode.getIdentifier()); CyEdge subEdge = Cytoscape.getCyEdge(subNode, reaNode, Semantics.INTERACTION, "cr", true, true); edges.add(subEdge); edgeAttr.setAttribute(subEdge.getIdentifier(), KEGG_REACTION_TYPE, "substrate"); CyEdge proEdge = Cytoscape.getCyEdge(reaNode, subNode, Semantics.INTERACTION, "rc", true, true); edges.add(proEdge); edgeAttr.setAttribute(proEdge.getIdentifier(), KEGG_REACTION_TYPE, "product"); } for (Product pro : rea.getProduct()) { CyNode proNode = nodeMap.get(pro.getId()); CyEdge proEdge = Cytoscape.getCyEdge(reaNode, proNode, Semantics.INTERACTION, "rc", true, true); edges.add(proEdge); edgeAttr.setAttribute(proEdge.getIdentifier(), KEGG_REACTION_TYPE, "product"); CyEdge subEdge = Cytoscape.getCyEdge(proNode, reaNode, Semantics.INTERACTION, "cr", true, true); edges.add(subEdge); edgeAttr.setAttribute(subEdge.getIdentifier(), KEGG_REACTION_TYPE, "substrate"); } } } } return edges; } protected void updateView(final CyNetwork network) { final String vsName = "KEGG: " + pathway.getTitle() + "(" + pathwayName + ")"; final VisualStyle defStyle = new VisualStyle(vsName); NodeAppearanceCalculator nac = defStyle.getNodeAppearanceCalculator(); EdgeAppearanceCalculator eac = defStyle.getEdgeAppearanceCalculator(); GlobalAppearanceCalculator gac = defStyle .getGlobalAppearanceCalculator(); // Default values final Color nodeColor = Color.WHITE; final Color nodeLineColor = new Color(20, 20, 20); final Color nodeLabelColor = new Color(30, 30, 30); final Color geneNodeColor = new Color(153, 255, 153); final Font nodeLabelFont = new Font("SansSerif", 7, Font.PLAIN); gac.setDefaultBackgroundColor(Color.white); final PassThroughMapping m = new PassThroughMapping("", KEGG_LABEL); final Calculator nodeLabelMappingCalc = new BasicCalculator(vsName + "-" + "NodeLabelMapping", m, VisualPropertyType.NODE_LABEL); nac.setCalculator(nodeLabelMappingCalc); nac.setNodeSizeLocked(false); nac.getDefaultAppearance().set(VisualPropertyType.NODE_FILL_COLOR, nodeColor); nac.getDefaultAppearance().set(VisualPropertyType.NODE_SHAPE, NodeShape.ROUND_RECT); nac.getDefaultAppearance().set(VisualPropertyType.NODE_BORDER_COLOR, nodeLineColor); nac.getDefaultAppearance().set(VisualPropertyType.NODE_LINE_WIDTH, 1); nac.getDefaultAppearance().set(VisualPropertyType.NODE_LABEL_COLOR, nodeLabelColor); nac.getDefaultAppearance().set(VisualPropertyType.NODE_FONT_FACE, nodeLabelFont); nac.getDefaultAppearance().set(VisualPropertyType.NODE_FONT_SIZE, 6); // Default Edge appr eac.getDefaultAppearance().set(VisualPropertyType.EDGE_TGTARROW_SHAPE, ArrowShape.DELTA); final DiscreteMapping edgeLineStyle = new DiscreteMapping( LineStyle.SOLID, KEGG_RELATION_TYPE, ObjectMapping.EDGE_MAPPING); final Calculator edgeLineStyleCalc = new BasicCalculator(vsName + "-" + "EdgeLineStyleMapping", edgeLineStyle, VisualPropertyType.EDGE_LINE_STYLE); edgeLineStyle.putMapValue(KEGGRelationType.MAPLINK.getTag(), LineStyle.LONG_DASH); eac.setCalculator(edgeLineStyleCalc); final DiscreteMapping nodeShape = new DiscreteMapping(NodeShape.RECT, KEGG_ENTRY_TYPE, ObjectMapping.NODE_MAPPING); final Calculator nodeShapeCalc = new BasicCalculator(vsName + "-" + "NodeShapeMapping", nodeShape, VisualPropertyType.NODE_SHAPE); nodeShape.putMapValue(KEGGEntryType.MAP.getTag(), NodeShape.ROUND_RECT); nodeShape.putMapValue(KEGGEntryType.GENE.getTag(), NodeShape.RECT); nodeShape.putMapValue(KEGGEntryType.ORTHOLOG.getTag(), NodeShape.RECT); nodeShape.putMapValue(KEGGEntryType.COMPOUND.getTag(), NodeShape.ELLIPSE); nac.setCalculator(nodeShapeCalc); final DiscreteMapping nodeColorMap = new DiscreteMapping(nodeColor, KEGG_ENTRY_TYPE, ObjectMapping.NODE_MAPPING); final Calculator nodeColorCalc = new BasicCalculator(vsName + "-" + "NodeColorMapping", nodeColorMap, VisualPropertyType.NODE_FILL_COLOR); nodeColorMap.putMapValue(KEGGEntryType.GENE.getTag(), geneNodeColor); nac.setCalculator(nodeColorCalc); final DiscreteMapping nodeBorderColorMap = new DiscreteMapping( nodeColor, KEGG_ENTRY_TYPE, ObjectMapping.NODE_MAPPING); final Calculator nodeBorderColorCalc = new BasicCalculator(vsName + "-" + "NodeBorderColorMapping", nodeBorderColorMap, VisualPropertyType.NODE_BORDER_COLOR); nodeBorderColorMap.putMapValue(KEGGEntryType.MAP.getTag(), Color.BLUE); nac.setCalculator(nodeBorderColorCalc); final DiscreteMapping nodeWidth = new DiscreteMapping(30, "ID", ObjectMapping.NODE_MAPPING); final Calculator nodeWidthCalc = new BasicCalculator(vsName + "-" + "NodeWidthMapping", nodeWidth, VisualPropertyType.NODE_WIDTH); final DiscreteMapping nodeHeight = new DiscreteMapping(30, "ID", ObjectMapping.NODE_MAPPING); final Calculator nodeHeightCalc = new BasicCalculator(vsName + "-" + "NodeHeightMapping", nodeHeight, VisualPropertyType.NODE_HEIGHT); nac.setCalculator(nodeHeightCalc); nac.setCalculator(nodeWidthCalc); final CyNetworkView view = Cytoscape.getNetworkView(network .getIdentifier()); final CyAttributes nodeAttr = Cytoscape.getNodeAttributes(); nodeWidth.setControllingAttributeName("ID", null, false); nodeHeight.setControllingAttributeName("ID", null, false); for (String key : nodeMap.keySet()) { for (Graphics nodeGraphics : entryMap.get(key).getGraphics()) { if (KEGGShape.getShape(nodeGraphics.getType()) != -1) { final String nodeID = nodeMap.get(key).getIdentifier(); final NodeView nv = view.getNodeView(nodeMap.get(key)); nv.setXPosition(Double.parseDouble(nodeGraphics.getX())); nv.setYPosition(Double.parseDouble(nodeGraphics.getY())); final double w = Double .parseDouble(nodeGraphics.getWidth()); nodeAttr.setAttribute(nodeID, "KEGG.nodeWidth", w); nodeWidth.putMapValue(nodeID, w); final double h = Double.parseDouble(nodeGraphics .getHeight()); nodeAttr.setAttribute(nodeID, "KEGG.nodeHeight", h); nodeHeight.putMapValue(nodeID, h); nv.setShape(KEGGShape.getShape(nodeGraphics.getType())); } } } Cytoscape.getVisualMappingManager().getCalculatorCatalog() .addVisualStyle(defStyle); Cytoscape.getVisualMappingManager().setVisualStyle(defStyle); view.setVisualStyle(defStyle.getName()); Cytoscape.getVisualMappingManager().setNetworkView(view); view.redrawGraph(false, true); } public int[] getNodeIdx() { return nodeIdx; } public int[] getEdgeIdx() { return edgeIdx; } }
modified edge attribute git-svn-id: 7b9ef9234d626f3af90deabf5e615f70ebb4b6a1@7 bac3df7d-1e23-83cd-b5da-1fcb26fd12d5
src/org/cytoscape/data/reader/kgml/PathwayMapper.java
modified edge attribute
<ide><path>rc/org/cytoscape/data/reader/kgml/PathwayMapper.java <ide> cpdNode, Semantics.INTERACTION, type, true, <ide> true); <ide> edges.add(edge2); <del> edgeAttr.setAttribute(edge2.getIdentifier(), <del> KEGG_RELATION_TYPE, type); <add>// edgeAttr.setAttribute(edge2.getIdentifier(), <add>// KEGG_RELATION_TYPE, type); <ide> } <ide> } else { <ide> CyNode maplinkNode = nodeMap.get(rel.getEntry2()); <ide> cpdNode, Semantics.INTERACTION, type, true, <ide> true); <ide> edges.add(edge2); <del> edgeAttr.setAttribute(edge2.getIdentifier(), <del> KEGG_RELATION_TYPE, type); <add>// edgeAttr.setAttribute(edge2.getIdentifier(), <add>// KEGG_RELATION_TYPE, type); <ide> } <ide> } <ide> } <ide> Semantics.INTERACTION, "cc", true); <ide> edges.add(edge); <ide> edgeAttr.setAttribute(edge.getIdentifier(), <del> KEGG_REACTION_TYPE, rea.getName()); <add> KEGG_NAME, rea.getName()); <add> edgeAttr.setAttribute(edge.getIdentifier(), <add> KEGG_REACTION_TYPE, rea.getType()); <ide> } <ide> } <ide> } <ide> Semantics.INTERACTION, "cr", true, true); <ide> edges.add(edge); <ide> edgeAttr.setAttribute(edge.getIdentifier(), <del> KEGG_REACTION_TYPE, "substrate"); <add> KEGG_NAME, rea.getName()); <add> edgeAttr.setAttribute(edge.getIdentifier(), <add> KEGG_REACTION_TYPE, rea.getType()); <ide> } <ide> for (Product pro : rea.getProduct()) { <ide> CyNode proNode = nodeMap.get(pro.getId()); <ide> Semantics.INTERACTION, "rc", true, true); <ide> edges.add(edge); <ide> edgeAttr.setAttribute(edge.getIdentifier(), <del> KEGG_REACTION_TYPE, "product"); <add> KEGG_NAME, rea.getName()); <add> edgeAttr.setAttribute(edge.getIdentifier(), <add> KEGG_REACTION_TYPE, rea.getType()); <ide> } <ide> <ide> } else { <ide> Semantics.INTERACTION, "cr", true, true); <ide> edges.add(subEdge); <ide> edgeAttr.setAttribute(subEdge.getIdentifier(), <del> KEGG_REACTION_TYPE, "substrate"); <add> KEGG_NAME, rea.getName()); <add> edgeAttr.setAttribute(subEdge.getIdentifier(), <add> KEGG_REACTION_TYPE, rea.getType()); <ide> <ide> CyEdge proEdge = Cytoscape.getCyEdge(reaNode, subNode, <ide> Semantics.INTERACTION, "rc", true, true); <ide> edges.add(proEdge); <ide> edgeAttr.setAttribute(proEdge.getIdentifier(), <del> KEGG_REACTION_TYPE, "product"); <add> KEGG_NAME, rea.getName()); <add> edgeAttr.setAttribute(proEdge.getIdentifier(), <add> KEGG_REACTION_TYPE, rea.getType()); <ide> } <ide> for (Product pro : rea.getProduct()) { <ide> CyNode proNode = nodeMap.get(pro.getId()); <ide> Semantics.INTERACTION, "rc", true, true); <ide> edges.add(proEdge); <ide> edgeAttr.setAttribute(proEdge.getIdentifier(), <del> KEGG_REACTION_TYPE, "product"); <add> KEGG_NAME, rea.getName()); <add> edgeAttr.setAttribute(proEdge.getIdentifier(), <add> KEGG_REACTION_TYPE, rea.getType()); <ide> <ide> CyEdge subEdge = Cytoscape.getCyEdge(proNode, reaNode, <ide> Semantics.INTERACTION, "cr", true, true); <ide> edges.add(subEdge); <ide> edgeAttr.setAttribute(subEdge.getIdentifier(), <del> KEGG_REACTION_TYPE, "substrate"); <add> KEGG_NAME, rea.getName()); <add> edgeAttr.setAttribute(subEdge.getIdentifier(), <add> KEGG_REACTION_TYPE, rea.getType()); <ide> } <ide> } <ide> }
JavaScript
mit
58838037aba926a7f34e495de3616ad03a2f266e
0
saydulk/stalker_portal,saydulk/stalker_portal,saydulk/stalker_portal,saydulk/stalker_portal,saydulk/stalker_portal
/** * Player constructor * @constructor */ function player(){ var self = this; this.on = false; this.f_ch_idx = 0; this.ch_idx = 0; this.channels; this.fav_channels; this.fav_channels_ids; this.start_time; this.cur_media_item; this.need_show_info = 0; this.pause = {"on" : false}; this.is_tv = false; this.prev_layer = {}; this.info = {"on" : false, "hide_timer" : 2000}; this.init(); this.init_pause(); this.init_show_info(); } player.prototype.init = function(){ _debug('player.init'); try{ stb.InitPlayer(); stb.SetTopWin(0); stb.SetAspect(0x10); stb.SetPIG(1, -1, -1, -1); stb.SetUserFlickerControl(1); stb.SetDefaultFlicker(1); stb.SetLoop(0); stb.SetMicVolume(100); stbEvent.onEvent = (function(self){ return function(){ self.event_callback.apply(self, arguments); } })(this); }catch(e){ _debug(e); } } player.prototype.event_callback = function(event){ _debug('event: ', event); var event = parseInt(event); switch(event){ case 1: // End of stream { try{ this.prev_layer && this.prev_layer.show && this.prev_layer.show.call(this.prev_layer, true); this.stop(); }catch(e){ _debug(e); } break; } case 4: // Playback started { break; } } } player.prototype.volume_bar = new function(){ this.volume = 100; this.volume_bar_dom_obj = $('volume_bar'); this.set_volume = function(v){ this.volume = v; stb.SetVolume(this.volume); } this.show = function(){ this.volume_bar_dom_obj.show(); } this.hide = function(){ this.volume_bar_dom_obj.hide(); } this.save = function(){ stb.load( { 'type' : 'stb', 'action' : 'set_volume', 'vol' : this.volume }, function(result){ } ); } } player.prototype.seek_bar = new function(){ this.seek_bar_dom_obj = $('seek_bar'); this.show = function(){ this.seek_bar_dom_obj.show(); } this.hide = function(){ this.seek_bar_dom_obj.hide(); } this.set_pos = function(){ } } player.prototype.define_media_type = function(cmd){ if (cmd.indexOf('://') > 0){ if (cmd.indexOf('udp://') || cmd.indexOf('rtp://')){ this.is_tv = true; } return 'stream'; }else{ this.is_tv = false; return 'file'; } } player.prototype.play_last = function(){ _debug('player.play_last'); this.play(this.cur_media_item); } player.prototype.play = function(item){ _debug('player.play'); var cmd; this.on = true; this.cur_media_item = item; if (typeof(item) == 'object'){ if (!item.hasOwnProperty('cmd')){ return; } cmd = item.cmd; }else{ cmd = item; } _debug('cmd: ', cmd); this.media_type = this.define_media_type(cmd); _debug('player.media_type: ', this.media_type); if (this.media_type == 'stream'){ this.play_now(cmd); if (this.is_tv){ this.send_last_tv_id(item.id); } }else{ this.create_link('vod', cmd); } } player.prototype.create_link = function(type, uri){ stb.load( { 'type' : type, 'action' : 'create_link', 'cmd' : uri, 'series' : '' }, function(result){ _debug('create_link callback: ', result); this.play_now(result.cmd); }, this ) } player.prototype.play_now = function(uri){ _debug('player.play_now'); this.start_time = Date.parse(new Date())/1000; if (this.need_show_info){ this.show_info(cur_media_item); } try{ stb.Play(uri); }catch(e){_debug(e)} } player.prototype.stop = function(){ _debug('player.stop'); this.prev_layer = {}; this.need_show_info = 0; this.on = false; if(this.pause.on){ this.disable_pause(); } try{ stb.Stop(); }catch(e){} } player.prototype.init_pause = function(){ this.pause.dom_obj = create_block_element('pause'); this.pause.dom_obj.hide(); } player.prototype.pause_switch = function(){ _debug('player.pause_switch'); if (this.is_tv){ return; } if (this.pause.on){ this.disable_pause(); }else{ try{ stb.Pause(); }catch(e){}; this.pause.on = true; this.pause.dom_obj.show(); } } player.prototype.disable_pause = function(){ try{ stb.Continue(); }catch(e){}; this.pause.on = false; this.pause.dom_obj.hide(); } player.prototype.show_info_after_play = function(){ this.need_show_info = 1; } player.prototype.init_show_info = function(){ this.info.dom_obj = create_block_element("osd_info"); this.info.title = create_block_element("osd_info_title", this.info['dom_obj']); this.info.epg = create_block_element("osd_info_epg", this.info['dom_obj']); this.info.dom_obj.hide(); } player.prototype.show_info = function(item){ _debug('show_info'); try{ if(this.info.on){ window.clearTimeout(this.info.hide_timeout); }else{ this.info.dom_obj.show(); this.info.on = true; } var title = ''; if (item.hasOwnProperty('number')){ title = item.number + '. '; } title += item.name this.info.title.innerHTML = title; var self = this; this.info.hide_timeout = window.setTimeout(function(){ self.info.dom_obj.hide(); self.info.on = false }, this.info.hide_timer); }catch(e){ _debug(e); } } player.prototype.switch_channel = function(dir, show_info){ _debug('switch_channel', dir); if (!this.is_tv){ return; } if (dir > 0){ if (stb.user.fav_itv_on){ if (this.f_ch_idx < this.fav_channels.length-1){ this.f_ch_idx++; }else{ this.f_ch_idx = 0; } _debug('this.f_ch_idx:', this.f_ch_idx); if (show_info){ this.show_info(this.fav_channels[this.f_ch_idx]); } this.play(this.fav_channels[this.f_ch_idx]); }else{ if (this.ch_idx < this.channels.length-1){ this.ch_idx++; }else{ this.ch_idx = 0; } _debug('this.ch_idx:', this.ch_idx); if (show_info){ this.show_info(this.channels[this.ch_idx]); } this.play(this.channels[this.ch_idx]); } }else{ if (stb.user.fav_itv_on){ if (this.f_ch_idx > 0){ this.f_ch_idx--; }else{ this.f_ch_idx = this.fav_channels.length-1; } _debug('this.f_ch_idx:', this.f_ch_idx); if (show_info){ this.show_info(this.fav_channels[this.f_ch_idx]); } this.play(this.fav_channels[this.f_ch_idx]); }else{ if (this.ch_idx > 0){ this.ch_idx--; }else{ this.ch_idx = this.channels.length-1; } _debug('this.ch_idx:', this.ch_idx); if (show_info){ this.show_info(this.channels[this.ch_idx]); } this.play(this.channels[this.ch_idx]); } } } player.prototype.send_last_tv_id = function(id){ _debug('send_last_tv_id', id); stb.load( { 'type' : 'itv', 'action' : 'set_last_id', 'id' : id }, function(result){ _debug('last_tv_id saved', result); } ) } player.prototype.show_prev_layer = function(){ _debug('player.show_prev_layer'); this.prev_layer.show.call(this.prev_layer, true); this.stop(); } player.prototype.bind = function(){ var self = this; this.switch_channel.bind(key.UP, self, 1); this.switch_channel.bind(key.DOWN, self, -1); this.switch_channel.bind(key.CHANNEL_NEXT, self, 1, true); this.switch_channel.bind(key.CHANNEL_PREV, self, -1, true); this.pause_switch.bind(key.PAUSE, this); this.show_prev_layer.bind(key.EXIT, self); } player.prototype.save_fav_ids = function(){ _debug('player.save_fav'); stb.load( { 'type' : 'itv', 'action' : 'set_fav', 'fav_ch' : this.fav_channels_ids }, function(result){ _debug('fav_saved', result); }, this ) } /* * END Player */
c/player.js
/** * Player constructor * @constructor */ function player(){ var self = this; this.on = false; this.f_ch_idx = 0; this.ch_idx = 0; this.channels; this.fav_channels; this.fav_channels_ids; this.start_time; this.cur_media_item; this.paused = false; this.need_show_info = 0; this.pause_dom_obj = $('pause'); this.is_tv = false; this.prev_layer = {}; this.init(); } player.prototype.init = function(){ _debug('player.init'); try{ stb.InitPlayer(); stb.SetTopWin(0); stb.SetAspect(0x10); stb.SetPIG(1, -1, -1, -1); stb.SetUserFlickerControl(1); stb.SetDefaultFlicker(1); stb.SetLoop(0); stb.SetMicVolume(100); stbEvent.onEvent = (function(self){ return function(){ self.event_callback.apply(self, arguments); } })(this); }catch(e){ _debug(e); } } player.prototype.event_callback = function(event){ _debug('event: ', event); var event = parseInt(event); switch(event){ case 1: // End of stream { try{ this.prev_layer && this.prev_layer.show && this.prev_layer.show.call(this.prev_layer, true); this.stop(); }catch(e){ _debug(e); } break; } case 4: // Playback started { break; } } } player.prototype.volume_bar = new function(){ this.volume = 100; this.volume_bar_dom_obj = $('volume_bar'); this.set_volume = function(v){ this.volume = v; stb.SetVolume(this.volume); } this.show = function(){ this.volume_bar_dom_obj.show(); } this.hide = function(){ this.volume_bar_dom_obj.hide(); } this.save = function(){ stb.load( { 'type' : 'stb', 'action' : 'set_volume', 'vol' : this.volume }, function(result){ } ); } } player.prototype.seek_bar = new function(){ this.seek_bar_dom_obj = $('seek_bar'); this.show = function(){ this.seek_bar_dom_obj.show(); } this.hide = function(){ this.seek_bar_dom_obj.hide(); } this.set_pos = function(){ } } player.prototype.define_media_type = function(cmd){ if (cmd.indexOf('://') > 0){ if (cmd.indexOf('udp://') || cmd.indexOf('rtp://')){ this.is_tv = true; } return 'stream'; }else{ this.is_tv = false; return 'file'; } } player.prototype.play_last = function(){ _debug('player.play_last'); this.play(this.cur_media_item); } player.prototype.play = function(item){ _debug('player.play'); var cmd; this.on = true; this.cur_media_item = item; if (typeof(item) == 'object'){ if (!item.hasOwnProperty('cmd')){ return; } cmd = item.cmd; }else{ cmd = item; } _debug('cmd: ', cmd); this.media_type = this.define_media_type(cmd); _debug('player.media_type: ', this.media_type); if (this.media_type == 'stream'){ this.play_now(cmd); }else{ this.create_link('vod', cmd); } } player.prototype.create_link = function(type, uri){ stb.load( { 'type' : type, 'action' : 'create_link', 'cmd' : uri, 'series' : '' }, function(result){ _debug('create_link callback: ', result); this.play_now(result.cmd); }, this ) } player.prototype.play_now = function(uri){ _debug('player.play_now'); this.start_time = Date.parse(new Date())/1000; if (this.need_show_info){ this.show_info(cur_media_item); } try{ stb.Play(uri); }catch(e){_debug(e)} } player.prototype.stop = function(){ _debug('player.stop'); this.prev_layer = {}; this.need_show_info = 0; this.on = false; try{ stb.Stop(); }catch(e){} } player.prototype.pause = function(){ _debug('player.pause'); if (this.paused){ try{ stb.Continue(); }catch(e){}; this.paused = false; this.pause_dom_obj.hide(); }else{ try{ stb.Pause(); }catch(e){}; this.paused = true; this.pause_dom_obj.show(); } } player.prototype.show_info_after_play = function(){ this.need_show_info = 1; } player.prototype.show_info = function(item){ } player.prototype.switch_channel = function(dir){ _debug('switch_channel', dir); if (!this.is_tv){ return; } if (dir > 0){ if (stb.user.fav_itv_on){ if (this.f_ch_idx < this.fav_channels.length-1){ this.f_ch_idx++; }else{ this.f_ch_idx = 0; } _debug('this.f_ch_idx:', this.f_ch_idx); this.show_info(this.fav_channels[this.f_ch_idx]); this.play(this.fav_channels[this.f_ch_idx]); }else{ if (this.ch_idx < this.channels.length-1){ this.ch_idx++; }else{ this.ch_idx = 0; } _debug('this.ch_idx:', this.ch_idx); this.show_info(this.channels[this.ch_idx]); this.play(this.channels[this.ch_idx]); } }else{ if (stb.user.fav_itv_on){ if (this.f_ch_idx > 0){ this.f_ch_idx--; }else{ this.f_ch_idx = this.fav_channels.length-1; } _debug('this.f_ch_idx:', this.f_ch_idx); this.show_info(this.fav_channels[this.f_ch_idx]); this.play(this.fav_channels[this.f_ch_idx]); }else{ if (this.ch_idx > 0){ this.ch_idx--; }else{ this.ch_idx = this.channels.length-1; } _debug('this.ch_idx:', this.ch_idx); this.show_info(this.channels[this.ch_idx]); this.play(this.channels[this.ch_idx]); } } } player.prototype.show_prev_layer = function(){ _debug('player.show_prev_layer'); this.prev_layer.show.call(this.prev_layer, true); this.stop(); } player.prototype.bind = function(){ var self = this; this.switch_channel.bind(key.UP, self, 1); this.switch_channel.bind(key.DOWN, self, -1); this.show_prev_layer.bind(key.EXIT, self); } player.prototype.save_fav_ids = function(){ _debug('player.save_fav'); stb.load( { 'type' : 'itv', 'action' : 'set_fav', 'fav_ch' : this.fav_channels_ids }, function(result){ _debug('fav_saved', result); }, this ) } /* * END Player */
"Add pause, osd"
c/player.js
"Add pause, osd"
<ide><path>/player.js <ide> <ide> this.start_time; <ide> this.cur_media_item; <del> this.paused = false; <ide> this.need_show_info = 0; <ide> <del> this.pause_dom_obj = $('pause'); <add> this.pause = {"on" : false}; <ide> <ide> this.is_tv = false; <ide> <ide> this.prev_layer = {}; <ide> <add> this.info = {"on" : false, "hide_timer" : 2000}; <add> <ide> this.init(); <add> this.init_pause(); <add> this.init_show_info(); <ide> } <ide> <ide> player.prototype.init = function(){ <ide> <ide> if (this.media_type == 'stream'){ <ide> this.play_now(cmd); <add> <add> if (this.is_tv){ <add> this.send_last_tv_id(item.id); <add> } <add> <ide> }else{ <ide> this.create_link('vod', cmd); <ide> } <ide> <ide> this.on = false; <ide> <add> if(this.pause.on){ <add> this.disable_pause(); <add> } <add> <ide> try{ <ide> stb.Stop(); <ide> }catch(e){} <ide> } <ide> <del>player.prototype.pause = function(){ <del> _debug('player.pause'); <del> <del> if (this.paused){ <del> try{ <del> stb.Continue(); <del> }catch(e){}; <del> this.paused = false; <del> this.pause_dom_obj.hide(); <add>player.prototype.init_pause = function(){ <add> this.pause.dom_obj = create_block_element('pause'); <add> this.pause.dom_obj.hide(); <add>} <add> <add>player.prototype.pause_switch = function(){ <add> _debug('player.pause_switch'); <add> <add> if (this.is_tv){ <add> return; <add> } <add> <add> if (this.pause.on){ <add> this.disable_pause(); <ide> }else{ <ide> try{ <ide> stb.Pause(); <ide> }catch(e){}; <del> this.paused = true; <del> this.pause_dom_obj.show(); <del> } <del> <add> this.pause.on = true; <add> this.pause.dom_obj.show(); <add> } <add>} <add> <add>player.prototype.disable_pause = function(){ <add> try{ <add> stb.Continue(); <add> }catch(e){}; <add> this.pause.on = false; <add> this.pause.dom_obj.hide(); <ide> } <ide> <ide> player.prototype.show_info_after_play = function(){ <ide> this.need_show_info = 1; <ide> } <ide> <add>player.prototype.init_show_info = function(){ <add> <add> this.info.dom_obj = create_block_element("osd_info"); <add> <add> this.info.title = create_block_element("osd_info_title", this.info['dom_obj']); <add> <add> this.info.epg = create_block_element("osd_info_epg", this.info['dom_obj']); <add> <add> this.info.dom_obj.hide(); <add>} <add> <ide> player.prototype.show_info = function(item){ <del> <del>} <del> <del>player.prototype.switch_channel = function(dir){ <add> _debug('show_info'); <add> <add> try{ <add> if(this.info.on){ <add> window.clearTimeout(this.info.hide_timeout); <add> }else{ <add> this.info.dom_obj.show(); <add> this.info.on = true; <add> } <add> <add> var title = ''; <add> <add> if (item.hasOwnProperty('number')){ <add> title = item.number + '. '; <add> } <add> <add> title += item.name <add> <add> this.info.title.innerHTML = title; <add> <add> var self = this; <add> <add> this.info.hide_timeout = window.setTimeout(function(){ <add> self.info.dom_obj.hide(); <add> self.info.on = false <add> }, <add> this.info.hide_timer); <add> }catch(e){ <add> _debug(e); <add> } <add>} <add> <add>player.prototype.switch_channel = function(dir, show_info){ <ide> <ide> _debug('switch_channel', dir); <ide> <ide> <ide> _debug('this.f_ch_idx:', this.f_ch_idx); <ide> <del> this.show_info(this.fav_channels[this.f_ch_idx]); <add> if (show_info){ <add> this.show_info(this.fav_channels[this.f_ch_idx]); <add> } <add> <ide> this.play(this.fav_channels[this.f_ch_idx]); <ide> <ide> }else{ <ide> } <ide> <ide> _debug('this.ch_idx:', this.ch_idx); <del> <del> this.show_info(this.channels[this.ch_idx]); <add> <add> if (show_info){ <add> this.show_info(this.channels[this.ch_idx]); <add> } <add> <ide> this.play(this.channels[this.ch_idx]); <ide> } <ide> <ide> <ide> _debug('this.f_ch_idx:', this.f_ch_idx); <ide> <del> this.show_info(this.fav_channels[this.f_ch_idx]); <add> if (show_info){ <add> this.show_info(this.fav_channels[this.f_ch_idx]); <add> } <ide> this.play(this.fav_channels[this.f_ch_idx]); <ide> <ide> }else{ <ide> <ide> _debug('this.ch_idx:', this.ch_idx); <ide> <del> this.show_info(this.channels[this.ch_idx]); <add> if (show_info){ <add> this.show_info(this.channels[this.ch_idx]); <add> } <ide> this.play(this.channels[this.ch_idx]); <ide> } <ide> } <add>} <add> <add>player.prototype.send_last_tv_id = function(id){ <add> _debug('send_last_tv_id', id); <add> <add> stb.load( <add> <add> { <add> 'type' : 'itv', <add> 'action' : 'set_last_id', <add> 'id' : id <add> }, <add> <add> function(result){ <add> _debug('last_tv_id saved', result); <add> } <add> ) <ide> } <ide> <ide> player.prototype.show_prev_layer = function(){ <ide> <ide> this.switch_channel.bind(key.UP, self, 1); <ide> this.switch_channel.bind(key.DOWN, self, -1); <add> <add> this.switch_channel.bind(key.CHANNEL_NEXT, self, 1, true); <add> this.switch_channel.bind(key.CHANNEL_PREV, self, -1, true); <add> <add> this.pause_switch.bind(key.PAUSE, this); <ide> <ide> this.show_prev_layer.bind(key.EXIT, self); <ide> }
Java
bsd-3-clause
11d0d7b12641d1b28d368536b882c6b0adb73564
0
johanneskoester/libmodallogic
/* Copyright (c) 2010, Johannes Köster <[email protected]> * All rights reserved. * * This software is open-source under the BSD license; see "license.txt" * for a description. */ package modalLogic.tableau; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.List; import modalLogic.formula.Formula; import modalLogic.formula.Literal; import org.apache.commons.collections15.iterators.IteratorChain; import util.Pair; /** * The currently investigated branch of the tableau. * * @author Johannes Köster <[email protected]> */ public class Branch<P> { private Tableau<P> tableau; private Comparator<P> propositionComparator; private List<LabelledFormula<P>> unexpanded; /** * Constructor of class Branch. * * @param tableau the tableau * @param propositionComparator a comparator for propositions */ public Branch(Tableau<P> tableau, Comparator<P> propositionComparator) { this.tableau = tableau; this.propositionComparator = propositionComparator; unexpanded = new ArrayList<LabelledFormula<P>>(); } /** * Returns a list of unexpanded subformulas. * * @return a list of unexpanded subformulas */ public List<LabelledFormula<P>> getUnexpanded() { return unexpanded; } /** * Clears the list of unexpanded subformulas. */ public void clear() { unexpanded.clear(); } /** * Add a subformula to the branch. * * @param f the subformula */ public void add(LabelledFormula<P> f) { if (f.getFormula().getType() == Formula.LITERAL) { f.getWorld().addLiteral(f); } unexpanded.add(f); } /** * Returns an iterator over all clashes in the branch. * * @return the iterator */ public Iterator<Pair<LabelledFormula<P>>> clashes() { IteratorChain<Pair<LabelledFormula<P>>> ites = new IteratorChain<Pair<LabelledFormula<P>>>(); for(World<P> w : tableau.getWorlds()) { if(w.isClashing()) ites.addIterator(w.clashes()); } return ites; } /** * Add subformula to the unexpanded ones. * * @param lf the subformula */ public void unexpand(LabelledFormula<P> lf) { unexpanded.add(lf); } /** * Return the last unexpanded formula. * * @return the last unexpanded formula */ public LabelledFormula<P> unexpanded() { if(unexpanded.isEmpty()) { return null; } return unexpanded.remove(unexpanded.size()-1); } /** * Remove subformula from current branch and world. * * @param lf the subformula */ public void remove(LabelledFormula<P> lf) { unexpanded.remove(lf); if(lf.getFormula() instanceof Literal) lf.getWorld().removeLiteral(lf); } /** * Remove all subformulas of given collection. * * @param lfs the subformulas */ public void removeAll(Collection<LabelledFormula<P>> lfs) { for (LabelledFormula<P> lf : lfs) { remove(lf); } } /** * Return number of unexpanded subformulas. * * @return the number of unexpanded subformulas */ public int unexpandedSize() { return unexpanded.size(); } }
LibModalLogic/src/modalLogic/tableau/Branch.java
/* Copyright (c) 2010, Johannes Köster <[email protected]> * All rights reserved. * * This software is open-source under the BSD license; see "license.txt" * for a description. */ package modalLogic.tableau; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.List; import modalLogic.formula.Formula; import org.apache.commons.collections15.iterators.IteratorChain; import util.Pair; /** * The currently investigated branch of the tableau. * * @author Johannes Köster <[email protected]> */ public class Branch<P> { private Tableau<P> tableau; private Comparator<P> propositionComparator; private List<LabelledFormula<P>> unexpanded; /** * Constructor of class Branch. * * @param tableau the tableau * @param propositionComparator a comparator for propositions */ public Branch(Tableau<P> tableau, Comparator<P> propositionComparator) { this.tableau = tableau; this.propositionComparator = propositionComparator; unexpanded = new ArrayList<LabelledFormula<P>>(); } /** * Returns a list of unexpanded subformulas. * * @return a list of unexpanded subformulas */ public List<LabelledFormula<P>> getUnexpanded() { return unexpanded; } /** * Clears the list of unexpanded subformulas. */ public void clear() { unexpanded.clear(); } /** * Add a subformula to the branch. * * @param f the subformula */ public void add(LabelledFormula<P> f) { if (f.getFormula().getType() == Formula.LITERAL) { f.getWorld().addLiteral(f); } unexpanded.add(f); } /** * Returns an iterator over all clashes in the branch. * * @return the iterator */ public Iterator<Pair<LabelledFormula<P>>> clashes() { IteratorChain<Pair<LabelledFormula<P>>> ites = new IteratorChain<Pair<LabelledFormula<P>>>(); for(World<P> w : tableau.getWorlds()) { if(w.isClashing()) ites.addIterator(w.clashes()); } return ites; } /** * Add subformula to the unexpanded ones. * * @param lf the subformula */ public void unexpand(LabelledFormula<P> lf) { unexpanded.add(lf); } /** * Return the last unexpanded formula. * * @return the last unexpanded formula */ public LabelledFormula<P> unexpanded() { if(unexpanded.isEmpty()) { return null; } return unexpanded.remove(unexpanded.size()-1); } /** * Remove subformula from current branch and world. * * @param lf the subformula */ public void remove(LabelledFormula<P> lf) { unexpanded.remove(lf); lf.getWorld().removeLiteral(lf); } /** * Remove all subformulas of given collection. * * @param lfs the subformulas */ public void removeAll(Collection<LabelledFormula<P>> lfs) { for (LabelledFormula<P> lf : lfs) { remove(lf); } } /** * Return number of unexpanded subformulas. * * @return the number of unexpanded subformulas */ public int unexpandedSize() { return unexpanded.size(); } }
Minor fix for backtracking non-literal disjuncts
LibModalLogic/src/modalLogic/tableau/Branch.java
Minor fix for backtracking non-literal disjuncts
<ide><path>ibModalLogic/src/modalLogic/tableau/Branch.java <ide> import java.util.Iterator; <ide> import java.util.List; <ide> import modalLogic.formula.Formula; <add>import modalLogic.formula.Literal; <ide> import org.apache.commons.collections15.iterators.IteratorChain; <ide> import util.Pair; <ide> <ide> */ <ide> public void remove(LabelledFormula<P> lf) { <ide> unexpanded.remove(lf); <del> lf.getWorld().removeLiteral(lf); <add> if(lf.getFormula() instanceof Literal) <add> lf.getWorld().removeLiteral(lf); <ide> } <ide> <ide> /**
Java
apache-2.0
b2f7e7e39b7b98d60afbbfb5707f68c6249b8521
0
apache/jackrabbit,apache/jackrabbit,apache/jackrabbit
/* * 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.jackrabbit.jcr2spi.hierarchy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.jackrabbit.jcr2spi.observation.InternalEventListener; import org.apache.jackrabbit.jcr2spi.WorkspaceManager; import org.apache.jackrabbit.jcr2spi.config.CacheBehaviour; import org.apache.jackrabbit.spi.EventFilter; import org.apache.jackrabbit.spi.Event; import org.apache.jackrabbit.spi.EventBundle; import org.apache.jackrabbit.spi.EventIterator; import org.apache.jackrabbit.spi.NodeId; import org.apache.jackrabbit.name.Path; import javax.jcr.RepositoryException; import java.util.Collection; import java.util.Collections; import java.util.Set; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ArrayList; /** * <code>HierarchyEventListener</code>... */ public class HierarchyEventListener implements InternalEventListener { private static Logger log = LoggerFactory.getLogger(HierarchyEventListener.class); private final HierarchyManager hierarchyMgr; private final Collection eventFilter; public HierarchyEventListener(WorkspaceManager wspManager, HierarchyManager hierarchyMgr, CacheBehaviour cacheBehaviour) { this.hierarchyMgr = hierarchyMgr; if (cacheBehaviour == CacheBehaviour.OBSERVATION) { EventFilter filter = null; try { // TODO: improve. for now listen to everything filter = wspManager.createEventFilter(Event.ALL_TYPES, Path.ROOT, true, null, null, false); } catch (RepositoryException e) { // spi does not support observation, or another error occurred. } this.eventFilter = (filter == null) ? Collections.EMPTY_LIST : Collections.singletonList(filter); wspManager.addEventListener(this); } else { this.eventFilter = Collections.EMPTY_LIST; } } //----------------------------------------------< InternalEventListener >--- /** * @see InternalEventListener#getEventFilters() */ public Collection getEventFilters() { return eventFilter; } /** * Processes <code>events</code> and invalidates cached <code>ItemState</code>s * accordingly. Note that this performed for both local and non-local changes, * since workspace operations are reported as local changes as well and * might have invoked changes (autocreated items etc.). * * @param eventBundle * @see InternalEventListener#onEvent(EventBundle) */ public void onEvent(EventBundle eventBundle) { pushEvents(getEventCollection(eventBundle)); } /** * Retrieve the workspace state(s) affected by the given event and refresh * them accordingly. * * @param events */ private void pushEvents(Collection events) { if (events.isEmpty()) { return; } // collect set of removed node ids Set removedEvents = new HashSet(); // separately collect the add events Set addEvents = new HashSet(); for (Iterator it = events.iterator(); it.hasNext();) { Event event = (Event) it.next(); int type = event.getType(); if (type == Event.NODE_REMOVED) { // remember removed nodes separately for proper handling later on. removedEvents.add(event.getItemId()); } else if (type == Event.NODE_ADDED || type == Event.PROPERTY_ADDED) { addEvents.add(event); it.remove(); } } /* Process ADD-events. In case of persisting transients modifications, the event-set may still contain events that are not covered by the changeLog such as new version-history or other autocreated properties and nodes. Add events need to be processed hierarchically, since its not possible to add a new child reference to a state that is not yet present in the state manager. The 'progress' flag is used to make sure, that during each loop at least one event has been processed and removed from the iterator. If this is not the case, there are not parent states present in the state manager that need to be updated and the remaining events may be ignored. */ boolean progress = true; while (!addEvents.isEmpty() && progress) { progress = false; for (Iterator it = addEvents.iterator(); it.hasNext();) { Event ev = (Event) it.next(); NodeEntry parent = (ev.getParentId() != null) ? (NodeEntry) hierarchyMgr.lookup(ev.getParentId()) : null; if (parent != null) { parent.refresh(ev); it.remove(); progress = true; } } } /* process all other events (removal, property changed) */ for (Iterator it = events.iterator(); it.hasNext(); ) { Event event = (Event) it.next(); int type = event.getType(); NodeId parentId = event.getParentId(); NodeEntry parent = (parentId != null) ? (NodeEntry) hierarchyMgr.lookup(parentId) : null; if (type == Event.NODE_REMOVED || type == Event.PROPERTY_REMOVED) { // notify parent about removal if its child-entry. // - if parent is 'null' (i.e. not yet loaded) the child-entry does // not exist either -> no need to inform child-entry // - if parent got removed with the same event-bundle // only remove the parent an skip this event. if (parent != null && !removedEvents.contains(parentId)) { parent.refresh(event); } } else if (type == Event.PROPERTY_CHANGED) { // notify parent in case jcr:mixintypes or jcr:uuid was changed. // if parent is 'null' (i.e. not yet loaded) the prop-entry does // not exist either -> no need to inform propEntry if (parent != null) { parent.refresh(event); } } else { // should never occur throw new IllegalArgumentException("Invalid event type: " + event.getType()); } } } private static Collection getEventCollection(EventBundle eventBundle) { List evs = new ArrayList(); for (EventIterator it = eventBundle.getEvents(); it.hasNext();) { evs.add(it.nextEvent()); } return evs; } }
contrib/spi/jcr2spi/src/main/java/org/apache/jackrabbit/jcr2spi/hierarchy/HierarchyEventListener.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.jackrabbit.jcr2spi.hierarchy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.jackrabbit.jcr2spi.observation.InternalEventListener; import org.apache.jackrabbit.jcr2spi.WorkspaceManager; import org.apache.jackrabbit.jcr2spi.config.CacheBehaviour; import org.apache.jackrabbit.spi.EventFilter; import org.apache.jackrabbit.spi.Event; import org.apache.jackrabbit.spi.EventBundle; import org.apache.jackrabbit.spi.EventIterator; import org.apache.jackrabbit.spi.NodeId; import org.apache.jackrabbit.name.Path; import javax.jcr.RepositoryException; import java.util.Collection; import java.util.Collections; import java.util.Set; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ArrayList; /** * <code>HierarchyEventListener</code>... */ public class HierarchyEventListener implements InternalEventListener { private static Logger log = LoggerFactory.getLogger(HierarchyEventListener.class); private final HierarchyManager hierarchyMgr; private final Collection eventFilter; public HierarchyEventListener(WorkspaceManager wspManager, HierarchyManager hierarchyMgr, CacheBehaviour cacheBehaviour) { this.hierarchyMgr = hierarchyMgr; if (cacheBehaviour == CacheBehaviour.OBSERVATION) { EventFilter filter = null; try { // TODO: improve. for now listen to everything filter = wspManager.createEventFilter(Event.ALL_TYPES, Path.ROOT, true, null, null, false); } catch (RepositoryException e) { // spi does not support observation, or another error occurred. } this.eventFilter = (filter == null) ? Collections.EMPTY_LIST : Collections.singletonList(filter); } else { this.eventFilter = Collections.EMPTY_LIST; } wspManager.addEventListener(this); } //----------------------------------------------< InternalEventListener >--- /** * @see InternalEventListener#getEventFilters() */ public Collection getEventFilters() { return eventFilter; } /** * Processes <code>events</code> and invalidates cached <code>ItemState</code>s * accordingly. Note that this performed for both local and non-local changes, * since workspace operations are reported as local changes as well and * might have invoked changes (autocreated items etc.). * * @param eventBundle * @see InternalEventListener#onEvent(EventBundle) */ public void onEvent(EventBundle eventBundle) { pushEvents(getEventCollection(eventBundle)); } /** * Retrieve the workspace state(s) affected by the given event and refresh * them accordingly. * * @param events */ private void pushEvents(Collection events) { if (events.isEmpty()) { return; } // collect set of removed node ids Set removedEvents = new HashSet(); // separately collect the add events Set addEvents = new HashSet(); for (Iterator it = events.iterator(); it.hasNext();) { Event event = (Event) it.next(); int type = event.getType(); if (type == Event.NODE_REMOVED) { // remember removed nodes separately for proper handling later on. removedEvents.add(event.getItemId()); } else if (type == Event.NODE_ADDED || type == Event.PROPERTY_ADDED) { addEvents.add(event); it.remove(); } } /* Process ADD-events. In case of persisting transients modifications, the event-set may still contain events that are not covered by the changeLog such as new version-history or other autocreated properties and nodes. Add events need to be processed hierarchically, since its not possible to add a new child reference to a state that is not yet present in the state manager. The 'progress' flag is used to make sure, that during each loop at least one event has been processed and removed from the iterator. If this is not the case, there are not parent states present in the state manager that need to be updated and the remaining events may be ignored. */ boolean progress = true; while (!addEvents.isEmpty() && progress) { progress = false; for (Iterator it = addEvents.iterator(); it.hasNext();) { Event ev = (Event) it.next(); NodeEntry parent = (ev.getParentId() != null) ? (NodeEntry) hierarchyMgr.lookup(ev.getParentId()) : null; if (parent != null) { parent.refresh(ev); it.remove(); progress = true; } } } /* process all other events (removal, property changed) */ for (Iterator it = events.iterator(); it.hasNext(); ) { Event event = (Event) it.next(); int type = event.getType(); NodeId parentId = event.getParentId(); NodeEntry parent = (parentId != null) ? (NodeEntry) hierarchyMgr.lookup(parentId) : null; if (type == Event.NODE_REMOVED || type == Event.PROPERTY_REMOVED) { // notify parent about removal if its child-entry. // - if parent is 'null' (i.e. not yet loaded) the child-entry does // not exist either -> no need to inform child-entry // - if parent got removed with the same event-bundle // only remove the parent an skip this event. if (parent != null && !removedEvents.contains(parentId)) { parent.refresh(event); } } else if (type == Event.PROPERTY_CHANGED) { // notify parent in case jcr:mixintypes or jcr:uuid was changed. // if parent is 'null' (i.e. not yet loaded) the prop-entry does // not exist either -> no need to inform propEntry if (parent != null) { parent.refresh(event); } } else { // should never occur throw new IllegalArgumentException("Invalid event type: " + event.getType()); } } } private static Collection getEventCollection(EventBundle eventBundle) { List evs = new ArrayList(); for (EventIterator it = eventBundle.getEvents(); it.hasNext();) { evs.add(it.nextEvent()); } return evs; } }
- Only register event listener if observation is needed. git-svn-id: 02b679d096242155780e1604e997947d154ee04a@512978 13f79535-47bb-0310-9956-ffa450edef68
contrib/spi/jcr2spi/src/main/java/org/apache/jackrabbit/jcr2spi/hierarchy/HierarchyEventListener.java
- Only register event listener if observation is needed.
<ide><path>ontrib/spi/jcr2spi/src/main/java/org/apache/jackrabbit/jcr2spi/hierarchy/HierarchyEventListener.java <ide> // spi does not support observation, or another error occurred. <ide> } <ide> this.eventFilter = (filter == null) ? Collections.EMPTY_LIST : Collections.singletonList(filter); <add> wspManager.addEventListener(this); <ide> } else { <ide> this.eventFilter = Collections.EMPTY_LIST; <ide> } <del> wspManager.addEventListener(this); <ide> } <ide> <ide> //----------------------------------------------< InternalEventListener >---
Java
apache-2.0
fb0f50de6bdc0541a429ee5604a5f3a347a71fc1
0
yanchenko/droidparts,droidparts/droidparts
/** * Copyright 2015 Alex Yanchenko * * 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.droidparts.net.http; import static android.content.Context.MODE_PRIVATE; import static java.util.Collections.singletonList; import static java.util.Collections.singletonMap; import static java.util.Collections.unmodifiableList; import static org.droidparts.util.Strings.join; import java.io.IOException; import java.net.CookieHandler; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.http.client.CookieStore; import org.apache.http.cookie.Cookie; import org.apache.http.cookie.CookieOrigin; import org.apache.http.cookie.CookieSpec; import org.apache.http.cookie.MalformedCookieException; import org.apache.http.cookie.SM; import org.apache.http.impl.cookie.BasicClientCookie; import org.apache.http.impl.cookie.BrowserCompatSpec; import org.apache.http.message.BasicHeader; import org.droidparts.util.L; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; public class CookieJar extends CookieHandler implements CookieStore { private final CookieSpec cookieSpec; private final SharedPreferences prefs; private boolean persistCookies; public CookieJar(Context ctx) { cookieSpec = new BrowserCompatSpec(); prefs = ctx.getSharedPreferences("droidparts_restclient_cookies", MODE_PRIVATE); } public void setPersistent(boolean persistent) { persistCookies = persistent; if (persistCookies) { cookies.clear(); restoreCookies(); } } // HttpURLConnection @Override public Map<String, List<String>> get(URI uri, Map<String, List<String>> requestHeaders) throws IOException { clearExpired(new Date()); ArrayList<String> cookies = new ArrayList<String>(); for (Cookie cookie : getCookies(uri)) { cookies.add(cookie.getName() + "=" + cookie.getValue()); } return singletonMap(SM.COOKIE, singletonList(join(cookies, SEP))); } @Override public void put(URI uri, Map<String, List<String>> responseHeaders) throws IOException { for (String key : responseHeaders.keySet()) { if (SM.SET_COOKIE.equalsIgnoreCase(key) || SM.SET_COOKIE2.equalsIgnoreCase(key)) { List<Cookie> cookies = parseCookies(uri, responseHeaders.get(key)); for (Cookie c : cookies) { addCookie(c); } return; } } } // HttpClient @Override public void addCookie(Cookie cookie) { L.d("Got a cookie: %s.", cookie); synchronized (cookies) { for (Iterator<Cookie> it = cookies.iterator(); it.hasNext();) { Cookie c = it.next(); if (isEqual(cookie, c)) { it.remove(); } } } if (!cookie.isExpired(new Date())) { cookies.add(cookie); } if (persistCookies) { persistCookies(); } } @Override public void clear() { cookies.clear(); if (persistCookies) { persistCookies(); } } @Override public boolean clearExpired(Date date) { boolean purged = false; synchronized (cookies) { for (Iterator<Cookie> it = cookies.iterator(); it.hasNext();) { Cookie cookie = it.next(); if (cookie.isExpired(date)) { it.remove(); purged = true; } } } if (persistCookies && purged) { persistCookies(); } return purged; } @Override public List<Cookie> getCookies() { L.d("Cookie count: %d.", cookies.size()); return unmodifiableList(cookies); } // Custom private final List<Cookie> cookies = Collections.synchronizedList(new ArrayList<Cookie>()); private List<Cookie> parseCookies(URI uri, List<String> cookieHeaders) { ArrayList<Cookie> cookies = new ArrayList<Cookie>(); int port = (uri.getPort() < 0) ? 80 : uri.getPort(); boolean secure = "https".equals(uri.getScheme()); CookieOrigin origin = new CookieOrigin(uri.getHost(), port, uri.getPath(), secure); for (String cookieHeader : cookieHeaders) { BasicHeader header = new BasicHeader(SM.SET_COOKIE, cookieHeader); try { cookies.addAll(cookieSpec.parse(header, origin)); } catch (MalformedCookieException e) { L.d(e); } } return cookies; } private Collection<Cookie> getCookies(URI uri) { HashMap<String, Cookie> map = new HashMap<String, Cookie>(); for (Cookie cookie : getCookies()) { boolean suitable = uri.getHost().equals(cookie.getDomain()) && uri.getPath().startsWith(cookie.getPath()); if (suitable) { boolean put = true; if (map.containsKey(cookie.getName())) { Cookie otherCookie = map.get(cookie.getName()); boolean betterMatchingPath = cookie.getPath().length() > otherCookie.getPath().length(); put = betterMatchingPath; } if (put) { map.put(cookie.getName(), cookie); } } } return map.values(); } private void persistCookies() { Editor editor = prefs.edit(); editor.clear(); for (int i = 0; i < cookies.size(); i++) { editor.putString(String.valueOf(i), toString(cookies.get(i))); } editor.commit(); } private void restoreCookies() { for (int i = 0; i < Integer.MAX_VALUE; i++) { String str = prefs.getString(String.valueOf(i), null); if (str == null) { return; } else { cookies.add(fromString(str)); } } } private static String toString(Cookie cookie) { StringBuilder sb = new StringBuilder(); sb.append(cookie.getName()); sb.append(SEP); sb.append(cookie.getValue()); sb.append(SEP); sb.append(cookie.getDomain()); sb.append(SEP); sb.append(cookie.getPath()); Date expiryDate = cookie.getExpiryDate(); if (expiryDate != null) { sb.append(SEP); sb.append(expiryDate.getTime()); } return sb.toString(); } private static Cookie fromString(String str) { String[] parts = str.split(SEP); BasicClientCookie cookie = new BasicClientCookie(parts[0], parts[1]); cookie.setDomain(parts[2]); cookie.setPath(parts[3]); if (parts.length == 5) { cookie.setExpiryDate(new Date(Long.valueOf(parts[4]))); } return cookie; } private static final String SEP = ";"; private static boolean isEqual(Cookie first, Cookie second) { boolean equal = first.getName().equals(second.getName()) && first.getDomain().equals(second.getDomain()) && first.getPath().equals(second.getPath()); return equal; } }
droidparts/src/org/droidparts/net/http/CookieJar.java
/** * Copyright 2015 Alex Yanchenko * * 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.droidparts.net.http; import static android.content.Context.MODE_PRIVATE; import static java.util.Collections.singletonList; import static java.util.Collections.singletonMap; import static java.util.Collections.unmodifiableList; import static org.droidparts.util.Strings.join; import java.io.IOException; import java.net.CookieHandler; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import org.apache.http.client.CookieStore; import org.apache.http.cookie.Cookie; import org.apache.http.cookie.CookieOrigin; import org.apache.http.cookie.CookieSpec; import org.apache.http.cookie.MalformedCookieException; import org.apache.http.cookie.SM; import org.apache.http.impl.cookie.BasicClientCookie; import org.apache.http.impl.cookie.BrowserCompatSpec; import org.apache.http.message.BasicHeader; import org.droidparts.util.L; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; public class CookieJar extends CookieHandler implements CookieStore { private final CookieSpec cookieSpec; private final SharedPreferences prefs; private boolean persistCookies; public CookieJar(Context ctx) { cookieSpec = new BrowserCompatSpec(); prefs = ctx.getSharedPreferences("droidparts_restclient_cookies", MODE_PRIVATE); } public void setPersistent(boolean persistent) { persistCookies = persistent; if (persistCookies) { cookies.clear(); restoreCookies(); } } // HttpURLConnection @Override public Map<String, List<String>> get(URI uri, Map<String, List<String>> requestHeaders) throws IOException { clearExpired(new Date()); ArrayList<String> cookies = new ArrayList<String>(); for (Cookie cookie : getCookies(uri)) { cookies.add(cookie.getName() + "=" + cookie.getValue()); } return singletonMap(SM.COOKIE, singletonList(join(cookies, SEP))); } @Override public void put(URI uri, Map<String, List<String>> responseHeaders) throws IOException { for (String key : responseHeaders.keySet()) { if (SM.SET_COOKIE.equalsIgnoreCase(key) || SM.SET_COOKIE2.equalsIgnoreCase(key)) { List<Cookie> cookies = parseCookies(uri, responseHeaders.get(key)); for (Cookie c : cookies) { addCookie(c); } return; } } } // HttpClient @Override public void addCookie(Cookie cookie) { L.d("Got a cookie: %s.", cookie); for (Iterator<Cookie> it = cookies.iterator(); it.hasNext();) { Cookie c = it.next(); if (isEqual(cookie, c)) { it.remove(); } } if (!cookie.isExpired(new Date())) { cookies.add(cookie); } if (persistCookies) { persistCookies(); } } @Override public void clear() { cookies.clear(); if (persistCookies) { persistCookies(); } } @Override public boolean clearExpired(Date date) { boolean purged = false; for (Iterator<Cookie> it = cookies.iterator(); it.hasNext();) { Cookie cookie = it.next(); if (cookie.isExpired(date)) { it.remove(); purged = true; } } if (persistCookies && purged) { persistCookies(); } return purged; } @Override public List<Cookie> getCookies() { L.d("Cookie count: %d.", cookies.size()); return unmodifiableList(cookies); } // Custom private final CopyOnWriteArrayList<Cookie> cookies = new CopyOnWriteArrayList<Cookie>(); private List<Cookie> parseCookies(URI uri, List<String> cookieHeaders) { ArrayList<Cookie> cookies = new ArrayList<Cookie>(); int port = (uri.getPort() < 0) ? 80 : uri.getPort(); boolean secure = "https".equals(uri.getScheme()); CookieOrigin origin = new CookieOrigin(uri.getHost(), port, uri.getPath(), secure); for (String cookieHeader : cookieHeaders) { BasicHeader header = new BasicHeader(SM.SET_COOKIE, cookieHeader); try { cookies.addAll(cookieSpec.parse(header, origin)); } catch (MalformedCookieException e) { L.d(e); } } return cookies; } private Collection<Cookie> getCookies(URI uri) { HashMap<String, Cookie> map = new HashMap<String, Cookie>(); for (Cookie cookie : getCookies()) { boolean suitable = uri.getHost().equals(cookie.getDomain()) && uri.getPath().startsWith(cookie.getPath()); if (suitable) { boolean put = true; if (map.containsKey(cookie.getName())) { Cookie otherCookie = map.get(cookie.getName()); boolean betterMatchingPath = cookie.getPath().length() > otherCookie.getPath().length(); put = betterMatchingPath; } if (put) { map.put(cookie.getName(), cookie); } } } return map.values(); } private void persistCookies() { Editor editor = prefs.edit(); editor.clear(); for (int i = 0; i < cookies.size(); i++) { editor.putString(String.valueOf(i), toString(cookies.get(i))); } editor.commit(); } private void restoreCookies() { for (int i = 0; i < Integer.MAX_VALUE; i++) { String str = prefs.getString(String.valueOf(i), null); if (str == null) { return; } else { cookies.add(fromString(str)); } } } private static String toString(Cookie cookie) { StringBuilder sb = new StringBuilder(); sb.append(cookie.getName()); sb.append(SEP); sb.append(cookie.getValue()); sb.append(SEP); sb.append(cookie.getDomain()); sb.append(SEP); sb.append(cookie.getPath()); Date expiryDate = cookie.getExpiryDate(); if (expiryDate != null) { sb.append(SEP); sb.append(expiryDate.getTime()); } return sb.toString(); } private static Cookie fromString(String str) { String[] parts = str.split(SEP); BasicClientCookie cookie = new BasicClientCookie(parts[0], parts[1]); cookie.setDomain(parts[2]); cookie.setPath(parts[3]); if (parts.length == 5) { cookie.setExpiryDate(new Date(Long.valueOf(parts[4]))); } return cookie; } private static final String SEP = ";"; private static boolean isEqual(Cookie first, Cookie second) { boolean equal = first.getName().equals(second.getName()) && first.getDomain().equals(second.getDomain()) && first.getPath().equals(second.getPath()); return equal; } }
CookieJar: fixed UnsupportedOperationException.
droidparts/src/org/droidparts/net/http/CookieJar.java
CookieJar: fixed UnsupportedOperationException.
<ide><path>roidparts/src/org/droidparts/net/http/CookieJar.java <ide> import java.net.URI; <ide> import java.util.ArrayList; <ide> import java.util.Collection; <add>import java.util.Collections; <ide> import java.util.Date; <ide> import java.util.HashMap; <ide> import java.util.Iterator; <ide> import java.util.List; <ide> import java.util.Map; <del>import java.util.concurrent.CopyOnWriteArrayList; <ide> <ide> import org.apache.http.client.CookieStore; <ide> import org.apache.http.cookie.Cookie; <ide> @Override <ide> public void addCookie(Cookie cookie) { <ide> L.d("Got a cookie: %s.", cookie); <del> for (Iterator<Cookie> it = cookies.iterator(); it.hasNext();) { <del> Cookie c = it.next(); <del> if (isEqual(cookie, c)) { <del> it.remove(); <add> synchronized (cookies) { <add> for (Iterator<Cookie> it = cookies.iterator(); it.hasNext();) { <add> Cookie c = it.next(); <add> if (isEqual(cookie, c)) { <add> it.remove(); <add> } <ide> } <ide> } <ide> if (!cookie.isExpired(new Date())) { <ide> @Override <ide> public boolean clearExpired(Date date) { <ide> boolean purged = false; <del> for (Iterator<Cookie> it = cookies.iterator(); it.hasNext();) { <del> Cookie cookie = it.next(); <del> if (cookie.isExpired(date)) { <del> it.remove(); <del> purged = true; <add> synchronized (cookies) { <add> for (Iterator<Cookie> it = cookies.iterator(); it.hasNext();) { <add> Cookie cookie = it.next(); <add> if (cookie.isExpired(date)) { <add> it.remove(); <add> purged = true; <add> } <ide> } <ide> } <ide> if (persistCookies && purged) { <ide> <ide> // Custom <ide> <del> private final CopyOnWriteArrayList<Cookie> cookies = new CopyOnWriteArrayList<Cookie>(); <add> private final List<Cookie> cookies = Collections.synchronizedList(new ArrayList<Cookie>()); <ide> <ide> private List<Cookie> parseCookies(URI uri, List<String> cookieHeaders) { <ide> ArrayList<Cookie> cookies = new ArrayList<Cookie>();
Java
mit
487ac38262afc137ba6c395a86766f41c2b55e69
0
selig/qea
package monitoring.impl; import java.util.IdentityHashMap; import structure.impl.SimplestQEA; import structure.impl.Verdict; import structure.intf.QEA; /** * A small-step monitor for the Simplest QEA * * @author Giles Reger * @author Helena Cuenca */ public class SimplestSmallStepQEAMonitor extends SmallStepMonitor { private IdentityHashMap<Object, Integer> bindings; private QEA qea; private SimplestQEA simplestQEA; private int bindingsInNonFinalStateCount; private int bindingsInFinalStateCount; /** * Creates a SimplestSmallStepQEAMonitor for the specified QEA * * @param qea * QEA */ SimplestSmallStepQEAMonitor(QEA qea) { this.qea = qea; bindings = new IdentityHashMap<>(); bindingsInNonFinalStateCount = 0; bindingsInFinalStateCount = 0; simplestQEA = (SimplestQEA) qea; // TODO Change this! } @Override public Verdict step(int eventName, Object[] args) { // TODO Auto-generated method stub return null; } @Override public Verdict step(int eventName, Object param1) { boolean existingBinding = false; int startState; // Determine if the value received corresponds to an existing binding if (bindings.containsKey(param1)) { // Existing binding // Get current state for the binding startState = bindings.get(param1); // Assign flag for counters update existingBinding = true; } else { // New binding startState = 1; } // Compute next state int endState = simplestQEA.getNextState(startState, eventName); // Update/add state for the binding bindings.put(param1, endState); // If applicable, update counters if (existingBinding) { if (qea.isStateFinal(startState) && !qea.isStateFinal(endState)) { bindingsInNonFinalStateCount++; bindingsInFinalStateCount--; } else if (!qea.isStateFinal(startState) && qea.isStateFinal(endState)) { bindingsInNonFinalStateCount--; bindingsInFinalStateCount++; } } else { if (qea.isStateFinal(endState)) { bindingsInFinalStateCount++; } else { bindingsInNonFinalStateCount++; } } // According to the quantification of the variable, return verdict if (simplestQEA.isQuantificationUniversal() && allBindingsInFinalState() || !simplestQEA.isQuantificationUniversal() && existsOneBindingInFinalState()) { return Verdict.WEAK_SUCCESS; } return Verdict.WEAK_FAILURE; } @Override public Verdict end() { // According to the quantification of the variable, return verdict if (simplestQEA.isQuantificationUniversal() && allBindingsInFinalState() || !simplestQEA.isQuantificationUniversal() && existsOneBindingInFinalState()) { return Verdict.SUCCESS; } return Verdict.FAILURE; } // public Verdict step(Event event) { // // TODO Auto-generated method stub // return null; // } /** * Determines if all bindings for the current monitor are in a final state * * @return <code>true</code> if all bindings for the current monitor are in * a final state; <code>false</code> otherwise */ private boolean allBindingsInFinalState() { if (bindingsInNonFinalStateCount == 0) { return true; } return false; } /** * Determines if there is at least one binding in a final state for the * current monitor * * @return <code>true</code> if at least one binding is in final state; * <code>false</code> otherwise */ private boolean existsOneBindingInFinalState() { if (bindingsInFinalStateCount > 0) { return true; } return false; } }
code/qea/src/monitoring/impl/SimplestSmallStepQEAMonitor.java
package monitoring.impl; import java.util.IdentityHashMap; import structure.impl.SimplestQEA; import structure.impl.Verdict; import structure.intf.QEA; /** * A small-step monitor for the Simplest QEA * * @author Giles Reger * @author Helena Cuenca */ public class SimplestSmallStepQEAMonitor extends SmallStepMonitor { private IdentityHashMap<Object, Integer> bindings; private QEA qea; private SimplestQEA simplestQEA; private int bindingsInNonFinalStateCount; SimplestSmallStepQEAMonitor(QEA qea) { bindings = new IdentityHashMap<>(); this.qea = qea; simplestQEA = (SimplestQEA) qea; // TODO Change this! bindingsInNonFinalStateCount = 0; } @Override public Verdict step(int eventName, Object[] args) { // TODO Auto-generated method stub return null; } @Override public Verdict step(int eventName, Object param1) { boolean existingBindingInNonFinalState = false; int startState; // Determine if the value received corresponds to an existing binding if (bindings.containsKey(param1)) { // Existing binding startState = bindings.get(param1); if (!simplestQEA.isStateFinal(startState)) { existingBindingInNonFinalState = true; } } else { // New binding startState = 1; } // Compute next state int endState = simplestQEA.getNextState(startState, eventName); // Update/add state for the binding bindings.put(param1, endState); // If applicable, update count of non-final state bindings if (existingBindingInNonFinalState && simplestQEA.isStateFinal(endState)) { bindingsInNonFinalStateCount--; } else if (!existingBindingInNonFinalState && !simplestQEA.isStateFinal(endState)) { bindingsInNonFinalStateCount++; } if (allBindingsInFinalState()) { return Verdict.WEAK_SUCCESS; } return Verdict.WEAK_FAILURE; } @Override public Verdict end() { if (allBindingsInFinalState()) { return Verdict.SUCCESS; } return Verdict.FAILURE; } // public Verdict step(Event event) { // // TODO Auto-generated method stub // return null; // } /** * Determines if all bindings for the current monitor are in a final state * * @return true if all bindings for the current monitor are in a final * state. Otherwise, false */ private boolean allBindingsInFinalState() { if (bindingsInNonFinalStateCount == 0) { return true; } return false; } }
Functionality for one variable with existential quantification added
code/qea/src/monitoring/impl/SimplestSmallStepQEAMonitor.java
Functionality for one variable with existential quantification added
<ide><path>ode/qea/src/monitoring/impl/SimplestSmallStepQEAMonitor.java <ide> * @author Giles Reger <ide> * @author Helena Cuenca <ide> */ <del> <ide> public class SimplestSmallStepQEAMonitor extends SmallStepMonitor { <ide> <ide> private IdentityHashMap<Object, Integer> bindings; <ide> <ide> private int bindingsInNonFinalStateCount; <ide> <add> private int bindingsInFinalStateCount; <add> <add> /** <add> * Creates a SimplestSmallStepQEAMonitor for the specified QEA <add> * <add> * @param qea <add> * QEA <add> */ <ide> SimplestSmallStepQEAMonitor(QEA qea) { <add> this.qea = qea; <ide> bindings = new IdentityHashMap<>(); <del> this.qea = qea; <add> bindingsInNonFinalStateCount = 0; <add> bindingsInFinalStateCount = 0; <ide> simplestQEA = (SimplestQEA) qea; // TODO Change this! <del> bindingsInNonFinalStateCount = 0; <ide> } <ide> <ide> @Override <ide> @Override <ide> public Verdict step(int eventName, Object param1) { <ide> <del> boolean existingBindingInNonFinalState = false; <add> boolean existingBinding = false; <ide> int startState; <ide> <ide> // Determine if the value received corresponds to an existing binding <ide> if (bindings.containsKey(param1)) { // Existing binding <ide> <add> // Get current state for the binding <ide> startState = bindings.get(param1); <del> if (!simplestQEA.isStateFinal(startState)) { <del> existingBindingInNonFinalState = true; <del> } <add> <add> // Assign flag for counters update <add> existingBinding = true; <add> <ide> } else { // New binding <ide> startState = 1; <ide> } <ide> // Update/add state for the binding <ide> bindings.put(param1, endState); <ide> <del> // If applicable, update count of non-final state bindings <del> if (existingBindingInNonFinalState <del> && simplestQEA.isStateFinal(endState)) { <del> bindingsInNonFinalStateCount--; <del> } else if (!existingBindingInNonFinalState <del> && !simplestQEA.isStateFinal(endState)) { <del> bindingsInNonFinalStateCount++; <add> // If applicable, update counters <add> if (existingBinding) { <add> if (qea.isStateFinal(startState) && !qea.isStateFinal(endState)) { <add> bindingsInNonFinalStateCount++; <add> bindingsInFinalStateCount--; <add> } else if (!qea.isStateFinal(startState) <add> && qea.isStateFinal(endState)) { <add> bindingsInNonFinalStateCount--; <add> bindingsInFinalStateCount++; <add> } <add> } else { <add> if (qea.isStateFinal(endState)) { <add> bindingsInFinalStateCount++; <add> } else { <add> bindingsInNonFinalStateCount++; <add> } <ide> } <ide> <del> if (allBindingsInFinalState()) { <add> // According to the quantification of the variable, return verdict <add> if (simplestQEA.isQuantificationUniversal() <add> && allBindingsInFinalState() <add> || !simplestQEA.isQuantificationUniversal() <add> && existsOneBindingInFinalState()) { <ide> return Verdict.WEAK_SUCCESS; <ide> } <ide> return Verdict.WEAK_FAILURE; <ide> <ide> @Override <ide> public Verdict end() { <del> if (allBindingsInFinalState()) { <add> <add> // According to the quantification of the variable, return verdict <add> if (simplestQEA.isQuantificationUniversal() <add> && allBindingsInFinalState() <add> || !simplestQEA.isQuantificationUniversal() <add> && existsOneBindingInFinalState()) { <ide> return Verdict.SUCCESS; <ide> } <ide> return Verdict.FAILURE; <ide> /** <ide> * Determines if all bindings for the current monitor are in a final state <ide> * <del> * @return true if all bindings for the current monitor are in a final <del> * state. Otherwise, false <add> * @return <code>true</code> if all bindings for the current monitor are in <add> * a final state; <code>false</code> otherwise <ide> */ <ide> private boolean allBindingsInFinalState() { <ide> if (bindingsInNonFinalStateCount == 0) { <ide> } <ide> return false; <ide> } <add> <add> /** <add> * Determines if there is at least one binding in a final state for the <add> * current monitor <add> * <add> * @return <code>true</code> if at least one binding is in final state; <add> * <code>false</code> otherwise <add> */ <add> private boolean existsOneBindingInFinalState() { <add> if (bindingsInFinalStateCount > 0) { <add> return true; <add> } <add> return false; <add> } <ide> }
Java
apache-2.0
3b4156f1666cff9e2b0b980647221ed13a65f15d
0
JNOSQL/artemis
/* * Copyright (c) 2017 Otávio Santana and others * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php. * * You may elect to redistribute this code under either of these licenses. * * Contributors: * * Otavio Santana */ package org.jnosql.artemis.column; import org.jnosql.artemis.Converters; import org.jnosql.artemis.IdNotFoundException; import org.jnosql.artemis.PreparedStatementAsync; import org.jnosql.artemis.column.util.ConverterUtil; import org.jnosql.artemis.reflection.ClassRepresentation; import org.jnosql.artemis.reflection.ClassRepresentations; import org.jnosql.artemis.reflection.FieldRepresentation; import org.jnosql.diana.api.column.ColumnDeleteQuery; import org.jnosql.diana.api.column.ColumnEntity; import org.jnosql.diana.api.column.ColumnFamilyManagerAsync; import org.jnosql.diana.api.column.ColumnObserverParser; import org.jnosql.diana.api.column.ColumnQuery; import org.jnosql.diana.api.column.ColumnQueryParserAsync; import org.jnosql.diana.api.column.query.ColumnQueryBuilder; import java.time.Duration; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.Consumer; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toList; /** * The template method to {@link ColumnTemplateAsync} */ public abstract class AbstractColumnTemplateAsync implements ColumnTemplateAsync { private static final Consumer EMPTY = t -> { }; private static final ColumnQueryParserAsync PARSER = ColumnQueryParserAsync.getParser(); protected abstract ColumnEntityConverter getConverter(); protected abstract ColumnFamilyManagerAsync getManager(); protected abstract ClassRepresentations getClassRepresentations(); protected abstract Converters getConverters(); private ColumnObserverParser observer; private ColumnObserverParser getObserver() { if (Objects.isNull(observer)) { observer = new ColumnMapperObserver(getClassRepresentations()); } return observer; } @Override public <T> void insert(T entity) { insert(entity, EMPTY); } @Override public <T> void insert(T entity, Duration ttl) { insert(entity, ttl, EMPTY); } @Override public <T> void insert(T entity, Consumer<T> callBack) { requireNonNull(entity, "entity is required"); requireNonNull(callBack, "callBack is required"); Consumer<ColumnEntity> dianaCallBack = c -> callBack.accept((T) getConverter().toEntity(entity.getClass(), c)); getManager().insert(getConverter().toColumn(entity), dianaCallBack); } @Override public <T> void insert(T entity, Duration ttl, Consumer<T> callback) { requireNonNull(entity, "entity is required"); requireNonNull(ttl, "ttl is required"); requireNonNull(callback, "callBack is required"); Consumer<ColumnEntity> dianaCallBack = c -> callback.accept((T) getConverter().toEntity(entity.getClass(), c)); getManager().insert(getConverter().toColumn(entity), ttl, dianaCallBack); } @Override public <T> void update(T entity) { requireNonNull(entity, "entity is required"); update(entity, EMPTY); } @Override public <T> void update(T entity, Consumer<T> callback) { requireNonNull(entity, "entity is required"); requireNonNull(callback, "callBack is required"); Consumer<ColumnEntity> dianaCallBack = c -> callback.accept((T) getConverter().toEntity(entity.getClass(), c)); getManager().update(getConverter().toColumn(entity), dianaCallBack); } @Override public void delete(ColumnDeleteQuery query) { requireNonNull(query, "query is required"); getManager().delete(query); } @Override public void delete(ColumnDeleteQuery query, Consumer<Void> callback) { requireNonNull(query, "query is required"); requireNonNull(callback, "callback is required"); getManager().delete(query, callback); } @Override public <T> void select(ColumnQuery query, Consumer<List<T>> callback) { requireNonNull(query, "query is required"); requireNonNull(callback, "callBack is required"); Consumer<List<ColumnEntity>> dianaCallBack = d -> callback.accept( d.stream() .map(getConverter()::toEntity) .map(o -> (T) o) .collect(toList())); getManager().select(query, dianaCallBack); } @Override public <T, ID> void find(Class<T> entityClass, ID id, Consumer<Optional<T>> callback) { requireNonNull(entityClass, "entityClass is required"); requireNonNull(id, "id is required"); requireNonNull(callback, "callBack is required"); ClassRepresentation classRepresentation = getClassRepresentations().get(entityClass); FieldRepresentation idField = classRepresentation.getId() .orElseThrow(() -> IdNotFoundException.newInstance(entityClass)); Object value = ConverterUtil.getValue(id, classRepresentation, idField.getFieldName(), getConverters()); ColumnQuery query = ColumnQueryBuilder.select().from(classRepresentation.getName()) .where(idField.getName()).eq(value).build(); singleResult(query, callback); } @Override public <T, ID> void delete(Class<T> entityClass, ID id, Consumer<Void> callback) { requireNonNull(entityClass, "entityClass is required"); requireNonNull(id, "id is required"); requireNonNull(callback, "callBack is required"); ColumnDeleteQuery query = getDeleteQuery(entityClass, id); delete(query, callback); } @Override public <T, ID> void delete(Class<T> entityClass, ID id) { requireNonNull(entityClass, "entityClass is required"); requireNonNull(id, "id is required"); ColumnDeleteQuery query = getDeleteQuery(entityClass, id); delete(query); } @Override public <T> void query(String query, Consumer<List<T>> callback) { requireNonNull(query, "query is required"); requireNonNull(callback, "callback is required"); Consumer<List<ColumnEntity>> mapper = columnEntities -> { callback.accept(columnEntities.stream().map(c -> (T) getConverter().toEntity(c)) .collect(toList())); }; PARSER.query(query, getManager(), mapper, getObserver()); } @Override public <T> void singleResult(String query, Consumer<Optional<T>> callback) { requireNonNull(query, "query is required"); requireNonNull(callback, "callBack is required"); Consumer<List<ColumnEntity>> mapper = columnEntities -> { List<T> entities = columnEntities.stream().map(c -> (T) getConverter().toEntity(c)).collect(toList()); if (entities.isEmpty()) { callback.accept(Optional.empty()); } if (entities.size() == 1) { callback.accept(Optional.ofNullable(getConverter().toEntity(columnEntities.get(0)))); } throw new UnsupportedOperationException("This query does not return a unique result: " + query); }; PARSER.query(query, getManager(), mapper, getObserver()); } @Override public PreparedStatementAsync prepare(String query) { requireNonNull(query, "query is required"); return new ColumnPreparedStatementAsync(PARSER.prepare(query, getManager(), getObserver()), getConverter()); } private <T, ID> ColumnDeleteQuery getDeleteQuery(Class<T> entityClass, ID id) { ClassRepresentation classRepresentation = getClassRepresentations().get(entityClass); FieldRepresentation idField = classRepresentation.getId() .orElseThrow(() -> IdNotFoundException.newInstance(entityClass)); Object value = ConverterUtil.getValue(id, classRepresentation, idField.getFieldName(), getConverters()); return ColumnQueryBuilder.delete().from(classRepresentation.getName()) .where(idField.getName()).eq(value).build(); } }
artemis-column/src/main/java/org/jnosql/artemis/column/AbstractColumnTemplateAsync.java
/* * Copyright (c) 2017 Otávio Santana and others * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php. * * You may elect to redistribute this code under either of these licenses. * * Contributors: * * Otavio Santana */ package org.jnosql.artemis.column; import org.jnosql.artemis.Converters; import org.jnosql.artemis.IdNotFoundException; import org.jnosql.artemis.PreparedStatementAsync; import org.jnosql.artemis.column.util.ConverterUtil; import org.jnosql.artemis.reflection.ClassRepresentation; import org.jnosql.artemis.reflection.ClassRepresentations; import org.jnosql.artemis.reflection.FieldRepresentation; import org.jnosql.diana.api.column.ColumnDeleteQuery; import org.jnosql.diana.api.column.ColumnEntity; import org.jnosql.diana.api.column.ColumnFamilyManagerAsync; import org.jnosql.diana.api.column.ColumnObserverParser; import org.jnosql.diana.api.column.ColumnQuery; import org.jnosql.diana.api.column.ColumnQueryParserAsync; import org.jnosql.diana.api.column.query.ColumnQueryBuilder; import java.time.Duration; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.Consumer; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toList; /** * The template method to {@link ColumnTemplateAsync} */ public abstract class AbstractColumnTemplateAsync implements ColumnTemplateAsync { private static final Consumer EMPTY = t -> { }; private static final ColumnQueryParserAsync PARSER = ColumnQueryParserAsync.getParser(); protected abstract ColumnEntityConverter getConverter(); protected abstract ColumnFamilyManagerAsync getManager(); protected abstract ClassRepresentations getClassRepresentations(); protected abstract Converters getConverters(); private ColumnObserverParser columnQueryParser; private ColumnObserverParser getObserver() { if (Objects.isNull(columnQueryParser)) { columnQueryParser = new ColumnMapperObserver(getClassRepresentations()); } return columnQueryParser; } @Override public <T> void insert(T entity) { insert(entity, EMPTY); } @Override public <T> void insert(T entity, Duration ttl) { insert(entity, ttl, EMPTY); } @Override public <T> void insert(T entity, Consumer<T> callBack) { requireNonNull(entity, "entity is required"); requireNonNull(callBack, "callBack is required"); Consumer<ColumnEntity> dianaCallBack = c -> callBack.accept((T) getConverter().toEntity(entity.getClass(), c)); getManager().insert(getConverter().toColumn(entity), dianaCallBack); } @Override public <T> void insert(T entity, Duration ttl, Consumer<T> callback) { requireNonNull(entity, "entity is required"); requireNonNull(ttl, "ttl is required"); requireNonNull(callback, "callBack is required"); Consumer<ColumnEntity> dianaCallBack = c -> callback.accept((T) getConverter().toEntity(entity.getClass(), c)); getManager().insert(getConverter().toColumn(entity), ttl, dianaCallBack); } @Override public <T> void update(T entity) { requireNonNull(entity, "entity is required"); update(entity, EMPTY); } @Override public <T> void update(T entity, Consumer<T> callback) { requireNonNull(entity, "entity is required"); requireNonNull(callback, "callBack is required"); Consumer<ColumnEntity> dianaCallBack = c -> callback.accept((T) getConverter().toEntity(entity.getClass(), c)); getManager().update(getConverter().toColumn(entity), dianaCallBack); } @Override public void delete(ColumnDeleteQuery query) { requireNonNull(query, "query is required"); getManager().delete(query); } @Override public void delete(ColumnDeleteQuery query, Consumer<Void> callback) { requireNonNull(query, "query is required"); requireNonNull(callback, "callback is required"); getManager().delete(query, callback); } @Override public <T> void select(ColumnQuery query, Consumer<List<T>> callback) { requireNonNull(query, "query is required"); requireNonNull(callback, "callBack is required"); Consumer<List<ColumnEntity>> dianaCallBack = d -> callback.accept( d.stream() .map(getConverter()::toEntity) .map(o -> (T) o) .collect(toList())); getManager().select(query, dianaCallBack); } @Override public <T, ID> void find(Class<T> entityClass, ID id, Consumer<Optional<T>> callback) { requireNonNull(entityClass, "entityClass is required"); requireNonNull(id, "id is required"); requireNonNull(callback, "callBack is required"); ClassRepresentation classRepresentation = getClassRepresentations().get(entityClass); FieldRepresentation idField = classRepresentation.getId() .orElseThrow(() -> IdNotFoundException.newInstance(entityClass)); Object value = ConverterUtil.getValue(id, classRepresentation, idField.getFieldName(), getConverters()); ColumnQuery query = ColumnQueryBuilder.select().from(classRepresentation.getName()) .where(idField.getName()).eq(value).build(); singleResult(query, callback); } @Override public <T, ID> void delete(Class<T> entityClass, ID id, Consumer<Void> callback) { requireNonNull(entityClass, "entityClass is required"); requireNonNull(id, "id is required"); requireNonNull(callback, "callBack is required"); ColumnDeleteQuery query = getDeleteQuery(entityClass, id); delete(query, callback); } @Override public <T, ID> void delete(Class<T> entityClass, ID id) { requireNonNull(entityClass, "entityClass is required"); requireNonNull(id, "id is required"); ColumnDeleteQuery query = getDeleteQuery(entityClass, id); delete(query); } @Override public <T> void query(String query, Consumer<List<T>> callback) { requireNonNull(query, "query is required"); requireNonNull(callback, "callback is required"); Consumer<List<ColumnEntity>> mapper = columnEntities -> { callback.accept(columnEntities.stream().map(c -> (T) getConverter().toEntity(c)) .collect(toList())); }; PARSER.query(query, getManager(), mapper, getObserver()); } @Override public <T> void singleResult(String query, Consumer<Optional<T>> callback) { requireNonNull(query, "query is required"); requireNonNull(callback, "callBack is required"); Consumer<List<ColumnEntity>> mapper = columnEntities -> { List<T> entities = columnEntities.stream().map(c -> (T) getConverter().toEntity(c)).collect(toList()); if (entities.isEmpty()) { callback.accept(Optional.empty()); } if (entities.size() == 1) { callback.accept(Optional.ofNullable(getConverter().toEntity(columnEntities.get(0)))); } throw new UnsupportedOperationException("This query does not return a unique result: " + query); }; PARSER.query(query, getManager(), mapper, getObserver()); } @Override public PreparedStatementAsync prepare(String query) { requireNonNull(query, "query is required"); return new ColumnPreparedStatementAsync(PARSER.prepare(query, getManager(), getObserver()), getConverter()); } private <T, ID> ColumnDeleteQuery getDeleteQuery(Class<T> entityClass, ID id) { ClassRepresentation classRepresentation = getClassRepresentations().get(entityClass); FieldRepresentation idField = classRepresentation.getId() .orElseThrow(() -> IdNotFoundException.newInstance(entityClass)); Object value = ConverterUtil.getValue(id, classRepresentation, idField.getFieldName(), getConverters()); return ColumnQueryBuilder.delete().from(classRepresentation.getName()) .where(idField.getName()).eq(value).build(); } }
fixes variable name
artemis-column/src/main/java/org/jnosql/artemis/column/AbstractColumnTemplateAsync.java
fixes variable name
<ide><path>rtemis-column/src/main/java/org/jnosql/artemis/column/AbstractColumnTemplateAsync.java <ide> <ide> protected abstract Converters getConverters(); <ide> <del> private ColumnObserverParser columnQueryParser; <add> private ColumnObserverParser observer; <ide> <ide> <ide> private ColumnObserverParser getObserver() { <del> if (Objects.isNull(columnQueryParser)) { <del> columnQueryParser = new ColumnMapperObserver(getClassRepresentations()); <add> if (Objects.isNull(observer)) { <add> observer = new ColumnMapperObserver(getClassRepresentations()); <ide> } <del> return columnQueryParser; <add> return observer; <ide> } <ide> <ide>
Java
bsd-2-clause
e297f2799fb7535fe013ce9084aff49aa3c7a49c
0
clementval/claw-compiler,clementval/claw-compiler
/* * This file is released under terms of BSD license * See LICENSE file for more information */ package cx2x.translator.transformation.claw.parallelize; import cx2x.translator.language.ClawLanguage; import cx2x.translator.language.helper.TransformationHelper; import cx2x.xcodeml.exception.IllegalTransformationException; import cx2x.xcodeml.helper.XnodeUtil; import cx2x.xcodeml.transformation.Transformation; import cx2x.xcodeml.transformation.Transformer; import cx2x.xcodeml.xnode.*; import xcodeml.util.XmOption; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * The parallelize forward transformation applies the changes in the subroutine * signatures to function call and function in which the call is nested if * needed. * * During the tranformation, a new "CLAW" XcodeML module file is generated * if the transformation has to be applied accross several file unit. This * file will be located in the same directory as the original XcodeML module * file and has the following naming structure: module_name.claw.xmod * * @author clementval */ public class ParallelizeForward extends Transformation { private final ClawLanguage _claw; private Xnode _fctCall; private XfunctionType _fctType; private Xmod _mod = null; private boolean _localFct = false; private boolean _flatten = false; private Xnode _innerDoStatement; private Xnode _outerDoStatement; private String _calledFctName; // For topological sorting private String _callingFctName; // For topological sorting private List<String> _promotedVar; // List of promoted array from the call /** * Constructs a new Parallelize transformation triggered from a specific * pragma. * @param directive The directive that triggered the define transformation. */ public ParallelizeForward(ClawLanguage directive) { super(directive); _claw = directive; // Keep information about the claw directive here _promotedVar = new ArrayList<>(); } @Override public boolean analyze(XcodeProgram xcodeml, Transformer transformer) { Xnode next = XnodeUtil.getNextSibling(_claw.getPragma()); if(next == null){ xcodeml.addError("Directive is not followed by a valid statement.", _claw.getPragma().getLineNo()); return false; } if(next.opcode() == Xcode.EXPRSTATEMENT || next.opcode() == Xcode.FASSIGNSTATEMENT) { _fctCall = next.find(Xcode.FUNCTIONCALL); if(_fctCall != null){ return analyzeForward(xcodeml); } } else if (next.opcode() == Xcode.FDOSTATEMENT) { _outerDoStatement = next; return analyzeForwardWithDo(xcodeml, next); } xcodeml.addError("Directive is not followed by a valid statement.", _claw.getPragma().getLineNo()); return false; } /** * Analyze the directive when it is used just before a do statement. * @param xcodeml Current XcodeML file unit. * @param doStmt The do statement following the pragma. * @return True if the analysis succeed. False otherwise. */ private boolean analyzeForwardWithDo(XcodeProgram xcodeml, Xnode doStmt){ _flatten = true; if(doStmt == null){ xcodeml.addError("Directive is not followed by do statement.", _claw.getPragma().getLineNo()); return false; } // Try to locate the fct call inside of the do statements. Can be nested. return analyzeNestedDoStmts(xcodeml, doStmt); } /** * Recursively analyze nested do statements in order to find the call * statements. * @param xcodeml Current XcodeML file unit. * @param doStmt First do statement to start the analyzis. * @return True if the analysis succed. False otehrwise. */ private boolean analyzeNestedDoStmts(XcodeProgram xcodeml, Xnode doStmt){ _innerDoStatement = doStmt; Xnode body = doStmt.find(Xcode.BODY); if(body == null){ xcodeml.addError("Cannot locate function call.", _claw.getPragma().getLineNo()); return false; } for(Xnode n : body.getChildren()){ if(n.opcode() == Xcode.FDOSTATEMENT){ return analyzeNestedDoStmts(xcodeml, n); } else if(n.opcode() != Xcode.FPRAGMASTATEMENT && n.opcode() != Xcode.EXPRSTATEMENT) { xcodeml.addError("Only pragmas, comments and function calls allowed " + "in the do statements.", _claw.getPragma().getLineNo()); return false; } else if (n.opcode() == Xcode.EXPRSTATEMENT || n.opcode() == Xcode.FASSIGNSTATEMENT) { _fctCall = n.find(Xcode.FUNCTIONCALL); if(_fctCall != null){ return analyzeForward(xcodeml); } } } xcodeml.addError("Function call not found.", _claw.getPragma().getLineNo()); return false; } /** * Analyze the directive when it is used just before a function call. * @param xcodeml Current XcodeML file unit. * @return True if the analysis succeed. False otherwise. */ private boolean analyzeForward(XcodeProgram xcodeml){ if(_fctCall == null){ xcodeml.addError("Directive is not followed by a fct call.", _claw.getPragma().getLineNo()); return false; } _calledFctName = _fctCall.find(Xcode.NAME).getValue(); XfunctionDefinition fctDef = XnodeUtil.findFunctionDefinition( xcodeml.getGlobalDeclarationsTable(), _calledFctName); XfunctionDefinition parentFctDef = XnodeUtil.findParentFunction(_claw.getPragma()); if(parentFctDef == null){ xcodeml.addError("Parellilize directive is not nested in a " + "function/subroutine.", _claw.getPragma().getLineNo()); return false; } XmoduleDefinition parentModule = XnodeUtil.findParentModule(parentFctDef); String fctType = _fctCall.find(Xcode.NAME).getAttribute(Xattr.TYPE); if(fctType.startsWith(Xtype.PREFIX_PROCEDURE)){ /* If type is a FbasicType element for a type-bound procedure, we have to * find the correct function in the typeTable. * TODO if there is a rename. * TODO generic call */ Xid id = parentModule.getSymbolTable().get(_calledFctName); if(id == null){ List<Xdecl> uses = XnodeUtil.getAllUse(parentFctDef); uses.addAll(XnodeUtil.getAllUse(parentModule)); if(!findInModule(uses)){ xcodeml.addError("Function definition not found in module ", _claw.getPragma().getLineNo()); return false; } } else { _fctType = (XfunctionType)xcodeml.getTypeTable().get(id.getType()); } } else { Xtype rawType = xcodeml.getTypeTable().get(fctType); if(rawType instanceof XfunctionType) { _fctType = (XfunctionType) rawType; } else { xcodeml.addError("Unsupported type of XcodeML/F element for the function " + _calledFctName, _claw.getPragma().getLineNo()); return false; } } /* Workaround for a bug in OMNI Compiler. Look at test case * claw/abstraction10. In this test case, the XcodeML/F intermediate * representation for the function call points to a FfunctionType element * with no parameters. Thus, we have to find the correct FfunctionType * for the same function/subroutine with the same name in the module * symbol table. */ if(_fctType.getParameterNb() == 0){ // If not, try to find the correct FfunctionType in the module definitions Xid id = parentModule.getSymbolTable().get(_calledFctName); if(id == null){ // Function is not located in the current module. List<Xdecl> uses = XnodeUtil.getAllUse(parentFctDef); uses.addAll(XnodeUtil.getAllUse(parentModule)); if(!findInModule(uses)){ xcodeml.addError("Function definition not found in module ", _claw.getPragma().getLineNo()); return false; } } else { _fctType = (XfunctionType)xcodeml.getTypeTable().get(id.getType()); if(_fctType == null){ xcodeml.addError("Called function cannot be found in the same module ", _claw.getPragma().getLineNo()); return false; } } } // end of workaround _callingFctName = parentFctDef.getName().getValue(); if(_fctType != null && fctDef != null){ _localFct = true; } else { // Has been found already if(_fctType != null && _calledFctName == null){ return true; } // Get all the use statements in the fct and module definitions List<Xdecl> uses = XnodeUtil.getAllUse(parentFctDef); uses.addAll(XnodeUtil.getAllUse(parentModule)); // Try to locate the fct in the modules defined in use statements if(findInModule(uses)){ return true; } xcodeml.addError("Function signature not found in the current module.", _claw.getPragma().getLineNo()); return false; } return true; } /** * Find a function in modules. * @param useDecls List of all USE statement declarations available for * search. * @return True if the function was found. False otherwise. */ private boolean findInModule(List<Xdecl> useDecls){ // TODO handle rename for(Xdecl d : useDecls){ // Check whether a CLAW file is available. _mod = TransformationHelper. locateClawModuleFile(d.getAttribute(Xattr.NAME)); if(_mod != null){ // debug information if(XmOption.isDebugOutput()){ System.out.println("Reading CLAW module file: " + _mod.getFullPath()); } if(_mod.getIdentifiers().contains(_calledFctName)){ String type = _mod.getIdentifiers().get(_calledFctName). getAttribute(Xattr.TYPE); _fctType = (XfunctionType) _mod.getTypeTable().get(type); if(_fctType != null){ _calledFctName = null; return true; } } } } return false; } @Override public void transform(XcodeProgram xcodeml, Transformer transformer, Transformation other) throws Exception { if(_flatten){ transformFlatten(xcodeml, transformer); } else { transformStd(xcodeml, transformer); } // Delete pragma _claw.getPragma().delete(); } /** * Do the flatten transformation for the forward directive. This * transformation adapt the function call nested in the do statements and * removes those do statements. The containing subroutine is not adapted. * @param xcodeml Current XcodeML file unit. * @param transformer Current transformer. * @throws Exception If something goes wrong. */ private void transformFlatten(XcodeProgram xcodeml, Transformer transformer) throws Exception { XnodeUtil.extractBody(_innerDoStatement, _outerDoStatement); _outerDoStatement.delete(); transformStd(xcodeml, transformer); } /** * Do the standard transformation for the forward directive. This * transformation adapt the function call and replicates any necessary changes * to the containing subroutine. * @param xcodeml Current XcodeML file unit. * @param transformer Current transformer. * @throws Exception If something goes wrong. */ private void transformStd(XcodeProgram xcodeml, Transformer transformer) throws Exception { XfunctionDefinition fDef = XnodeUtil.findParentFunction(_claw.getPragma()); if(fDef == null){ throw new IllegalTransformationException("Parallelize directive is not " + "nested in a function/subroutine.", _claw.getPragma().getLineNo()); } XfunctionType parentFctType = (XfunctionType)xcodeml.getTypeTable(). get(fDef.getName().getAttribute(Xattr.TYPE)); List<Xnode> params = _fctType.getParams().getAll(); List<Xnode> args = _fctCall.find(Xcode.ARGUMENTS).getChildren(); /* Compute the position of the first new arguments. In the case of a * type-bound procedure call, the first parameter declared in the procedure * is not actually passed as an argument. In this case, we add an offset of * one to the starting arguments. * TODO the check might be change to fit with the XcodeML/F2008 specs. The * TODO cont: attribute data_ref will probably be gone and replaced by a * TODO cont: FmemberRef element */ int argOffset = 0; if(params.get(0).getAttribute(Xattr.TYPE).startsWith(Xtype.PREFIX_STRUCT) && _fctCall.find(Xcode.NAME).hasAttribute(Xattr.DATAREF)) { argOffset = 1; } // 1. Adapt function call with potential new arguments for(int i = args.size() + argOffset; i < params.size(); i++){ Xnode p = params.get(i); String var = p.getValue(); String type; XbasicType paramType = (XbasicType) xcodeml.getTypeTable().get(p.getAttribute(Xattr.TYPE)); if(!fDef.getSymbolTable().contains(var)){ if(_flatten && !paramType.getBooleanAttribute(Xattr.IS_OPTIONAL)){ throw new IllegalTransformationException("Variable " + var + " must" + " be locally defined where the last call to parallelize if made.", _claw.getPragma().getLineNo()); } // Size variable have to be declared XbasicType intTypeIntentIn = XnodeUtil.createBasicType(xcodeml, xcodeml.getTypeTable().generateIntegerTypeHash(), Xname.TYPE_F_INT, Xintent.IN); xcodeml.getTypeTable().add(intTypeIntentIn); XnodeUtil.createIdAndDecl(var, intTypeIntentIn.getType(), Xname.SCLASS_F_PARAM, fDef, xcodeml); type = intTypeIntentIn.getType(); XnodeUtil.createAndAddParam(xcodeml, var, type, parentFctType); } else { // Var exists already. Add to the parameters if not here. type = fDef.getSymbolTable().get(var).getType(); /* If flatten mode, we do not add extra parameters to the function * definition */ if(!_flatten) { XnodeUtil. createAndAddParamIfNotExists(xcodeml, var, type, parentFctType); } } // Add variable in the function call Xnode arg = XnodeUtil.createNamedValue(var, xcodeml); Xnode namedValVar = XnodeUtil.createVar(type, var, Xscope.LOCAL, xcodeml); arg.appendToChildren(namedValVar, false); _fctCall.find(Xcode.ARGUMENTS).appendToChildren(arg, false); } // In flatten mode, arguments are demoted if needed. if(_flatten){ Xnode arguments = _fctCall.find(Xcode.ARGUMENTS); for(Xnode arg : arguments.getChildren()){ if(arg.opcode() == Xcode.FARRAYREF && arg.findAny( Arrays.asList(Xcode.INDEXRANGE, Xcode.ARRAYINDEX)) != null) { Xnode var = arg.find(Xcode.VARREF, Xcode.VAR); if(var != null){ XnodeUtil.insertAfter(arg, var.cloneObject()); arg.delete(); } } } } else { // 2. Adapt function/subroutine in which the function call is nested for(Xnode pBase : _fctType.getParams().getAll()){ for(Xnode pUpdate : parentFctType.getParams().getAll()){ if(pBase.getValue().equals(pUpdate.getValue())){ XbasicType typeBase = (_localFct) ? (XbasicType) xcodeml.getTypeTable().get(pBase.getAttribute(Xattr.TYPE)) : (XbasicType) _mod.getTypeTable(). get(pBase.getAttribute(Xattr.TYPE)); XbasicType typeToUpdate = (XbasicType)xcodeml.getTypeTable(). get(pUpdate.getAttribute(Xattr.TYPE)); // Types have different dimensions if(typeBase.getDimensions() > typeToUpdate.getDimensions()){ String type = _localFct ? XnodeUtil.duplicateWithDimension(typeBase, typeToUpdate, xcodeml, xcodeml) : XnodeUtil.duplicateWithDimension(typeBase, typeToUpdate, xcodeml, _mod); pUpdate.setAttribute(Xattr.TYPE, type); Xid id = fDef.getSymbolTable().get(pBase.getValue()); if(id != null){ id.setAttribute(Xattr.TYPE, type); } Xdecl varDecl = fDef.getDeclarationTable().get(pBase.getValue()); if(varDecl != null){ varDecl.find(Xcode.NAME).setAttribute(Xattr.TYPE, type); } _promotedVar.add(pBase.getValue()); } } } } if(!parentFctType.getBooleanAttribute(Xattr.IS_PRIVATE)){ // 3. Replicate the change in a potential module file XmoduleDefinition modDef = XnodeUtil.findParentModule(fDef); TransformationHelper.updateModuleSignature(xcodeml, fDef, parentFctType, modDef, _claw, transformer, false); } else if(_fctCall.find(Xcode.NAME).hasAttribute(Xattr.DATAREF)){ /* The function/subroutine is private but accessible through the type * as a type-bound procedure. In this case, the function is not in the * type table of the .xmod file. We need to insert it first and then * we can update it. */ XmoduleDefinition modDef = XnodeUtil.findParentModule(fDef); TransformationHelper.updateModuleSignature(xcodeml, fDef, parentFctType, modDef, _claw, transformer, true); } } propagatePromotion(); } /** * Propagate possible promotion in assignements statements in the parent * subroutine of the function call. */ private void propagatePromotion(){ XfunctionDefinition parentFctDef = XnodeUtil.findParentFunction(_fctCall); List<Xnode> assignments = XnodeUtil.findAll(Xcode.FASSIGNSTATEMENT, parentFctDef); for(Xnode assignment : assignments){ Xnode lhs = assignment.getChild(0); Xnode rhs = assignment.getChild(1); List<Xnode> varsInRhs = XnodeUtil.findAll(Xcode.VAR, rhs); for(Xnode var : varsInRhs){ if(_promotedVar.contains(var.getValue()) && XnodeUtil.findParent(Xcode.FUNCTIONCALL, var) == null) { Xnode varInLhs = XnodeUtil.find(Xcode.VAR, lhs, true); // TODO is assigned to a pointer? Is so, pointer must be promoted. break; } } } } @Override public boolean canBeTransformedWith(Transformation other) { return false; // independent transformation } /** * Get the called fct name. * @return Fct name. */ public String getCalledFctName(){ return _calledFctName; } /** * Get the parent fct name. * @return Fct name. */ public String getCallingFctName(){ return _callingFctName; } }
omni-cx2x/src/cx2x/translator/transformation/claw/parallelize/ParallelizeForward.java
/* * This file is released under terms of BSD license * See LICENSE file for more information */ package cx2x.translator.transformation.claw.parallelize; import cx2x.translator.language.ClawLanguage; import cx2x.translator.language.helper.TransformationHelper; import cx2x.xcodeml.exception.IllegalTransformationException; import cx2x.xcodeml.helper.XnodeUtil; import cx2x.xcodeml.transformation.Transformation; import cx2x.xcodeml.transformation.Transformer; import cx2x.xcodeml.xnode.*; import xcodeml.util.XmOption; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * The parallelize forward transformation applies the changes in the subroutine * signatures to function call and function in which the call is nested if * needed. * * During the tranformation, a new "CLAW" XcodeML module file is generated * if the transformation has to be applied accross several file unit. This * file will be located in the same directory as the original XcodeML module * file and has the following naming structure: module_name.claw.xmod * * @author clementval */ public class ParallelizeForward extends Transformation { private final ClawLanguage _claw; private Xnode _fctCall; private XfunctionType _fctType; private Xmod _mod = null; private boolean _localFct = false; private boolean _flatten = false; private Xnode _innerDoStatement; private Xnode _outerDoStatement; private String _calledFctName; // For topological sorting private String _callingFctName; // For topological sorting private List<String> _promotedVar; // List of promoted array from the call /** * Constructs a new Parallelize transformation triggered from a specific * pragma. * @param directive The directive that triggered the define transformation. */ public ParallelizeForward(ClawLanguage directive) { super(directive); _claw = directive; // Keep information about the claw directive here _promotedVar = new ArrayList<>(); } @Override public boolean analyze(XcodeProgram xcodeml, Transformer transformer) { Xnode next = XnodeUtil.getNextSibling(_claw.getPragma()); if(next == null){ xcodeml.addError("Directive is not followed by a valid statement.", _claw.getPragma().getLineNo()); return false; } if(next.opcode() == Xcode.EXPRSTATEMENT || next.opcode() == Xcode.FASSIGNSTATEMENT) { _fctCall = next.find(Xcode.FUNCTIONCALL); if(_fctCall != null){ return analyzeForward(xcodeml); } } else if (next.opcode() == Xcode.FDOSTATEMENT) { _outerDoStatement = next; return analyzeForwardWithDo(xcodeml, next); } xcodeml.addError("Directive is not followed by a valid statement.", _claw.getPragma().getLineNo()); return false; } /** * Analyze the directive when it is used just before a do statement. * @param xcodeml Current XcodeML file unit. * @param doStmt The do statement following the pragma. * @return True if the analysis succeed. False otherwise. */ private boolean analyzeForwardWithDo(XcodeProgram xcodeml, Xnode doStmt){ _flatten = true; if(doStmt == null){ xcodeml.addError("Directive is not followed by do statement.", _claw.getPragma().getLineNo()); return false; } // Try to locate the fct call inside of the do statements. Can be nested. return analyzeNestedDoStmts(xcodeml, doStmt); } /** * Recursively analyze nested do statements in order to find the call * statements. * @param xcodeml Current XcodeML file unit. * @param doStmt First do statement to start the analyzis. * @return True if the analysis succed. False otehrwise. */ private boolean analyzeNestedDoStmts(XcodeProgram xcodeml, Xnode doStmt){ _innerDoStatement = doStmt; Xnode body = doStmt.find(Xcode.BODY); if(body == null){ xcodeml.addError("Cannot locate function call.", _claw.getPragma().getLineNo()); return false; } for(Xnode n : body.getChildren()){ if(n.opcode() == Xcode.FDOSTATEMENT){ return analyzeNestedDoStmts(xcodeml, n); } else if(n.opcode() != Xcode.FPRAGMASTATEMENT && n.opcode() != Xcode.EXPRSTATEMENT) { xcodeml.addError("Only pragmas, comments and function calls allowed " + "in the do statements.", _claw.getPragma().getLineNo()); return false; } else if (n.opcode() == Xcode.EXPRSTATEMENT || n.opcode() == Xcode.FASSIGNSTATEMENT) { _fctCall = n.find(Xcode.FUNCTIONCALL); if(_fctCall != null){ return analyzeForward(xcodeml); } } } xcodeml.addError("Function call not found.", _claw.getPragma().getLineNo()); return false; } /** * Analyze the directive when it is used just before a function call. * @param xcodeml Current XcodeML file unit. * @return True if the analysis succeed. False otherwise. */ private boolean analyzeForward(XcodeProgram xcodeml){ if(_fctCall == null){ xcodeml.addError("Directive is not followed by a fct call.", _claw.getPragma().getLineNo()); return false; } _calledFctName = _fctCall.find(Xcode.NAME).getValue(); XfunctionDefinition fctDef = XnodeUtil.findFunctionDefinition( xcodeml.getGlobalDeclarationsTable(), _calledFctName); XfunctionDefinition parentFctDef = XnodeUtil.findParentFunction(_claw.getPragma()); if(parentFctDef == null){ xcodeml.addError("Parellilize directive is not nested in a " + "function/subroutine.", _claw.getPragma().getLineNo()); return false; } XmoduleDefinition parentModule = XnodeUtil.findParentModule(parentFctDef); String fctType = _fctCall.find(Xcode.NAME).getAttribute(Xattr.TYPE); if(fctType.startsWith(Xtype.PREFIX_PROCEDURE)){ /* If type is a FbasicType element for a type-bound procedure, we have to * find the correct function in the typeTable. * TODO if there is a rename. * TODO generic call */ Xid id = parentModule.getSymbolTable().get(_calledFctName); if(id == null){ List<Xdecl> uses = XnodeUtil.getAllUse(parentFctDef); uses.addAll(XnodeUtil.getAllUse(parentModule)); if(!findInModule(uses)){ xcodeml.addError("Function definition not found in module ", _claw.getPragma().getLineNo()); return false; } } else { _fctType = (XfunctionType)xcodeml.getTypeTable().get(id.getType()); } } else { Xtype rawType = xcodeml.getTypeTable().get(fctType); if(rawType instanceof XfunctionType) { _fctType = (XfunctionType) rawType; } else { xcodeml.addError("Unsupported type of XcodeML/F element for the function " + _calledFctName, _claw.getPragma().getLineNo()); return false; } } /* Workaround for a bug in OMNI Compiler. Look at test case * claw/abstraction10. In this test case, the XcodeML/F intermediate * representation for the function call points to a FfunctionType element * with no parameters. Thus, we have to find the correct FfunctionType * for the same function/subroutine with the same name in the module * symbol table. */ if(_fctType.getParameterNb() == 0){ // If not, try to find the correct FfunctionType in the module definitions Xid id = parentModule.getSymbolTable().get(_calledFctName); if(id == null){ // Function is not located in the current module. List<Xdecl> uses = XnodeUtil.getAllUse(parentFctDef); uses.addAll(XnodeUtil.getAllUse(parentModule)); if(!findInModule(uses)){ xcodeml.addError("Function definition not found in module ", _claw.getPragma().getLineNo()); return false; } } else { _fctType = (XfunctionType)xcodeml.getTypeTable().get(id.getType()); if(_fctType == null){ xcodeml.addError("Called function cannot be found in the same module ", _claw.getPragma().getLineNo()); return false; } } } // end of workaround _callingFctName = parentFctDef.getName().getValue(); if(_fctType != null && fctDef != null){ _localFct = true; } else { // Has been found already if(_fctType != null && _calledFctName == null){ return true; } // Get all the use statements in the fct and module definitions List<Xdecl> uses = XnodeUtil.getAllUse(parentFctDef); uses.addAll(XnodeUtil.getAllUse(parentModule)); // Try to locate the fct in the modules defined in use statements if(findInModule(uses)){ return true; } xcodeml.addError("Function signature not found in the current module.", _claw.getPragma().getLineNo()); return false; } return true; } /** * Find a function in modules. * @param useDecls List of all USE statement declarations available for * search. * @return True if the function was found. False otherwise. */ private boolean findInModule(List<Xdecl> useDecls){ // TODO handle rename for(Xdecl d : useDecls){ // Check whether a CLAW file is available. _mod = TransformationHelper. locateClawModuleFile(d.getAttribute(Xattr.NAME)); if(_mod != null){ // debug information if(XmOption.isDebugOutput()){ System.out.println("Reading CLAW module file: " + _mod.getFullPath()); } if(_mod.getIdentifiers().contains(_calledFctName)){ String type = _mod.getIdentifiers().get(_calledFctName). getAttribute(Xattr.TYPE); _fctType = (XfunctionType) _mod.getTypeTable().get(type); if(_fctType != null){ _calledFctName = null; return true; } } } } return false; } @Override public void transform(XcodeProgram xcodeml, Transformer transformer, Transformation other) throws Exception { if(_flatten){ transformFlatten(xcodeml, transformer); } else { transformStd(xcodeml, transformer); } // Delete pragma _claw.getPragma().delete(); } /** * Do the flatten transformation for the forward directive. This * transformation adapt the function call nested in the do statements and * removes those do statements. The containing subroutine is not adapted. * @param xcodeml Current XcodeML file unit. * @param transformer Current transformer. * @throws Exception If something goes wrong. */ private void transformFlatten(XcodeProgram xcodeml, Transformer transformer) throws Exception { XnodeUtil.extractBody(_innerDoStatement, _outerDoStatement); _outerDoStatement.delete(); transformStd(xcodeml, transformer); } /** * Do the standard transformation for the forward directive. This * transformation adapt the function call and replicates any necessary changes * to the containing subroutine. * @param xcodeml Current XcodeML file unit. * @param transformer Current transformer. * @throws Exception If something goes wrong. */ private void transformStd(XcodeProgram xcodeml, Transformer transformer) throws Exception { XfunctionDefinition fDef = XnodeUtil.findParentFunction(_claw.getPragma()); if(fDef == null){ throw new IllegalTransformationException("Parallelize directive is not " + "nested in a function/subroutine.", _claw.getPragma().getLineNo()); } XfunctionType parentFctType = (XfunctionType)xcodeml.getTypeTable(). get(fDef.getName().getAttribute(Xattr.TYPE)); List<Xnode> params = _fctType.getParams().getAll(); List<Xnode> args = _fctCall.find(Xcode.ARGUMENTS).getChildren(); /* Compute the position of the first new arguments. In the case of a * type-bound procedure call, the first parameter declared in the procedure * is not actually passed as an argument. In this case, we add an offset of * one to the starting arguments. * TODO the check might be change to fit with the XcodeML/F2008 specs. The * TODO cont: attribute data_ref will probably be gone and replaced by a * TODO cont: FmemberRef element */ int argOffset = 0; if(params.get(0).getAttribute(Xattr.TYPE).startsWith(Xtype.PREFIX_STRUCT) && _fctCall.find(Xcode.NAME).hasAttribute(Xattr.DATAREF)) { argOffset = 1; } // 1. Adapt function call with potential new arguments for(int i = args.size() + argOffset; i < params.size(); i++){ Xnode p = params.get(i); String var = p.getValue(); String type; if(!fDef.getSymbolTable().contains(var)){ if(_flatten){ throw new IllegalTransformationException("Variable " + var + " must" + " be locally defined where the last call to parallelize if made.", _claw.getPragma().getLineNo()); } // Size variable have to be declared XbasicType intTypeIntentIn = XnodeUtil.createBasicType(xcodeml, xcodeml.getTypeTable().generateIntegerTypeHash(), Xname.TYPE_F_INT, Xintent.IN); xcodeml.getTypeTable().add(intTypeIntentIn); XnodeUtil.createIdAndDecl(var, intTypeIntentIn.getType(), Xname.SCLASS_F_PARAM, fDef, xcodeml); type = intTypeIntentIn.getType(); XnodeUtil.createAndAddParam(xcodeml, var, type, parentFctType); } else { // Var exists already. Add to the parameters if not here. type = fDef.getSymbolTable().get(var).getType(); /* If flatten mode, we do not add extra parameters to the function * definition */ if(!_flatten) { XnodeUtil. createAndAddParamIfNotExists(xcodeml, var, type, parentFctType); } } // Add variable in the function call Xnode arg = XnodeUtil.createNamedValue(var, xcodeml); Xnode namedValVar = XnodeUtil.createVar(type, var, Xscope.LOCAL, xcodeml); arg.appendToChildren(namedValVar, false); _fctCall.find(Xcode.ARGUMENTS).appendToChildren(arg, false); } // In flatten mode, arguments are demoted if needed. if(_flatten){ Xnode arguments = _fctCall.find(Xcode.ARGUMENTS); for(Xnode arg : arguments.getChildren()){ if(arg.opcode() == Xcode.FARRAYREF && arg.findAny( Arrays.asList(Xcode.INDEXRANGE, Xcode.ARRAYINDEX)) != null) { Xnode var = arg.find(Xcode.VARREF, Xcode.VAR); if(var != null){ XnodeUtil.insertAfter(arg, var.cloneObject()); arg.delete(); } } } } else { // 2. Adapt function/subroutine in which the function call is nested for(Xnode pBase : _fctType.getParams().getAll()){ for(Xnode pUpdate : parentFctType.getParams().getAll()){ if(pBase.getValue().equals(pUpdate.getValue())){ XbasicType typeBase = (_localFct) ? (XbasicType) xcodeml.getTypeTable().get(pBase.getAttribute(Xattr.TYPE)) : (XbasicType) _mod.getTypeTable(). get(pBase.getAttribute(Xattr.TYPE)); XbasicType typeToUpdate = (XbasicType)xcodeml.getTypeTable(). get(pUpdate.getAttribute(Xattr.TYPE)); // Types have different dimensions if(typeBase.getDimensions() > typeToUpdate.getDimensions()){ String type = _localFct ? XnodeUtil.duplicateWithDimension(typeBase, typeToUpdate, xcodeml, xcodeml) : XnodeUtil.duplicateWithDimension(typeBase, typeToUpdate, xcodeml, _mod); pUpdate.setAttribute(Xattr.TYPE, type); Xid id = fDef.getSymbolTable().get(pBase.getValue()); if(id != null){ id.setAttribute(Xattr.TYPE, type); } Xdecl varDecl = fDef.getDeclarationTable().get(pBase.getValue()); if(varDecl != null){ varDecl.find(Xcode.NAME).setAttribute(Xattr.TYPE, type); } _promotedVar.add(pBase.getValue()); } } } } if(!parentFctType.getBooleanAttribute(Xattr.IS_PRIVATE)){ // 3. Replicate the change in a potential module file XmoduleDefinition modDef = XnodeUtil.findParentModule(fDef); TransformationHelper.updateModuleSignature(xcodeml, fDef, parentFctType, modDef, _claw, transformer, false); } else if(_fctCall.find(Xcode.NAME).hasAttribute(Xattr.DATAREF)){ /* The function/subroutine is private but accessible through the type * as a type-bound procedure. In this case, the function is not in the * type table of the .xmod file. We need to insert it first and then * we can update it. */ XmoduleDefinition modDef = XnodeUtil.findParentModule(fDef); TransformationHelper.updateModuleSignature(xcodeml, fDef, parentFctType, modDef, _claw, transformer, true); } } propagatePromotion(); } /** * Propagate possible promotion in assignements statements in the parent * subroutine of the function call. */ private void propagatePromotion(){ XfunctionDefinition parentFctDef = XnodeUtil.findParentFunction(_fctCall); List<Xnode> assignments = XnodeUtil.findAll(Xcode.FASSIGNSTATEMENT, parentFctDef); for(Xnode assignment : assignments){ Xnode lhs = assignment.getChild(0); Xnode rhs = assignment.getChild(1); List<Xnode> varsInRhs = XnodeUtil.findAll(Xcode.VAR, rhs); for(Xnode var : varsInRhs){ if(_promotedVar.contains(var.getValue()) && XnodeUtil.findParent(Xcode.FUNCTIONCALL, var) == null) { Xnode varInLhs = XnodeUtil.find(Xcode.VAR, lhs, true); // TODO is assigned to a pointer? Is so, pointer must be promoted. break; } } } } @Override public boolean canBeTransformedWith(Transformation other) { return false; // independent transformation } /** * Get the called fct name. * @return Fct name. */ public String getCalledFctName(){ return _calledFctName; } /** * Get the parent fct name. * @return Fct name. */ public String getCallingFctName(){ return _callingFctName; } }
Avoid problem with optional parameter #35
omni-cx2x/src/cx2x/translator/transformation/claw/parallelize/ParallelizeForward.java
Avoid problem with optional parameter
<ide><path>mni-cx2x/src/cx2x/translator/transformation/claw/parallelize/ParallelizeForward.java <ide> String var = p.getValue(); <ide> String type; <ide> <add> XbasicType paramType = <add> (XbasicType) xcodeml.getTypeTable().get(p.getAttribute(Xattr.TYPE)); <add> <ide> if(!fDef.getSymbolTable().contains(var)){ <del> if(_flatten){ <add> if(_flatten && !paramType.getBooleanAttribute(Xattr.IS_OPTIONAL)){ <ide> throw new IllegalTransformationException("Variable " + var + " must" + <ide> " be locally defined where the last call to parallelize if made.", <ide> _claw.getPragma().getLineNo());
Java
mit
9a654b883e4b5def507ea8e0379c3f4b19140106
0
Ordinastie/MalisisCore
/* * The MIT License (MIT) * * Copyright (c) 2014 Ordinastie * * 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 net.malisis.core.util.multiblock; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import net.malisis.core.MalisisCore; import net.malisis.core.block.IComponent; import net.malisis.core.block.component.DirectionalComponent; import net.malisis.core.registry.AutoLoad; import net.malisis.core.util.BlockPosUtils; import net.malisis.core.util.EnumFacingUtils; import net.malisis.core.util.MBlockState; import net.malisis.core.util.blockdata.BlockDataHandler; import net.minecraft.block.properties.PropertyDirection; import net.minecraft.block.state.IBlockState; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; /** * @author Ordinastie * */ @AutoLoad public abstract class MultiBlock implements Iterable<MBlockState> { public static String ORIGIN_BLOCK_DATA = MalisisCore.modid + ":multiBlockOrigin"; static { BlockDataHandler.registerBlockData(ORIGIN_BLOCK_DATA, BlockPosUtils::fromBytes, BlockPosUtils::toBytes); } protected Map<BlockPos, MBlockState> states = new HashMap<>(); protected BlockPos offset = BlockPos.ORIGIN; protected PropertyDirection property = DirectionalComponent.HORIZONTAL; private int rotation; private boolean bulkPlace; private boolean bulkBreak; public void setOffset(BlockPos offset) { this.offset = offset; buildStates(); } public void setPropertyDirection(PropertyDirection property) { this.property = property; } public void setRotation(IBlockState state) { if (state == null || !state.getProperties().containsKey(property)) rotation = 0; else { EnumFacing direction = state.getValue(property); rotation = EnumFacingUtils.getRotationCount(direction); } } public int getRotation() { return rotation; } public void setBulkProcess(boolean bulkPlace, boolean bulkBreak) { this.bulkPlace = bulkPlace; this.bulkBreak = bulkBreak; } public boolean isBulkPlace() { return bulkPlace; } public boolean isBulkBreak() { return bulkBreak; } public boolean isFromMultiblock(World world, BlockPos pos) { BlockPos origin = getOrigin(world, pos); if (origin == null) return false; IBlockState state = world.getBlockState(origin); setRotation(state); for (MBlockState mstate : this) { mstate = mstate.rotate(rotation).offset(pos); if (mstate.getPos().equals(pos)) return true; } return false; } public MBlockState getState(BlockPos pos) { pos = BlockPosUtils.rotate(pos, 4 - rotation); return states.get(pos); } public boolean canPlaceBlockAt(World world, BlockPos pos, IBlockState state, boolean placeOrigin) { setRotation(state); for (MBlockState mstate : this) { mstate = mstate.rotate(rotation).offset(pos); if ((!mstate.getPos().equals(pos) || placeOrigin) && !world.getBlockState(mstate.getPos()).getBlock().isReplaceable(world, mstate.getPos())) return false; } return true; } public void placeBlocks(World world, BlockPos pos, IBlockState state, boolean placeOrigin) { setRotation(state); for (MBlockState mstate : this) { mstate = mstate.rotate(rotation).offset(pos); if (!mstate.getPos().equals(pos) || placeOrigin) { BlockDataHandler.setData(ORIGIN_BLOCK_DATA, world, mstate.getPos(), pos); mstate.placeBlock(world, 2); } } BlockDataHandler.setData(ORIGIN_BLOCK_DATA, world, pos, pos); } public void breakBlocks(World world, BlockPos pos, IBlockState state) { BlockPos origin = getOrigin(world, pos); if (origin == null) { world.setBlockToAir(pos); return; } if (!pos.equals(origin)) { breakBlocks(world, origin, world.getBlockState(origin)); return; } BlockDataHandler.removeData(ORIGIN_BLOCK_DATA, world, origin); setRotation(state); for (MBlockState mstate : this) { mstate = mstate.rotate(rotation).offset(origin); if (mstate.matchesWorld(world)) { mstate.breakBlock(world, 2); BlockDataHandler.removeData(ORIGIN_BLOCK_DATA, world, mstate.getPos()); } } } public void setOriginData(World world, BlockPos pos, IBlockState state) { setRotation(state); for (MBlockState mstate : this) { mstate = mstate.rotate(rotation).offset(pos); BlockDataHandler.setData(ORIGIN_BLOCK_DATA, world, mstate.getPos(), pos); } BlockDataHandler.setData(ORIGIN_BLOCK_DATA, world, pos, pos); } public boolean isComplete(World world, BlockPos pos) { return isComplete(world, pos, null); } public boolean isComplete(World world, BlockPos pos, MBlockState newState) { setRotation(world.getBlockState(pos)); MultiBlockAccess mba = new MultiBlockAccess(this, world); for (MBlockState mstate : this) { mstate = new MBlockState(mba, mstate.getPos())/*.rotate(rotation)*/.offset(pos); boolean matches = mstate.matchesWorld(world); if (!matches) mstate.matchesWorld(world); if (!matches && (newState == null || !mstate.equals(newState))) return false; } return true; } @Override public Iterator<MBlockState> iterator() { return states.values().iterator(); } protected abstract void buildStates(); public static BlockPos getOrigin(IBlockAccess world, BlockPos pos) { BlockPos origin = BlockDataHandler.getData(ORIGIN_BLOCK_DATA, world, pos); if (origin != null && IComponent.getComponent(MultiBlockComponent.class, world.getBlockState(origin).getBlock()) == null) { origin = null; BlockDataHandler.removeData(ORIGIN_BLOCK_DATA, world, pos); } return world != null && pos != null ? origin : null; } public static boolean isOrigin(IBlockAccess world, BlockPos pos) { return world != null && pos != null && pos.equals(getOrigin(world, pos)); } }
src/main/java/net/malisis/core/util/multiblock/MultiBlock.java
/* * The MIT License (MIT) * * Copyright (c) 2014 Ordinastie * * 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 net.malisis.core.util.multiblock; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import net.malisis.core.MalisisCore; import net.malisis.core.block.IComponent; import net.malisis.core.block.component.DirectionalComponent; import net.malisis.core.registry.AutoLoad; import net.malisis.core.util.BlockPosUtils; import net.malisis.core.util.EnumFacingUtils; import net.malisis.core.util.MBlockState; import net.malisis.core.util.blockdata.BlockDataHandler; import net.minecraft.block.properties.PropertyDirection; import net.minecraft.block.state.IBlockState; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; /** * @author Ordinastie * */ @AutoLoad public abstract class MultiBlock implements Iterable<MBlockState> { public static String ORIGIN_BLOCK_DATA = MalisisCore.modid + ":multiBlockOrigin"; static { BlockDataHandler.registerBlockData(ORIGIN_BLOCK_DATA, BlockPosUtils::fromBytes, BlockPosUtils::toBytes); } protected Map<BlockPos, MBlockState> states = new HashMap<>(); protected BlockPos offset = BlockPos.ORIGIN; protected PropertyDirection property = DirectionalComponent.HORIZONTAL; private int rotation; private boolean bulkPlace; private boolean bulkBreak; public void setOffset(BlockPos offset) { this.offset = offset; buildStates(); } public void setPropertyDirection(PropertyDirection property) { this.property = property; } public void setRotation(IBlockState state) { if (state == null || !state.getProperties().containsKey(property)) rotation = 0; else { EnumFacing direction = state.getValue(property); rotation = EnumFacingUtils.getRotationCount(direction); } } public int getRotation() { return rotation; } public void setBulkProcess(boolean bulkPlace, boolean bulkBreak) { this.bulkPlace = bulkPlace; this.bulkBreak = bulkBreak; } public boolean isBulkPlace() { return bulkPlace; } public boolean isBulkBreak() { return bulkBreak; } public boolean isFromMultiblock(World world, BlockPos pos) { BlockPos origin = getOrigin(world, pos); if (origin == null) return false; IBlockState state = world.getBlockState(origin); setRotation(state); for (MBlockState mstate : this) { mstate = mstate.rotate(rotation).offset(pos); if (mstate.getPos().equals(pos)) return true; } return false; } public MBlockState getState(BlockPos pos) { pos = BlockPosUtils.rotate(pos, 4 - rotation); return states.get(pos); } public boolean canPlaceBlockAt(World world, BlockPos pos, IBlockState state, boolean placeOrigin) { setRotation(state); for (MBlockState mstate : this) { mstate = mstate.rotate(rotation).offset(pos); if ((!mstate.getPos().equals(pos) || placeOrigin) && !world.getBlockState(mstate.getPos()).getBlock().isReplaceable(world, mstate.getPos())) return false; } return true; } public void placeBlocks(World world, BlockPos pos, IBlockState state, boolean placeOrigin) { setRotation(state); for (MBlockState mstate : this) { mstate = mstate.rotate(rotation).offset(pos); if (!mstate.getPos().equals(pos) || placeOrigin) { BlockDataHandler.setData(ORIGIN_BLOCK_DATA, world, mstate.getPos(), pos); mstate.placeBlock(world, 2); } } BlockDataHandler.setData(ORIGIN_BLOCK_DATA, world, pos, pos); } public void breakBlocks(World world, BlockPos pos, IBlockState state) { BlockPos origin = getOrigin(world, pos); if (origin == null) { world.setBlockToAir(pos); return; } if (!pos.equals(origin)) { breakBlocks(world, origin, world.getBlockState(origin)); return; } BlockDataHandler.removeData(ORIGIN_BLOCK_DATA, world, origin); setRotation(state); for (MBlockState mstate : this) { mstate = mstate.rotate(rotation).offset(origin); if (mstate.matchesWorld(world)) { mstate.breakBlock(world, 2); BlockDataHandler.removeData(ORIGIN_BLOCK_DATA, world, mstate.getPos()); } } } public boolean isComplete(World world, BlockPos pos) { return isComplete(world, pos, null); } public boolean isComplete(World world, BlockPos pos, MBlockState newState) { setRotation(world.getBlockState(pos)); MultiBlockAccess mba = new MultiBlockAccess(this, world); for (MBlockState mstate : this) { mstate = new MBlockState(mba, mstate.getPos())/*.rotate(rotation)*/.offset(pos); boolean matches = mstate.matchesWorld(world); if (!matches) mstate.matchesWorld(world); if (!matches && (newState == null || !mstate.equals(newState))) return false; } return true; } @Override public Iterator<MBlockState> iterator() { return states.values().iterator(); } protected abstract void buildStates(); public static void registerBlockData() { } public static BlockPos getOrigin(IBlockAccess world, BlockPos pos) { BlockPos origin = BlockDataHandler.getData(ORIGIN_BLOCK_DATA, world, pos); if (origin != null && IComponent.getComponent(MultiBlockComponent.class, world.getBlockState(origin).getBlock()) == null) { origin = null; BlockDataHandler.removeData(ORIGIN_BLOCK_DATA, world, pos); } return world != null && pos != null ? origin : null; } public static boolean isOrigin(IBlockAccess world, BlockPos pos) { return world != null && pos != null && pos.equals(getOrigin(world, pos)); } }
Added setOriginData()
src/main/java/net/malisis/core/util/multiblock/MultiBlock.java
Added setOriginData()
<ide><path>rc/main/java/net/malisis/core/util/multiblock/MultiBlock.java <ide> } <ide> } <ide> <add> public void setOriginData(World world, BlockPos pos, IBlockState state) <add> { <add> setRotation(state); <add> for (MBlockState mstate : this) <add> { <add> mstate = mstate.rotate(rotation).offset(pos); <add> BlockDataHandler.setData(ORIGIN_BLOCK_DATA, world, mstate.getPos(), pos); <add> } <add> BlockDataHandler.setData(ORIGIN_BLOCK_DATA, world, pos, pos); <add> } <add> <ide> public boolean isComplete(World world, BlockPos pos) <ide> { <ide> return isComplete(world, pos, null); <ide> <ide> protected abstract void buildStates(); <ide> <del> public static void registerBlockData() <del> { <del> <del> } <del> <ide> public static BlockPos getOrigin(IBlockAccess world, BlockPos pos) <ide> { <ide> BlockPos origin = BlockDataHandler.getData(ORIGIN_BLOCK_DATA, world, pos);
Java
apache-2.0
23b46b85197ab22b8f4eb9688143ed7b052b353e
0
manifold-systems/manifold,manifold-systems/manifold,manifold-systems/manifold
/* * Copyright (c) 2020 - Manifold Systems LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 manifold.api.json; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import abc.Dummy; import spark.Spark; import static org.junit.Assert.assertEquals; public class RequesterTest { @BeforeClass public static void init() { TestServer.main(new String[0]); Spark.awaitInitialization(); } @AfterClass public static void destroy() { TestServer.stop(); } @Test public void httpPostRequestWithParams() { Requester<Dummy> req = Dummy.request( "http://localhost:4567/" ) .withParam( "foo", "bar" ) .withParam( "abc", "8" ); Object queryString = req.postOne( "testPost_QueryString", Dummy.create(), Requester.Format.Text ); assertEquals( "foo=bar&abc=8", queryString ); } @Test public void httpGetRequestWithParams() { Requester<Dummy> req = Dummy.request( "http://localhost:4567/" ) .withParam( "foo", "bar" ) .withParam( "abc", "8" ); Object queryString = req.getOne( "testGet_QueryString", Dummy.create(), Requester.Format.Text ); assertEquals( "foo=bar&abc=8", queryString ); } @Test public void httpPostRequestWithParameterizedUrlSuffixWithParams() { Requester<Dummy> req = Dummy.request( "http://localhost:4567/" ) .withParam( "foo", "bar" ) .withParam( "abc", "8" ); Object queryString = req.postOne( "testPost_QueryString?firstParam=firstValue", Dummy.create(), Requester.Format.Text ); assertEquals( "firstParam=firstValue&foo=bar&abc=8", queryString ); } @Test public void httpGetRequestWithParameterizedUrlSuffixWithParams() { Requester<Dummy> req = Dummy.request( "http://localhost:4567/" ) .withParam( "foo", "bar" ) .withParam( "abc", "8" ); Object queryString = req.getOne( "testGet_QueryString?firstParam=firstValue", Dummy.create(), Requester.Format.Text ); assertEquals( "firstParam=firstValue&foo=bar&abc=8", queryString ); } }
manifold-deps-parent/manifold-json-test/src/test/java/manifold/api/json/RequesterTest.java
/* * Copyright (c) 2020 - Manifold Systems LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 manifold.api.json; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import abc.Dummy; import static org.junit.Assert.assertEquals; public class RequesterTest { @BeforeClass public static void init() { TestServer.main(new String[0]); } @AfterClass public static void destroy() { TestServer.stop(); } @Test public void httpPostRequestWithParams() { Requester<Dummy> req = Dummy.request( "http://localhost:4567/" ) .withParam( "foo", "bar" ) .withParam( "abc", "8" ); Object queryString = req.postOne( "testPost_QueryString", Dummy.create(), Requester.Format.Text ); assertEquals( "foo=bar&abc=8", queryString ); } @Test public void httpGetRequestWithParams() { Requester<Dummy> req = Dummy.request( "http://localhost:4567/" ) .withParam( "foo", "bar" ) .withParam( "abc", "8" ); Object queryString = req.getOne( "testGet_QueryString", Dummy.create(), Requester.Format.Text ); assertEquals( "foo=bar&abc=8", queryString ); } @Test public void httpPostRequestWithParameterizedUrlSuffixWithParams() { Requester<Dummy> req = Dummy.request( "http://localhost:4567/" ) .withParam( "foo", "bar" ) .withParam( "abc", "8" ); Object queryString = req.postOne( "testPost_QueryString?firstParam=firstValue", Dummy.create(), Requester.Format.Text ); assertEquals( "firstParam=firstValue&foo=bar&abc=8", queryString ); } @Test public void httpGetRequestWithParameterizedUrlSuffixWithParams() { Requester<Dummy> req = Dummy.request( "http://localhost:4567/" ) .withParam( "foo", "bar" ) .withParam( "abc", "8" ); Object queryString = req.getOne( "testGet_QueryString?firstParam=firstValue", Dummy.create(), Requester.Format.Text ); assertEquals( "firstParam=firstValue&foo=bar&abc=8", queryString ); } }
fix test breaks on CircleCI, wait for Spark server to initialize before tests run
manifold-deps-parent/manifold-json-test/src/test/java/manifold/api/json/RequesterTest.java
fix test breaks on CircleCI, wait for Spark server to initialize before tests run
<ide><path>anifold-deps-parent/manifold-json-test/src/test/java/manifold/api/json/RequesterTest.java <ide> import org.junit.Test; <ide> <ide> import abc.Dummy; <add>import spark.Spark; <ide> <ide> import static org.junit.Assert.assertEquals; <ide> <ide> public class RequesterTest <ide> { <ide> @BeforeClass <del> public static void init() { <add> public static void init() <add> { <ide> TestServer.main(new String[0]); <add> Spark.awaitInitialization(); <ide> } <ide> <ide> @AfterClass
Java
apache-2.0
2713af81680afccc44e8221ee2013bec4a576f2c
0
tingletech/jena-joseki,tingletech/jena-joseki,tingletech/jena-joseki
/* * (c) Copyright 2005, 2006 Hewlett-Packard Development Company, LP * All rights reserved. * [See end of file] */ package org.joseki.processors; import java.util.Iterator; import java.util.List; import com.hp.hpl.jena.query.*; import com.hp.hpl.jena.rdf.model.*; import com.hp.hpl.jena.shared.JenaException; import com.hp.hpl.jena.shared.NotFoundException; import com.hp.hpl.jena.shared.QueryStageException; import com.hp.hpl.jena.util.FileManager; import org.apache.commons.logging.*; import org.joseki.*; import org.joseki.module.Loadable; import org.joseki.util.GraphUtils; public class SPARQL extends QueryCom implements Loadable { // TODO Refactor into the stages of a query private static Log log = LogFactory.getLog(SPARQL.class) ; static final Property allowDatasetDescP = ResourceFactory.createProperty(JosekiVocab.getURI(), "allowExplicitDataset") ; static final Property allowWebLoadingP = ResourceFactory.createProperty(JosekiVocab.getURI(), "allowWebLoading") ; static private Model m = ModelFactory.createDefaultModel() ; static final Literal XSD_TRUE = m.createTypedLiteral(true) ; static final Literal XSD_FALSE = m.createTypedLiteral(false) ; public static final String P_QUERY = "query" ; public static final String P_QUERY_REF = "query-uri" ; public static final String P_NAMED_GRAPH = "named-graph-uri" ; public static final String P_DEFAULT_GRAPH = "default-graph-uri" ; protected boolean allowDatasetDesc = false ; protected boolean allowWebLoading = false ; protected int maxTriples = 10000 ; protected FileManager fileManager ; public SPARQL() { } public void init(Resource service, Resource implementation) { log.info("SPARQL processor") ; fileManager = new FileManager() ; //fileManager = FileManager.get() ; // Needed for DAWG tests - but why? // Only know how to handle http URLs fileManager.addLocatorURL() ; if ( service.hasProperty(allowDatasetDescP, XSD_TRUE) ) allowDatasetDesc = true ; if ( service.hasProperty(allowWebLoadingP, XSD_TRUE) ) allowWebLoading = true ; log.info("Dataset description: "+allowDatasetDesc+" // Web loading: "+allowWebLoading) ; } public void execQuery(Request request, Response response, DatasetDesc datasetDesc) throws QueryExecutionException { execQueryProtected(request, response, datasetDesc) ; } public void execQueryProtected(Request request, Response response, DatasetDesc datasetDesc) throws QueryExecutionException { try { execQueryWorker(request, response, datasetDesc) ; } catch (QueryExecutionException qEx) { throw qEx; } catch (QueryException qEx) { log.info("Query execution error: "+qEx) ; QueryExecutionException qExEx = new QueryExecutionException(ReturnCodes.rcQueryExecutionFailure, qEx.getMessage()) ; throw qExEx ; } catch (NotFoundException ex) { // Trouble loading data log.info(ex.getMessage()) ; QueryExecutionException qExEx = new QueryExecutionException(ReturnCodes.rcResourceNotFound, ex.getMessage()) ; throw qExEx ; } catch (QueryStageException ex) { // Something nasty happened log.warn("QueryStageException: "+ex.getMessage(), ex) ; QueryExecutionException qExEx = new QueryExecutionException(ReturnCodes.rcInternalError, ex.getMessage()) ; throw qExEx ; } catch (JenaException ex) { log.info("JenaException: "+ex.getMessage()) ; QueryExecutionException qExEx = new QueryExecutionException(ReturnCodes.rcArgumentUnreadable, ex.getMessage()) ; throw qExEx ; } catch (Throwable ex) { // Attempt to catch anything log.info("Throwable: "+ex.getMessage()) ; QueryExecutionException qExEx = new QueryExecutionException(ReturnCodes.rcInternalError, ex.getMessage()) ; throw qExEx ; } } private void execQueryWorker(Request request, Response response, DatasetDesc datasetDesc) throws QueryExecutionException { //log.info("Request: "+request.paramsAsString()) ; String queryString = null ; if ( request.containsParam(P_QUERY) ) { queryString = request.getParam(P_QUERY) ; if (queryString == null ) { log.debug("No query argument (but query parameter exists)") ; throw new JosekiServerException("Query string is null") ; } } if ( request.containsParam(P_QUERY_REF) ) { String queryURI = request.getParam(P_QUERY_REF) ; if ( queryURI == null ) { log.debug("No query reference argument (but query parameter exists)") ; throw new JosekiServerException("Query reference is null") ; } queryString = getRemoteString(queryURI) ; } if ( queryString == null ) { log.debug("No query argument") ; throw new QueryExecutionException(ReturnCodes.rcQueryExecutionFailure, "No query string"); } if ( queryString.equals("") ) { log.debug("Empty query string") ; throw new QueryExecutionException(ReturnCodes.rcQueryExecutionFailure, "Empty query string"); } // ---- Query String queryStringLog = formatForLog(queryString) ; log.info("Query: "+queryStringLog) ; Query query = null ; try { // NB syntax is ARQ (a superset of SPARQL) query = QueryFactory.create(queryString, Syntax.syntaxARQ) ; } catch (QueryException ex) { // TODO Enable errors to be sent as body // response.setError(ExecutionError.rcQueryParseFailure) // OutputString out = response.getOutputStream() ; // out.write(something meaning full) String tmp = queryString +"\n\r" + ex.getMessage() ; throw new QueryExecutionException(ReturnCodes.rcQueryParseFailure, "Parse error: \n"+tmp) ; } catch (Throwable thrown) { log.info("Query unknown error during parsing: "+queryStringLog, thrown) ; throw new QueryExecutionException(ReturnCodes.rcQueryParseFailure, "Unknown Parse error") ; } // Check arguments if ( ! allowDatasetDesc ) { // Restrict to service dataset only. if ( datasetInProtocol(request) ) throw new QueryExecutionException(ReturnCodes.rcArgumentError, "This service does not allow the dataset to be specified in the protocol request") ; if ( query.hasDatasetDescription() ) throw new QueryExecutionException(ReturnCodes.rcArgumentError, "This service does not allow the dataset to be specified in the query") ; } // ---- Dataset Dataset dataset = datasetFromProtocol(request) ; boolean useQueryDesc = false ; if ( dataset == null ) { // No dataset in protocol if ( query.hasDatasetDescription() ) useQueryDesc = true ; // If in query, then the query engine will do the loading. } // Use the service dataset description if // not in query and not in protocol. if ( !useQueryDesc && dataset == null ) { if ( datasetDesc != null ) dataset = datasetDesc.getDataset() ; } if ( !useQueryDesc && dataset == null ) throw new QueryExecutionException(ReturnCodes.rcQueryExecutionFailure, "No datatset given") ; QueryExecution qexec = null ; if ( useQueryDesc ) qexec = QueryExecutionFactory.create(query) ; else qexec = QueryExecutionFactory.create(query, dataset) ; if ( query.hasDatasetDescription() ) qexec = QueryExecutionFactory.create(query) ; else qexec = QueryExecutionFactory.create(query, dataset) ; response.setCallback(new QueryExecutionClose(qexec)) ; if ( query.isSelectType() ) { response.setResultSet(qexec.execSelect()) ; log.info("OK/select: "+queryStringLog) ; return ; } if ( query.isConstructType() ) { Model model = qexec.execConstruct() ; response.setModel(model) ; log.info("OK/construct: "+queryStringLog) ; return ; } if ( query.isDescribeType() ) { Model model = qexec.execDescribe() ; response.setModel(model) ; log.info("OK/describe: "+queryStringLog) ; return ; } if ( query.isAskType() ) { boolean b = qexec.execAsk() ; response.setBoolean(b) ; log.info("OK/ask: "+queryStringLog) ; return ; } log.warn("Unknown query type - "+queryStringLog) ; } private String formatForLog(String queryString) { String tmp = queryString ; tmp = tmp.replace('\n', ' ') ; tmp = tmp.replace('\r', ' ') ; return tmp ; } private boolean datasetInProtocol(Request request) { String d = request.getParam(P_DEFAULT_GRAPH) ; if ( d != null && !d.equals("") ) return true ; List n = request.getParams(P_NAMED_GRAPH) ; if ( n != null && n.size() > 0 ) return true ; return false ; } protected Dataset datasetFromProtocol(Request request) throws QueryExecutionException { try { List graphURLs = request.getParams(P_DEFAULT_GRAPH) ; List namedGraphs = request.getParams(P_NAMED_GRAPH) ; graphURLs = removeEmptyValues(graphURLs) ; namedGraphs = removeEmptyValues(namedGraphs) ; if ( graphURLs.size() == 0 && namedGraphs.size() == 0 ) return null ; DataSource dataset = null ; // TODO Refactor: get names and call DatasetUtils.createDatasetGraph // if ( graphURL != null && request.getBaseURI() != null ) // graphURL = RelURI.resolve(graphURL, request.getBaseURI()) ; // Look in cache for loaded graphs!! if ( graphURLs != null ) { if ( dataset == null ) dataset = DatasetFactory.create() ; Model model = ModelFactory.createDefaultModel() ; for ( Iterator iter = graphURLs.iterator() ; iter.hasNext() ; ) { String uri = (String)iter.next() ; if ( uri == null ) { log.warn("Null "+P_DEFAULT_GRAPH+ " (ignored)") ; continue ; } if ( uri.equals("") ) { log.warn("Empty "+P_DEFAULT_GRAPH+ " (ignored)") ; continue ; } try { GraphUtils.loadModel(model, uri, maxTriples) ; log.info("Load (default) "+uri) ; } catch (Exception ex) { log.info("Failed to load (default) "+uri+" : "+ex.getMessage()) ; throw new QueryExecutionException( ReturnCodes.rcArgumentUnreadable, "Failed to load URL "+uri) ; } } dataset.setDefaultModel(model) ; } if ( namedGraphs != null ) { if ( dataset == null ) dataset = DatasetFactory.create() ; for ( Iterator iter = namedGraphs.iterator() ; iter.hasNext() ; ) { String uri = (String)iter.next() ; if ( uri == null ) { log.warn("Null "+P_NAMED_GRAPH+ " (ignored)") ; continue ; } if ( uri.equals("") ) { log.warn("Empty "+P_NAMED_GRAPH+ " (ignored)") ; continue ; } try { Model model = fileManager.loadModel(uri) ; log.info("Load (named) "+uri) ; dataset.addNamedModel(uri, model) ; } catch (Exception ex) { log.info("Failer to load (named) "+uri+" : "+ex.getMessage()) ; throw new QueryExecutionException( ReturnCodes.rcArgumentUnreadable, "Failed to load URL "+uri) ; } } } return dataset ; } catch (Exception ex) { log.info("SPARQL parameter error",ex) ; throw new QueryExecutionException( ReturnCodes.rcArgumentError, "Parameter error"); } } private List removeEmptyValues(List strList) { for ( Iterator iter = strList.iterator() ; iter.hasNext(); ) { String v = (String)iter.next(); if ( v.equals("") ) iter.remove() ; } return strList ; } /** * @param queryURI * @return */ private String getRemoteString(String queryURI) { return FileManager.get().readWholeFileAsUTF8(queryURI) ; } } /* * (c) Copyright 2005, 2006 Hewlett-Packard Development Company, LP * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. */
src/org/joseki/processors/SPARQL.java
/* * (c) Copyright 2005, 2006 Hewlett-Packard Development Company, LP * All rights reserved. * [See end of file] */ package org.joseki.processors; import java.util.Iterator; import java.util.List; import com.hp.hpl.jena.query.*; import com.hp.hpl.jena.rdf.model.*; import com.hp.hpl.jena.shared.JenaException; import com.hp.hpl.jena.shared.NotFoundException; import com.hp.hpl.jena.shared.QueryStageException; import com.hp.hpl.jena.util.FileManager; import org.apache.commons.logging.*; import org.joseki.*; import org.joseki.module.Loadable; import org.joseki.util.GraphUtils; public class SPARQL extends QueryCom implements Loadable { // TODO Refactor into the stages of a query private static Log log = LogFactory.getLog(SPARQL.class) ; static final Property allowDatasetDescP = ResourceFactory.createProperty(JosekiVocab.getURI(), "allowExplicitDataset") ; static final Property allowWebLoadingP = ResourceFactory.createProperty(JosekiVocab.getURI(), "allowWebLoading") ; static private Model m = ModelFactory.createDefaultModel() ; static final Literal XSD_TRUE = m.createTypedLiteral(true) ; static final Literal XSD_FALSE = m.createTypedLiteral(false) ; public static final String P_QUERY = "query" ; public static final String P_QUERY_REF = "query-uri" ; public static final String P_NAMED_GRAPH = "named-graph-uri" ; public static final String P_DEFAULT_GRAPH = "default-graph-uri" ; protected boolean allowDatasetDesc = false ; protected boolean allowWebLoading = false ; protected int maxTriples = 10000 ; protected FileManager fileManager ; public SPARQL() { } public void init(Resource service, Resource implementation) { log.info("SPARQL processor") ; fileManager = new FileManager() ; //fileManager = FileManager.get() ; // Needed for DAWG tests - but why? // Only know how to handle http URLs fileManager.addLocatorURL() ; if ( service.hasProperty(allowDatasetDescP, XSD_TRUE) ) allowDatasetDesc = true ; if ( service.hasProperty(allowWebLoadingP, XSD_TRUE) ) allowWebLoading = true ; log.info("Dataset description: "+allowDatasetDesc+" // Web loading: "+allowWebLoading) ; } public void execQuery(Request request, Response response, DatasetDesc datasetDesc) throws QueryExecutionException { execQueryProtected(request, response, datasetDesc) ; } public void execQueryProtected(Request request, Response response, DatasetDesc datasetDesc) throws QueryExecutionException { try { execQueryWorker(request, response, datasetDesc) ; } catch (QueryException qEx) { log.info("Query execution error: "+qEx) ; QueryExecutionException qExEx = new QueryExecutionException(ReturnCodes.rcQueryExecutionFailure, qEx.getMessage()) ; throw qExEx ; } catch (NotFoundException ex) { // Trouble loading data log.info(ex.getMessage()) ; QueryExecutionException qExEx = new QueryExecutionException(ReturnCodes.rcResourceNotFound, ex.getMessage()) ; throw qExEx ; } catch (QueryStageException ex) { // Something nasty happened log.warn("QueryStageException: "+ex.getMessage(), ex) ; QueryExecutionException qExEx = new QueryExecutionException(ReturnCodes.rcInternalError, ex.getMessage()) ; throw qExEx ; } catch (JenaException ex) { log.info("JenaException: "+ex.getMessage()) ; QueryExecutionException qExEx = new QueryExecutionException(ReturnCodes.rcArgumentUnreadable, ex.getMessage()) ; throw qExEx ; } catch (Throwable ex) { // Attempt to catch anything log.info("Throwable: "+ex.getMessage()) ; QueryExecutionException qExEx = new QueryExecutionException(ReturnCodes.rcInternalError, ex.getMessage()) ; throw qExEx ; } } private void execQueryWorker(Request request, Response response, DatasetDesc datasetDesc) throws QueryExecutionException { //log.info("Request: "+request.paramsAsString()) ; String queryString = null ; if ( request.containsParam(P_QUERY) ) { queryString = request.getParam(P_QUERY) ; if (queryString == null ) { log.debug("No query argument (but query parameter exists)") ; throw new JosekiServerException("Query string is null") ; } } if ( request.containsParam(P_QUERY_REF) ) { String queryURI = request.getParam(P_QUERY_REF) ; if ( queryURI == null ) { log.debug("No query reference argument (but query parameter exists)") ; throw new JosekiServerException("Query reference is null") ; } queryString = getRemoteString(queryURI) ; } if ( queryString == null ) { log.debug("No query argument") ; throw new QueryExecutionException(ReturnCodes.rcQueryExecutionFailure, "No query string"); } if ( queryString.equals("") ) { log.debug("Empty query string") ; throw new QueryExecutionException(ReturnCodes.rcQueryExecutionFailure, "Empty query string"); } // ---- Query String queryStringLog = formatForLog(queryString) ; log.info("Query: "+queryStringLog) ; Query query = null ; try { // NB syntax is ARQ (a superset of SPARQL) query = QueryFactory.create(queryString, Syntax.syntaxARQ) ; } catch (QueryException ex) { // TODO Enable errors to be sent as body // response.setError(ExecutionError.rcQueryParseFailure) // OutputString out = response.getOutputStream() ; // out.write(something meaning full) String tmp = queryString +"\n\r" + ex.getMessage() ; throw new QueryExecutionException(ReturnCodes.rcQueryParseFailure, "Parse error: \n"+tmp) ; } catch (Throwable thrown) { log.info("Query unknown error during parsing: "+queryStringLog, thrown) ; throw new QueryExecutionException(ReturnCodes.rcQueryParseFailure, "Unknown Parse error") ; } // Check arguments if ( ! allowDatasetDesc ) { // Restrict to service dataset only. if ( datasetInProtocol(request) ) throw new QueryExecutionException(ReturnCodes.rcArgumentError, "This service does not allow the dataset to be specified in the protocol request") ; if ( query.hasDatasetDescription() ) throw new QueryExecutionException(ReturnCodes.rcArgumentError, "This service does not allow the dataset to be specified in the query") ; } // ---- Dataset Dataset dataset = datasetFromProtocol(request) ; boolean useQueryDesc = false ; if ( dataset == null ) { // No dataset in protocol if ( query.hasDatasetDescription() ) useQueryDesc = true ; // If in query, then the query engine will do the loading. } // Use the service dataset description if // not in query and not in protocol. if ( !useQueryDesc && dataset == null ) { if ( datasetDesc != null ) dataset = datasetDesc.getDataset() ; } if ( !useQueryDesc && dataset == null ) throw new QueryExecutionException(ReturnCodes.rcQueryExecutionFailure, "No datatset given") ; QueryExecution qexec = null ; if ( useQueryDesc ) qexec = QueryExecutionFactory.create(query) ; else qexec = QueryExecutionFactory.create(query, dataset) ; if ( query.hasDatasetDescription() ) qexec = QueryExecutionFactory.create(query) ; else qexec = QueryExecutionFactory.create(query, dataset) ; response.setCallback(new QueryExecutionClose(qexec)) ; if ( query.isSelectType() ) { response.setResultSet(qexec.execSelect()) ; log.info("OK/select: "+queryStringLog) ; return ; } if ( query.isConstructType() ) { Model model = qexec.execConstruct() ; response.setModel(model) ; log.info("OK/construct: "+queryStringLog) ; return ; } if ( query.isDescribeType() ) { Model model = qexec.execDescribe() ; response.setModel(model) ; log.info("OK/describe: "+queryStringLog) ; return ; } if ( query.isAskType() ) { boolean b = qexec.execAsk() ; response.setBoolean(b) ; log.info("OK/ask: "+queryStringLog) ; return ; } log.warn("Unknown query type - "+queryStringLog) ; } private String formatForLog(String queryString) { String tmp = queryString ; tmp = tmp.replace('\n', ' ') ; tmp = tmp.replace('\r', ' ') ; return tmp ; } private boolean datasetInProtocol(Request request) { String d = request.getParam(P_DEFAULT_GRAPH) ; if ( d != null && !d.equals("") ) return true ; List n = request.getParams(P_NAMED_GRAPH) ; if ( n != null && n.size() > 0 ) return true ; return false ; } protected Dataset datasetFromProtocol(Request request) throws QueryExecutionException { try { List graphURLs = request.getParams(P_DEFAULT_GRAPH) ; List namedGraphs = request.getParams(P_NAMED_GRAPH) ; if ( graphURLs.size() == 0 && namedGraphs.size() == 0 ) return null ; DataSource dataset = null ; // TODO Refactor: get names and call DatasetUtils.createDatasetGraph // if ( graphURL != null && request.getBaseURI() != null ) // graphURL = RelURI.resolve(graphURL, request.getBaseURI()) ; // Look in cache for loaded graphs!! if ( graphURLs != null ) { if ( dataset == null ) dataset = DatasetFactory.create() ; Model model = ModelFactory.createDefaultModel() ; for ( Iterator iter = graphURLs.iterator() ; iter.hasNext() ; ) { String uri = (String)iter.next() ; if ( uri == null ) { log.warn("Null "+P_DEFAULT_GRAPH+ " (ignored)") ; continue ; } if ( uri.equals("") ) { log.warn("Empty "+P_DEFAULT_GRAPH+ " (ignored)") ; continue ; } try { GraphUtils.loadModel(model, uri, maxTriples) ; log.info("Load (default) "+uri) ; } catch (Exception ex) { log.info("Failed to load (default) "+uri+" : "+ex.getMessage()) ; throw new QueryExecutionException( ReturnCodes.rcArgumentUnreadable, "Failed to load URL "+uri) ; } } dataset.setDefaultModel(model) ; } if ( namedGraphs != null ) { if ( dataset == null ) dataset = DatasetFactory.create() ; for ( Iterator iter = namedGraphs.iterator() ; iter.hasNext() ; ) { String uri = (String)iter.next() ; if ( uri == null ) { log.warn("Null "+P_NAMED_GRAPH+ " (ignored)") ; continue ; } if ( uri.equals("") ) { log.warn("Empty "+P_NAMED_GRAPH+ " (ignored)") ; continue ; } try { Model model = fileManager.loadModel(uri) ; log.info("Load (named) "+uri) ; dataset.addNamedModel(uri, model) ; } catch (Exception ex) { log.info("Failer to load (named) "+uri+" : "+ex.getMessage()) ; throw new QueryExecutionException( ReturnCodes.rcArgumentUnreadable, "Failed to load URL "+uri) ; } } } return dataset ; } catch (Exception ex) { log.info("SPARQL parameter error",ex) ; throw new QueryExecutionException( ReturnCodes.rcArgumentError, "Parameter error"); } } /** * @param queryURI * @return */ private String getRemoteString(String queryURI) { return FileManager.get().readWholeFileAsUTF8(queryURI) ; } } /* * (c) Copyright 2005, 2006 Hewlett-Packard Development Company, LP * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. */
*** empty log message *** git-svn-id: 1a37ca0372d1852423f8ef75091f1e501b9acb0e@1114926 13f79535-47bb-0310-9956-ffa450edef68
src/org/joseki/processors/SPARQL.java
*** empty log message ***
<ide><path>rc/org/joseki/processors/SPARQL.java <ide> try { <ide> execQueryWorker(request, response, datasetDesc) ; <ide> } <add> catch (QueryExecutionException qEx) { throw qEx; } <ide> catch (QueryException qEx) <ide> { <ide> log.info("Query execution error: "+qEx) ; <ide> <ide> List graphURLs = request.getParams(P_DEFAULT_GRAPH) ; <ide> List namedGraphs = request.getParams(P_NAMED_GRAPH) ; <add> <add> graphURLs = removeEmptyValues(graphURLs) ; <add> namedGraphs = removeEmptyValues(namedGraphs) ; <ide> <ide> if ( graphURLs.size() == 0 && namedGraphs.size() == 0 ) <ide> return null ; <ide> <ide> } <ide> <add> private List removeEmptyValues(List strList) <add> { <add> for ( Iterator iter = strList.iterator() ; iter.hasNext(); ) <add> { <add> String v = (String)iter.next(); <add> if ( v.equals("") ) <add> iter.remove() ; <add> } <add> return strList ; <add> } <add> <ide> /** <ide> * @param queryURI <ide> * @return